Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b=. -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 -o /tmp/scan-build-2020-09-17-195756-12974-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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_via_dependent_bases_lookup) << &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 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
438 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
439 if (!IIDecl ||
440 (*Res)->getLocation().getRawEncoding() <
441 IIDecl->getLocation().getRawEncoding())
442 IIDecl = *Res;
443 }
444 }
445
446 if (!IIDecl) {
447 // None of the entities we found is a type, so there is no way
448 // to even assume that the result is a type. In this case, don't
449 // complain about the ambiguity. The parser will either try to
450 // perform this lookup again (e.g., as an object name), which
451 // will produce the ambiguity, or will complain that it expected
452 // a type name.
453 Result.suppressDiagnostics();
454 return nullptr;
455 }
456
457 // We found a type within the ambiguous lookup; diagnose the
458 // ambiguity and then return that type. This might be the right
459 // answer, or it might not be, but it suppresses any attempt to
460 // perform the name lookup again.
461 break;
462
463 case LookupResult::Found:
464 IIDecl = Result.getFoundDecl();
465 break;
466 }
467
468 assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void
> (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 468, __PRETTY_FUNCTION__))
;
469
470 QualType T;
471 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
472 // C++ [class.qual]p2: A lookup that would find the injected-class-name
473 // instead names the constructors of the class, except when naming a class.
474 // This is ill-formed when we're not actually forming a ctor or dtor name.
475 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
476 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
477 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
478 FoundRD->isInjectedClassName() &&
479 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
480 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
481 << &II << /*Type*/1;
482
483 DiagnoseUseOfDecl(IIDecl, NameLoc);
484
485 T = Context.getTypeDeclType(TD);
486 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
487 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
488 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
489 if (!HasTrailingDot)
490 T = Context.getObjCInterfaceType(IDecl);
491 } else if (AllowDeducedTemplate) {
492 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
493 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
494 QualType(), false);
495 }
496
497 if (T.isNull()) {
498 // If it's not plausibly a type, suppress diagnostics.
499 Result.suppressDiagnostics();
500 return nullptr;
501 }
502
503 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
504 // constructor or destructor name (in such a case, the scope specifier
505 // will be attached to the enclosing Expr or Decl node).
506 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
507 !isa<ObjCInterfaceDecl>(IIDecl)) {
508 if (WantNontrivialTypeSourceInfo) {
509 // Construct a type with type-source information.
510 TypeLocBuilder Builder;
511 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
512
513 T = getElaboratedType(ETK_None, *SS, T);
514 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
515 ElabTL.setElaboratedKeywordLoc(SourceLocation());
516 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
517 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
518 } else {
519 T = getElaboratedType(ETK_None, *SS, T);
520 }
521 }
522
523 return ParsedType::make(T);
524}
525
526// Builds a fake NNS for the given decl context.
527static NestedNameSpecifier *
528synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
529 for (;; DC = DC->getLookupParent()) {
530 DC = DC->getPrimaryContext();
531 auto *ND = dyn_cast<NamespaceDecl>(DC);
532 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
533 return NestedNameSpecifier::Create(Context, nullptr, ND);
534 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
535 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
536 RD->getTypeForDecl());
537 else if (isa<TranslationUnitDecl>(DC))
538 return NestedNameSpecifier::GlobalSpecifier(Context);
539 }
540 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 540)
;
541}
542
543/// Find the parent class with dependent bases of the innermost enclosing method
544/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
545/// up allowing unqualified dependent type names at class-level, which MSVC
546/// correctly rejects.
547static const CXXRecordDecl *
548findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
549 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
550 DC = DC->getPrimaryContext();
551 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
552 if (MD->getParent()->hasAnyDependentBases())
553 return MD->getParent();
554 }
555 return nullptr;
556}
557
558ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
559 SourceLocation NameLoc,
560 bool IsTemplateTypeArg) {
561 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 561, __PRETTY_FUNCTION__))
;
562
563 NestedNameSpecifier *NNS = nullptr;
564 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
565 // If we weren't able to parse a default template argument, delay lookup
566 // until instantiation time by making a non-dependent DependentTypeName. We
567 // pretend we saw a NestedNameSpecifier referring to the current scope, and
568 // lookup is retried.
569 // FIXME: This hurts our diagnostic quality, since we get errors like "no
570 // type named 'Foo' in 'current_namespace'" when the user didn't write any
571 // name specifiers.
572 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
573 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
574 } else if (const CXXRecordDecl *RD =
575 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
576 // Build a DependentNameType that will perform lookup into RD at
577 // instantiation time.
578 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
579 RD->getTypeForDecl());
580
581 // Diagnose that this identifier was undeclared, and retry the lookup during
582 // template instantiation.
583 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
584 << RD;
585 } else {
586 // This is not a situation that we should recover from.
587 return ParsedType();
588 }
589
590 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
591
592 // Build type location information. We synthesized the qualifier, so we have
593 // to build a fake NestedNameSpecifierLoc.
594 NestedNameSpecifierLocBuilder NNSLocBuilder;
595 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
596 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
597
598 TypeLocBuilder Builder;
599 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
600 DepTL.setNameLoc(NameLoc);
601 DepTL.setElaboratedKeywordLoc(SourceLocation());
602 DepTL.setQualifierLoc(QualifierLoc);
603 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
604}
605
606/// isTagName() - This method is called *for error recovery purposes only*
607/// to determine if the specified name is a valid tag name ("struct foo"). If
608/// so, this returns the TST for the tag corresponding to it (TST_enum,
609/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
610/// cases in C where the user forgot to specify the tag.
611DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
612 // Do a tag name lookup in this scope.
613 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
614 LookupName(R, S, false);
615 R.suppressDiagnostics();
616 if (R.getResultKind() == LookupResult::Found)
617 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
618 switch (TD->getTagKind()) {
619 case TTK_Struct: return DeclSpec::TST_struct;
620 case TTK_Interface: return DeclSpec::TST_interface;
621 case TTK_Union: return DeclSpec::TST_union;
622 case TTK_Class: return DeclSpec::TST_class;
623 case TTK_Enum: return DeclSpec::TST_enum;
624 }
625 }
626
627 return DeclSpec::TST_unspecified;
628}
629
630/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
631/// if a CXXScopeSpec's type is equal to the type of one of the base classes
632/// then downgrade the missing typename error to a warning.
633/// This is needed for MSVC compatibility; Example:
634/// @code
635/// template<class T> class A {
636/// public:
637/// typedef int TYPE;
638/// };
639/// template<class T> class B : public A<T> {
640/// public:
641/// A<T>::TYPE a; // no typename required because A<T> is a base class.
642/// };
643/// @endcode
644bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
645 if (CurContext->isRecord()) {
646 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
647 return true;
648
649 const Type *Ty = SS->getScopeRep()->getAsType();
650
651 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
652 for (const auto &Base : RD->bases())
653 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
654 return true;
655 return S->isFunctionPrototypeScope();
656 }
657 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
658}
659
660void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
661 SourceLocation IILoc,
662 Scope *S,
663 CXXScopeSpec *SS,
664 ParsedType &SuggestedType,
665 bool IsTemplateName) {
666 // Don't report typename errors for editor placeholders.
667 if (II->isEditorPlaceholder())
668 return;
669 // We don't have anything to suggest (yet).
670 SuggestedType = nullptr;
671
672 // There may have been a typo in the name of the type. Look up typo
673 // results, in case we have something that we can suggest.
674 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
675 /*AllowTemplates=*/IsTemplateName,
676 /*AllowNonTemplates=*/!IsTemplateName);
677 if (TypoCorrection Corrected =
678 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
679 CCC, CTK_ErrorRecovery)) {
680 // FIXME: Support error recovery for the template-name case.
681 bool CanRecover = !IsTemplateName;
682 if (Corrected.isKeyword()) {
683 // We corrected to a keyword.
684 diagnoseTypo(Corrected,
685 PDiag(IsTemplateName ? diag::err_no_template_suggest
686 : diag::err_unknown_typename_suggest)
687 << II);
688 II = Corrected.getCorrectionAsIdentifierInfo();
689 } else {
690 // We found a similarly-named type or interface; suggest that.
691 if (!SS || !SS->isSet()) {
692 diagnoseTypo(Corrected,
693 PDiag(IsTemplateName ? diag::err_no_template_suggest
694 : diag::err_unknown_typename_suggest)
695 << II, CanRecover);
696 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
697 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
698 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
699 II->getName().equals(CorrectedStr);
700 diagnoseTypo(Corrected,
701 PDiag(IsTemplateName
702 ? diag::err_no_member_template_suggest
703 : diag::err_unknown_nested_typename_suggest)
704 << II << DC << DroppedSpecifier << SS->getRange(),
705 CanRecover);
706 } else {
707 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 707)
;
708 }
709
710 if (!CanRecover)
711 return;
712
713 CXXScopeSpec tmpSS;
714 if (Corrected.getCorrectionSpecifier())
715 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
716 SourceRange(IILoc));
717 // FIXME: Support class template argument deduction here.
718 SuggestedType =
719 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
720 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
721 /*IsCtorOrDtorName=*/false,
722 /*WantNontrivialTypeSourceInfo=*/true);
723 }
724 return;
725 }
726
727 if (getLangOpts().CPlusPlus && !IsTemplateName) {
728 // See if II is a class template that the user forgot to pass arguments to.
729 UnqualifiedId Name;
730 Name.setIdentifier(II, IILoc);
731 CXXScopeSpec EmptySS;
732 TemplateTy TemplateResult;
733 bool MemberOfUnknownSpecialization;
734 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
735 Name, nullptr, true, TemplateResult,
736 MemberOfUnknownSpecialization) == TNK_Type_template) {
737 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
738 return;
739 }
740 }
741
742 // FIXME: Should we move the logic that tries to recover from a missing tag
743 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
744
745 if (!SS || (!SS->isSet() && !SS->isInvalid()))
746 Diag(IILoc, IsTemplateName ? diag::err_no_template
747 : diag::err_unknown_typename)
748 << II;
749 else if (DeclContext *DC = computeDeclContext(*SS, false))
750 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
751 : diag::err_typename_nested_not_found)
752 << II << DC << SS->getRange();
753 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
754 SuggestedType =
755 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
756 } else if (isDependentScopeSpecifier(*SS)) {
757 unsigned DiagID = diag::err_typename_missing;
758 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
759 DiagID = diag::ext_typename_missing;
760
761 Diag(SS->getRange().getBegin(), DiagID)
762 << SS->getScopeRep() << II->getName()
763 << SourceRange(SS->getRange().getBegin(), IILoc)
764 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
765 SuggestedType = ActOnTypenameType(S, SourceLocation(),
766 *SS, *II, IILoc).get();
767 } else {
768 assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"
) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 769, __PRETTY_FUNCTION__))
769 "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed"
) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 769, __PRETTY_FUNCTION__))
;
770 }
771}
772
773/// Determine whether the given result set contains either a type name
774/// or
775static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
776 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
777 NextToken.is(tok::less);
778
779 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
780 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
781 return true;
782
783 if (CheckTemplate && isa<TemplateDecl>(*I))
784 return true;
785 }
786
787 return false;
788}
789
790static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
791 Scope *S, CXXScopeSpec &SS,
792 IdentifierInfo *&Name,
793 SourceLocation NameLoc) {
794 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
795 SemaRef.LookupParsedName(R, S, &SS);
796 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
797 StringRef FixItTagName;
798 switch (Tag->getTagKind()) {
799 case TTK_Class:
800 FixItTagName = "class ";
801 break;
802
803 case TTK_Enum:
804 FixItTagName = "enum ";
805 break;
806
807 case TTK_Struct:
808 FixItTagName = "struct ";
809 break;
810
811 case TTK_Interface:
812 FixItTagName = "__interface ";
813 break;
814
815 case TTK_Union:
816 FixItTagName = "union ";
817 break;
818 }
819
820 StringRef TagName = FixItTagName.drop_back();
821 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
822 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
823 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
824
825 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
826 I != IEnd; ++I)
827 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
828 << Name << TagName;
829
830 // Replace lookup results with just the tag decl.
831 Result.clear(Sema::LookupTagName);
832 SemaRef.LookupParsedName(Result, S, &SS);
833 return true;
834 }
835
836 return false;
837}
838
839/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
840static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
841 QualType T, SourceLocation NameLoc) {
842 ASTContext &Context = S.Context;
843
844 TypeLocBuilder Builder;
845 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
846
847 T = S.getElaboratedType(ETK_None, SS, T);
848 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
849 ElabTL.setElaboratedKeywordLoc(SourceLocation());
850 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
851 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
852}
853
854Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
855 IdentifierInfo *&Name,
856 SourceLocation NameLoc,
857 const Token &NextToken,
858 CorrectionCandidateCallback *CCC) {
859 DeclarationNameInfo NameInfo(Name, NameLoc);
860 ObjCMethodDecl *CurMethod = getCurMethodDecl();
861
862 assert(NextToken.isNot(tok::coloncolon) &&((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName"
) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 863, __PRETTY_FUNCTION__))
863 "parse nested name specifiers before calling ClassifyName")((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName"
) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 863, __PRETTY_FUNCTION__))
;
864 if (getLangOpts().CPlusPlus && SS.isSet() &&
865 isCurrentClassName(*Name, S, &SS)) {
866 // Per [class.qual]p2, this names the constructors of SS, not the
867 // injected-class-name. We don't have a classification for that.
868 // There's not much point caching this result, since the parser
869 // will reject it later.
870 return NameClassification::Unknown();
871 }
872
873 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
874 LookupParsedName(Result, S, &SS, !CurMethod);
875
876 if (SS.isInvalid())
877 return NameClassification::Error();
878
879 // For unqualified lookup in a class template in MSVC mode, look into
880 // dependent base classes where the primary class template is known.
881 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
882 if (ParsedType TypeInBase =
883 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
884 return TypeInBase;
885 }
886
887 // Perform lookup for Objective-C instance variables (including automatically
888 // synthesized instance variables), if we're in an Objective-C method.
889 // FIXME: This lookup really, really needs to be folded in to the normal
890 // unqualified lookup mechanism.
891 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
892 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
893 if (Ivar.isInvalid())
894 return NameClassification::Error();
895 if (Ivar.isUsable())
896 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
897
898 // We defer builtin creation until after ivar lookup inside ObjC methods.
899 if (Result.empty())
900 LookupBuiltin(Result);
901 }
902
903 bool SecondTry = false;
904 bool IsFilteredTemplateName = false;
905
906Corrected:
907 switch (Result.getResultKind()) {
908 case LookupResult::NotFound:
909 // If an unqualified-id is followed by a '(', then we have a function
910 // call.
911 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
912 // In C++, this is an ADL-only call.
913 // FIXME: Reference?
914 if (getLangOpts().CPlusPlus)
915 return NameClassification::UndeclaredNonType();
916
917 // C90 6.3.2.2:
918 // If the expression that precedes the parenthesized argument list in a
919 // function call consists solely of an identifier, and if no
920 // declaration is visible for this identifier, the identifier is
921 // implicitly declared exactly as if, in the innermost block containing
922 // the function call, the declaration
923 //
924 // extern int identifier ();
925 //
926 // appeared.
927 //
928 // We also allow this in C99 as an extension.
929 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
930 return NameClassification::NonType(D);
931 }
932
933 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
934 // In C++20 onwards, this could be an ADL-only call to a function
935 // template, and we're required to assume that this is a template name.
936 //
937 // FIXME: Find a way to still do typo correction in this case.
938 TemplateName Template =
939 Context.getAssumedTemplateName(NameInfo.getName());
940 return NameClassification::UndeclaredTemplate(Template);
941 }
942
943 // In C, we first see whether there is a tag type by the same name, in
944 // which case it's likely that the user just forgot to write "enum",
945 // "struct", or "union".
946 if (!getLangOpts().CPlusPlus && !SecondTry &&
947 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
948 break;
949 }
950
951 // Perform typo correction to determine if there is another name that is
952 // close to this name.
953 if (!SecondTry && CCC) {
954 SecondTry = true;
955 if (TypoCorrection Corrected =
956 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
957 &SS, *CCC, CTK_ErrorRecovery)) {
958 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
959 unsigned QualifiedDiag = diag::err_no_member_suggest;
960
961 NamedDecl *FirstDecl = Corrected.getFoundDecl();
962 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
963 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
964 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
965 UnqualifiedDiag = diag::err_no_template_suggest;
966 QualifiedDiag = diag::err_no_member_template_suggest;
967 } else if (UnderlyingFirstDecl &&
968 (isa<TypeDecl>(UnderlyingFirstDecl) ||
969 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
970 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
971 UnqualifiedDiag = diag::err_unknown_typename_suggest;
972 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
973 }
974
975 if (SS.isEmpty()) {
976 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
977 } else {// FIXME: is this even reachable? Test it.
978 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
979 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
980 Name->getName().equals(CorrectedStr);
981 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
982 << Name << computeDeclContext(SS, false)
983 << DroppedSpecifier << SS.getRange());
984 }
985
986 // Update the name, so that the caller has the new name.
987 Name = Corrected.getCorrectionAsIdentifierInfo();
988
989 // Typo correction corrected to a keyword.
990 if (Corrected.isKeyword())
991 return Name;
992
993 // Also update the LookupResult...
994 // FIXME: This should probably go away at some point
995 Result.clear();
996 Result.setLookupName(Corrected.getCorrection());
997 if (FirstDecl)
998 Result.addDecl(FirstDecl);
999
1000 // If we found an Objective-C instance variable, let
1001 // LookupInObjCMethod build the appropriate expression to
1002 // reference the ivar.
1003 // FIXME: This is a gross hack.
1004 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1005 DeclResult R =
1006 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1007 if (R.isInvalid())
1008 return NameClassification::Error();
1009 if (R.isUsable())
1010 return NameClassification::NonType(Ivar);
1011 }
1012
1013 goto Corrected;
1014 }
1015 }
1016
1017 // We failed to correct; just fall through and let the parser deal with it.
1018 Result.suppressDiagnostics();
1019 return NameClassification::Unknown();
1020
1021 case LookupResult::NotFoundInCurrentInstantiation: {
1022 // We performed name lookup into the current instantiation, and there were
1023 // dependent bases, so we treat this result the same way as any other
1024 // dependent nested-name-specifier.
1025
1026 // C++ [temp.res]p2:
1027 // A name used in a template declaration or definition and that is
1028 // dependent on a template-parameter is assumed not to name a type
1029 // unless the applicable name lookup finds a type name or the name is
1030 // qualified by the keyword typename.
1031 //
1032 // FIXME: If the next token is '<', we might want to ask the parser to
1033 // perform some heroics to see if we actually have a
1034 // template-argument-list, which would indicate a missing 'template'
1035 // keyword here.
1036 return NameClassification::DependentNonType();
1037 }
1038
1039 case LookupResult::Found:
1040 case LookupResult::FoundOverloaded:
1041 case LookupResult::FoundUnresolvedValue:
1042 break;
1043
1044 case LookupResult::Ambiguous:
1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1046 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047 /*AllowDependent=*/false)) {
1048 // C++ [temp.local]p3:
1049 // A lookup that finds an injected-class-name (10.2) can result in an
1050 // ambiguity in certain cases (for example, if it is found in more than
1051 // one base class). If all of the injected-class-names that are found
1052 // refer to specializations of the same class template, and if the name
1053 // is followed by a template-argument-list, the reference refers to the
1054 // class template itself and not a specialization thereof, and is not
1055 // ambiguous.
1056 //
1057 // This filtering can make an ambiguous result into an unambiguous one,
1058 // so try again after filtering out template names.
1059 FilterAcceptableTemplateNames(Result);
1060 if (!Result.isAmbiguous()) {
1061 IsFilteredTemplateName = true;
1062 break;
1063 }
1064 }
1065
1066 // Diagnose the ambiguity and return an error.
1067 return NameClassification::Error();
1068 }
1069
1070 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1071 (IsFilteredTemplateName ||
1072 hasAnyAcceptableTemplateNames(
1073 Result, /*AllowFunctionTemplates=*/true,
1074 /*AllowDependent=*/false,
1075 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1076 getLangOpts().CPlusPlus20))) {
1077 // C++ [temp.names]p3:
1078 // After name lookup (3.4) finds that a name is a template-name or that
1079 // an operator-function-id or a literal- operator-id refers to a set of
1080 // overloaded functions any member of which is a function template if
1081 // this is followed by a <, the < is always taken as the delimiter of a
1082 // template-argument-list and never as the less-than operator.
1083 // C++2a [temp.names]p2:
1084 // A name is also considered to refer to a template if it is an
1085 // unqualified-id followed by a < and name lookup finds either one
1086 // or more functions or finds nothing.
1087 if (!IsFilteredTemplateName)
1088 FilterAcceptableTemplateNames(Result);
1089
1090 bool IsFunctionTemplate;
1091 bool IsVarTemplate;
1092 TemplateName Template;
1093 if (Result.end() - Result.begin() > 1) {
1094 IsFunctionTemplate = true;
1095 Template = Context.getOverloadedTemplateName(Result.begin(),
1096 Result.end());
1097 } else if (!Result.empty()) {
1098 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1099 *Result.begin(), /*AllowFunctionTemplates=*/true,
1100 /*AllowDependent=*/false));
1101 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1102 IsVarTemplate = isa<VarTemplateDecl>(TD);
1103
1104 if (SS.isNotEmpty())
1105 Template =
1106 Context.getQualifiedTemplateName(SS.getScopeRep(),
1107 /*TemplateKeyword=*/false, TD);
1108 else
1109 Template = TemplateName(TD);
1110 } else {
1111 // All results were non-template functions. This is a function template
1112 // name.
1113 IsFunctionTemplate = true;
1114 Template = Context.getAssumedTemplateName(NameInfo.getName());
1115 }
1116
1117 if (IsFunctionTemplate) {
1118 // Function templates always go through overload resolution, at which
1119 // point we'll perform the various checks (e.g., accessibility) we need
1120 // to based on which function we selected.
1121 Result.suppressDiagnostics();
1122
1123 return NameClassification::FunctionTemplate(Template);
1124 }
1125
1126 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1127 : NameClassification::TypeTemplate(Template);
1128 }
1129
1130 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1131 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1132 DiagnoseUseOfDecl(Type, NameLoc);
1133 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1134 QualType T = Context.getTypeDeclType(Type);
1135 if (SS.isNotEmpty())
1136 return buildNestedType(*this, SS, T, NameLoc);
1137 return ParsedType::make(T);
1138 }
1139
1140 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1141 if (!Class) {
1142 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1143 if (ObjCCompatibleAliasDecl *Alias =
1144 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1145 Class = Alias->getClassInterface();
1146 }
1147
1148 if (Class) {
1149 DiagnoseUseOfDecl(Class, NameLoc);
1150
1151 if (NextToken.is(tok::period)) {
1152 // Interface. <something> is parsed as a property reference expression.
1153 // Just return "unknown" as a fall-through for now.
1154 Result.suppressDiagnostics();
1155 return NameClassification::Unknown();
1156 }
1157
1158 QualType T = Context.getObjCInterfaceType(Class);
1159 return ParsedType::make(T);
1160 }
1161
1162 if (isa<ConceptDecl>(FirstDecl))
1163 return NameClassification::Concept(
1164 TemplateName(cast<TemplateDecl>(FirstDecl)));
1165
1166 // We can have a type template here if we're classifying a template argument.
1167 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1168 !isa<VarTemplateDecl>(FirstDecl))
1169 return NameClassification::TypeTemplate(
1170 TemplateName(cast<TemplateDecl>(FirstDecl)));
1171
1172 // Check for a tag type hidden by a non-type decl in a few cases where it
1173 // seems likely a type is wanted instead of the non-type that was found.
1174 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1175 if ((NextToken.is(tok::identifier) ||
1176 (NextIsOp &&
1177 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1178 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1179 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1180 DiagnoseUseOfDecl(Type, NameLoc);
1181 QualType T = Context.getTypeDeclType(Type);
1182 if (SS.isNotEmpty())
1183 return buildNestedType(*this, SS, T, NameLoc);
1184 return ParsedType::make(T);
1185 }
1186
1187 // If we already know which single declaration is referenced, just annotate
1188 // that declaration directly. Defer resolving even non-overloaded class
1189 // member accesses, as we need to defer certain access checks until we know
1190 // the context.
1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1193 return NameClassification::NonType(Result.getRepresentativeDecl());
1194
1195 // Otherwise, this is an overload set that we will need to resolve later.
1196 Result.suppressDiagnostics();
1197 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1198 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1199 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1200 Result.begin(), Result.end()));
1201}
1202
1203ExprResult
1204Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1205 SourceLocation NameLoc) {
1206 assert(getLangOpts().CPlusPlus && "ADL-only call in C?")((getLangOpts().CPlusPlus && "ADL-only call in C?") ?
static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1206, __PRETTY_FUNCTION__))
;
1207 CXXScopeSpec SS;
1208 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1209 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1210}
1211
1212ExprResult
1213Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1214 IdentifierInfo *Name,
1215 SourceLocation NameLoc,
1216 bool IsAddressOfOperand) {
1217 DeclarationNameInfo NameInfo(Name, NameLoc);
1218 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1219 NameInfo, IsAddressOfOperand,
1220 /*TemplateArgs=*/nullptr);
1221}
1222
1223ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1224 NamedDecl *Found,
1225 SourceLocation NameLoc,
1226 const Token &NextToken) {
1227 if (getCurMethodDecl() && SS.isEmpty())
1228 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1229 return BuildIvarRefExpr(S, NameLoc, Ivar);
1230
1231 // Reconstruct the lookup result.
1232 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1233 Result.addDecl(Found);
1234 Result.resolveKind();
1235
1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1237 return BuildDeclarationNameExpr(SS, Result, ADL);
1238}
1239
1240ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1241 // For an implicit class member access, transform the result into a member
1242 // access expression if necessary.
1243 auto *ULE = cast<UnresolvedLookupExpr>(E);
1244 if ((*ULE->decls_begin())->isCXXClassMember()) {
1245 CXXScopeSpec SS;
1246 SS.Adopt(ULE->getQualifierLoc());
1247
1248 // Reconstruct the lookup result.
1249 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1250 LookupOrdinaryName);
1251 Result.setNamingClass(ULE->getNamingClass());
1252 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1253 Result.addDecl(*I, I.getAccess());
1254 Result.resolveKind();
1255 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1256 nullptr, S);
1257 }
1258
1259 // Otherwise, this is already in the form we needed, and no further checks
1260 // are necessary.
1261 return ULE;
1262}
1263
1264Sema::TemplateNameKindForDiagnostics
1265Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1266 auto *TD = Name.getAsTemplateDecl();
1267 if (!TD)
1268 return TemplateNameKindForDiagnostics::DependentTemplate;
1269 if (isa<ClassTemplateDecl>(TD))
1270 return TemplateNameKindForDiagnostics::ClassTemplate;
1271 if (isa<FunctionTemplateDecl>(TD))
1272 return TemplateNameKindForDiagnostics::FunctionTemplate;
1273 if (isa<VarTemplateDecl>(TD))
1274 return TemplateNameKindForDiagnostics::VarTemplate;
1275 if (isa<TypeAliasTemplateDecl>(TD))
1276 return TemplateNameKindForDiagnostics::AliasTemplate;
1277 if (isa<TemplateTemplateParmDecl>(TD))
1278 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1279 if (isa<ConceptDecl>(TD))
1280 return TemplateNameKindForDiagnostics::Concept;
1281 return TemplateNameKindForDiagnostics::DependentTemplate;
1282}
1283
1284void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1285 assert(DC->getLexicalParent() == CurContext &&((DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1286, __PRETTY_FUNCTION__))
1286 "The next DeclContext should be lexically contained in the current one.")((DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1286, __PRETTY_FUNCTION__))
;
1287 CurContext = DC;
1288 S->setEntity(DC);
1289}
1290
1291void Sema::PopDeclContext() {
1292 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1292, __PRETTY_FUNCTION__))
;
1293
1294 CurContext = CurContext->getLexicalParent();
1295 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1295, __PRETTY_FUNCTION__))
;
1296}
1297
1298Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1299 Decl *D) {
1300 // Unlike PushDeclContext, the context to which we return is not necessarily
1301 // the containing DC of TD, because the new context will be some pre-existing
1302 // TagDecl definition instead of a fresh one.
1303 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1304 CurContext = cast<TagDecl>(D)->getDefinition();
1305 assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag"
) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1305, __PRETTY_FUNCTION__))
;
1306 // Start lookups from the parent of the current context; we don't want to look
1307 // into the pre-existing complete definition.
1308 S->setEntity(CurContext->getLookupParent());
1309 return Result;
1310}
1311
1312void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1313 CurContext = static_cast<decltype(CurContext)>(Context);
1314}
1315
1316/// EnterDeclaratorContext - Used when we must lookup names in the context
1317/// of a declarator's nested name specifier.
1318///
1319void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1320 // C++0x [basic.lookup.unqual]p13:
1321 // A name used in the definition of a static data member of class
1322 // X (after the qualified-id of the static member) is looked up as
1323 // if the name was used in a member function of X.
1324 // C++0x [basic.lookup.unqual]p14:
1325 // If a variable member of a namespace is defined outside of the
1326 // scope of its namespace then any name used in the definition of
1327 // the variable member (after the declarator-id) is looked up as
1328 // if the definition of the variable member occurred in its
1329 // namespace.
1330 // Both of these imply that we should push a scope whose context
1331 // is the semantic context of the declaration. We can't use
1332 // PushDeclContext here because that context is not necessarily
1333 // lexically contained in the current context. Fortunately,
1334 // the containing scope should have the appropriate information.
1335
1336 assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ?
static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1336, __PRETTY_FUNCTION__))
;
1337
1338#ifndef NDEBUG
1339 Scope *Ancestor = S->getParent();
1340 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1341 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch"
) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1341, __PRETTY_FUNCTION__))
;
1342#endif
1343
1344 CurContext = DC;
1345 S->setEntity(DC);
1346
1347 if (S->getParent()->isTemplateParamScope()) {
1348 // Also set the corresponding entities for all immediately-enclosing
1349 // template parameter scopes.
1350 EnterTemplatedContext(S->getParent(), DC);
1351 }
1352}
1353
1354void Sema::ExitDeclaratorContext(Scope *S) {
1355 assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!"
) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1355, __PRETTY_FUNCTION__))
;
1356
1357 // Switch back to the lexical context. The safety of this is
1358 // enforced by an assert in EnterDeclaratorContext.
1359 Scope *Ancestor = S->getParent();
1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361 CurContext = Ancestor->getEntity();
1362
1363 // We don't need to do anything with the scope, which is going to
1364 // disappear.
1365}
1366
1367void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1368 assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "expected to be initializing a template parameter scope"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1369, __PRETTY_FUNCTION__))
1369 "expected to be initializing a template parameter scope")((S->isTemplateParamScope() && "expected to be initializing a template parameter scope"
) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1369, __PRETTY_FUNCTION__))
;
1370
1371 // C++20 [temp.local]p7:
1372 // In the definition of a member of a class template that appears outside
1373 // of the class template definition, the name of a member of the class
1374 // template hides the name of a template-parameter of any enclosing class
1375 // templates (but not a template-parameter of the member if the member is a
1376 // class or function template).
1377 // C++20 [temp.local]p9:
1378 // In the definition of a class template or in the definition of a member
1379 // of such a template that appears outside of the template definition, for
1380 // each non-dependent base class (13.8.2.1), if the name of the base class
1381 // or the name of a member of the base class is the same as the name of a
1382 // template-parameter, the base class name or member name hides the
1383 // template-parameter name (6.4.10).
1384 //
1385 // This means that a template parameter scope should be searched immediately
1386 // after searching the DeclContext for which it is a template parameter
1387 // scope. For example, for
1388 // template<typename T> template<typename U> template<typename V>
1389 // void N::A<T>::B<U>::f(...)
1390 // we search V then B<U> (and base classes) then U then A<T> (and base
1391 // classes) then T then N then ::.
1392 unsigned ScopeDepth = getTemplateDepth(S);
1393 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1394 DeclContext *SearchDCAfterScope = DC;
1395 for (; DC; DC = DC->getLookupParent()) {
1396 if (const TemplateParameterList *TPL =
1397 cast<Decl>(DC)->getDescribedTemplateParams()) {
1398 unsigned DCDepth = TPL->getDepth() + 1;
1399 if (DCDepth > ScopeDepth)
1400 continue;
1401 if (ScopeDepth == DCDepth)
1402 SearchDCAfterScope = DC = DC->getLookupParent();
1403 break;
1404 }
1405 }
1406 S->setLookupEntity(SearchDCAfterScope);
1407 }
1408}
1409
1410void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1411 // We assume that the caller has already called
1412 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1413 FunctionDecl *FD = D->getAsFunction();
1414 if (!FD)
1415 return;
1416
1417 // Same implementation as PushDeclContext, but enters the context
1418 // from the lexical parent, rather than the top-level class.
1419 assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1420, __PRETTY_FUNCTION__))
1420 "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1420, __PRETTY_FUNCTION__))
;
1421 CurContext = FD;
1422 S->setEntity(CurContext);
1423
1424 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1425 ParmVarDecl *Param = FD->getParamDecl(P);
1426 // If the parameter has an identifier, then add it to the scope
1427 if (Param->getIdentifier()) {
1428 S->AddDecl(Param);
1429 IdResolver.AddDecl(Param);
1430 }
1431 }
1432}
1433
1434void Sema::ActOnExitFunctionContext() {
1435 // Same implementation as PopDeclContext, but returns to the lexical parent,
1436 // rather than the top-level class.
1437 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1437, __PRETTY_FUNCTION__))
;
1438 CurContext = CurContext->getLexicalParent();
1439 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1439, __PRETTY_FUNCTION__))
;
1440}
1441
1442/// Determine whether we allow overloading of the function
1443/// PrevDecl with another declaration.
1444///
1445/// This routine determines whether overloading is possible, not
1446/// whether some new function is actually an overload. It will return
1447/// true in C++ (where we can always provide overloads) or, as an
1448/// extension, in C when the previous function is already an
1449/// overloaded function declaration or has the "overloadable"
1450/// attribute.
1451static bool AllowOverloadingOfFunction(LookupResult &Previous,
1452 ASTContext &Context,
1453 const FunctionDecl *New) {
1454 if (Context.getLangOpts().CPlusPlus)
1455 return true;
1456
1457 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1458 return true;
1459
1460 return Previous.getResultKind() == LookupResult::Found &&
1461 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1462 New->hasAttr<OverloadableAttr>());
1463}
1464
1465/// Add this decl to the scope shadowed decl chains.
1466void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1467 // Move up the scope chain until we find the nearest enclosing
1468 // non-transparent context. The declaration will be introduced into this
1469 // scope.
1470 while (S->getEntity() && S->getEntity()->isTransparentContext())
1471 S = S->getParent();
1472
1473 // Add scoped declarations into their context, so that they can be
1474 // found later. Declarations without a context won't be inserted
1475 // into any context.
1476 if (AddToContext)
1477 CurContext->addDecl(D);
1478
1479 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1480 // are function-local declarations.
1481 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1482 !D->getDeclContext()->getRedeclContext()->Equals(
1483 D->getLexicalDeclContext()->getRedeclContext()) &&
1484 !D->getLexicalDeclContext()->isFunctionOrMethod())
1485 return;
1486
1487 // Template instantiations should also not be pushed into scope.
1488 if (isa<FunctionDecl>(D) &&
1489 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1490 return;
1491
1492 // If this replaces anything in the current scope,
1493 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1494 IEnd = IdResolver.end();
1495 for (; I != IEnd; ++I) {
1496 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1497 S->RemoveDecl(*I);
1498 IdResolver.RemoveDecl(*I);
1499
1500 // Should only need to replace one decl.
1501 break;
1502 }
1503 }
1504
1505 S->AddDecl(D);
1506
1507 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1508 // Implicitly-generated labels may end up getting generated in an order that
1509 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1510 // the label at the appropriate place in the identifier chain.
1511 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1512 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1513 if (IDC == CurContext) {
1514 if (!S->isDeclScope(*I))
1515 continue;
1516 } else if (IDC->Encloses(CurContext))
1517 break;
1518 }
1519
1520 IdResolver.InsertDeclAfter(I, D);
1521 } else {
1522 IdResolver.AddDecl(D);
1523 }
1524}
1525
1526bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1527 bool AllowInlineNamespace) {
1528 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1529}
1530
1531Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1532 DeclContext *TargetDC = DC->getPrimaryContext();
1533 do {
1534 if (DeclContext *ScopeDC = S->getEntity())
1535 if (ScopeDC->getPrimaryContext() == TargetDC)
1536 return S;
1537 } while ((S = S->getParent()));
1538
1539 return nullptr;
1540}
1541
1542static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1543 DeclContext*,
1544 ASTContext&);
1545
1546/// Filters out lookup results that don't fall within the given scope
1547/// as determined by isDeclInScope.
1548void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1549 bool ConsiderLinkage,
1550 bool AllowInlineNamespace) {
1551 LookupResult::Filter F = R.makeFilter();
1552 while (F.hasNext()) {
1553 NamedDecl *D = F.next();
1554
1555 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1556 continue;
1557
1558 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1559 continue;
1560
1561 F.erase();
1562 }
1563
1564 F.done();
1565}
1566
1567/// We've determined that \p New is a redeclaration of \p Old. Check that they
1568/// have compatible owning modules.
1569bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1570 // FIXME: The Modules TS is not clear about how friend declarations are
1571 // to be treated. It's not meaningful to have different owning modules for
1572 // linkage in redeclarations of the same entity, so for now allow the
1573 // redeclaration and change the owning modules to match.
1574 if (New->getFriendObjectKind() &&
11
Calling 'Decl::getFriendObjectKind'
17
Returning from 'Decl::getFriendObjectKind'
19
Taking false branch
1575 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
18
Assuming the condition is false
1576 New->setLocalOwningModule(Old->getOwningModule());
1577 makeMergedDefinitionVisible(New);
1578 return false;
1579 }
1580
1581 Module *NewM = New->getOwningModule();
1582 Module *OldM = Old->getOwningModule();
1583
1584 if (NewM
19.1
'NewM' is null
19.1
'NewM' is null
&& NewM->Kind == Module::PrivateModuleFragment)
1585 NewM = NewM->Parent;
1586 if (OldM
19.2
'OldM' is null
19.2
'OldM' is null
&& OldM->Kind == Module::PrivateModuleFragment)
1587 OldM = OldM->Parent;
1588
1589 if (NewM
19.3
'NewM' is equal to 'OldM'
19.3
'NewM' is equal to 'OldM'
== OldM)
20
Taking true branch
1590 return false;
21
Returning zero, which participates in a condition later
1591
1592 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1593 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1594 if (NewIsModuleInterface || OldIsModuleInterface) {
1595 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1596 // if a declaration of D [...] appears in the purview of a module, all
1597 // other such declarations shall appear in the purview of the same module
1598 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1599 << New
1600 << NewIsModuleInterface
1601 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1602 << OldIsModuleInterface
1603 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1604 Diag(Old->getLocation(), diag::note_previous_declaration);
1605 New->setInvalidDecl();
1606 return true;
1607 }
1608
1609 return false;
1610}
1611
1612static bool isUsingDecl(NamedDecl *D) {
1613 return isa<UsingShadowDecl>(D) ||
1614 isa<UnresolvedUsingTypenameDecl>(D) ||
1615 isa<UnresolvedUsingValueDecl>(D);
1616}
1617
1618/// Removes using shadow declarations from the lookup results.
1619static void RemoveUsingDecls(LookupResult &R) {
1620 LookupResult::Filter F = R.makeFilter();
1621 while (F.hasNext())
1622 if (isUsingDecl(F.next()))
1623 F.erase();
1624
1625 F.done();
1626}
1627
1628/// Check for this common pattern:
1629/// @code
1630/// class S {
1631/// S(const S&); // DO NOT IMPLEMENT
1632/// void operator=(const S&); // DO NOT IMPLEMENT
1633/// };
1634/// @endcode
1635static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1636 // FIXME: Should check for private access too but access is set after we get
1637 // the decl here.
1638 if (D->doesThisDeclarationHaveABody())
1639 return false;
1640
1641 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1642 return CD->isCopyConstructor();
1643 return D->isCopyAssignmentOperator();
1644}
1645
1646// We need this to handle
1647//
1648// typedef struct {
1649// void *foo() { return 0; }
1650// } A;
1651//
1652// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1653// for example. If 'A', foo will have external linkage. If we have '*A',
1654// foo will have no linkage. Since we can't know until we get to the end
1655// of the typedef, this function finds out if D might have non-external linkage.
1656// Callers should verify at the end of the TU if it D has external linkage or
1657// not.
1658bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1659 const DeclContext *DC = D->getDeclContext();
1660 while (!DC->isTranslationUnit()) {
1661 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1662 if (!RD->hasNameForLinkage())
1663 return true;
1664 }
1665 DC = DC->getParent();
1666 }
1667
1668 return !D->isExternallyVisible();
1669}
1670
1671// FIXME: This needs to be refactored; some other isInMainFile users want
1672// these semantics.
1673static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1674 if (S.TUKind != TU_Complete)
1675 return false;
1676 return S.SourceMgr.isInMainFile(Loc);
1677}
1678
1679bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1680 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1680, __PRETTY_FUNCTION__))
;
1681
1682 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1683 return false;
1684
1685 // Ignore all entities declared within templates, and out-of-line definitions
1686 // of members of class templates.
1687 if (D->getDeclContext()->isDependentContext() ||
1688 D->getLexicalDeclContext()->isDependentContext())
1689 return false;
1690
1691 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1692 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1693 return false;
1694 // A non-out-of-line declaration of a member specialization was implicitly
1695 // instantiated; it's the out-of-line declaration that we're interested in.
1696 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1697 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1698 return false;
1699
1700 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1701 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1702 return false;
1703 } else {
1704 // 'static inline' functions are defined in headers; don't warn.
1705 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1706 return false;
1707 }
1708
1709 if (FD->doesThisDeclarationHaveABody() &&
1710 Context.DeclMustBeEmitted(FD))
1711 return false;
1712 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713 // Constants and utility variables are defined in headers with internal
1714 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1715 // like "inline".)
1716 if (!isMainFileLoc(*this, VD->getLocation()))
1717 return false;
1718
1719 if (Context.DeclMustBeEmitted(VD))
1720 return false;
1721
1722 if (VD->isStaticDataMember() &&
1723 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1724 return false;
1725 if (VD->isStaticDataMember() &&
1726 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1727 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1728 return false;
1729
1730 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1731 return false;
1732 } else {
1733 return false;
1734 }
1735
1736 // Only warn for unused decls internal to the translation unit.
1737 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1738 // for inline functions defined in the main source file, for instance.
1739 return mightHaveNonExternalLinkage(D);
1740}
1741
1742void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1743 if (!D)
1744 return;
1745
1746 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1747 const FunctionDecl *First = FD->getFirstDecl();
1748 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1749 return; // First should already be in the vector.
1750 }
1751
1752 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1753 const VarDecl *First = VD->getFirstDecl();
1754 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1755 return; // First should already be in the vector.
1756 }
1757
1758 if (ShouldWarnIfUnusedFileScopedDecl(D))
1759 UnusedFileScopedDecls.push_back(D);
1760}
1761
1762static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1763 if (D->isInvalidDecl())
1764 return false;
1765
1766 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1767 // For a decomposition declaration, warn if none of the bindings are
1768 // referenced, instead of if the variable itself is referenced (which
1769 // it is, by the bindings' expressions).
1770 for (auto *BD : DD->bindings())
1771 if (BD->isReferenced())
1772 return false;
1773 } else if (!D->getDeclName()) {
1774 return false;
1775 } else if (D->isReferenced() || D->isUsed()) {
1776 return false;
1777 }
1778
1779 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1780 return false;
1781
1782 if (isa<LabelDecl>(D))
1783 return true;
1784
1785 // Except for labels, we only care about unused decls that are local to
1786 // functions.
1787 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1788 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1789 // For dependent types, the diagnostic is deferred.
1790 WithinFunction =
1791 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1792 if (!WithinFunction)
1793 return false;
1794
1795 if (isa<TypedefNameDecl>(D))
1796 return true;
1797
1798 // White-list anything that isn't a local variable.
1799 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1800 return false;
1801
1802 // Types of valid local variables should be complete, so this should succeed.
1803 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1804
1805 // White-list anything with an __attribute__((unused)) type.
1806 const auto *Ty = VD->getType().getTypePtr();
1807
1808 // Only look at the outermost level of typedef.
1809 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1810 if (TT->getDecl()->hasAttr<UnusedAttr>())
1811 return false;
1812 }
1813
1814 // If we failed to complete the type for some reason, or if the type is
1815 // dependent, don't diagnose the variable.
1816 if (Ty->isIncompleteType() || Ty->isDependentType())
1817 return false;
1818
1819 // Look at the element type to ensure that the warning behaviour is
1820 // consistent for both scalars and arrays.
1821 Ty = Ty->getBaseElementTypeUnsafe();
1822
1823 if (const TagType *TT = Ty->getAs<TagType>()) {
1824 const TagDecl *Tag = TT->getDecl();
1825 if (Tag->hasAttr<UnusedAttr>())
1826 return false;
1827
1828 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1829 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1830 return false;
1831
1832 if (const Expr *Init = VD->getInit()) {
1833 if (const ExprWithCleanups *Cleanups =
1834 dyn_cast<ExprWithCleanups>(Init))
1835 Init = Cleanups->getSubExpr();
1836 const CXXConstructExpr *Construct =
1837 dyn_cast<CXXConstructExpr>(Init);
1838 if (Construct && !Construct->isElidable()) {
1839 CXXConstructorDecl *CD = Construct->getConstructor();
1840 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1841 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1842 return false;
1843 }
1844
1845 // Suppress the warning if we don't know how this is constructed, and
1846 // it could possibly be non-trivial constructor.
1847 if (Init->isTypeDependent())
1848 for (const CXXConstructorDecl *Ctor : RD->ctors())
1849 if (!Ctor->isTrivial())
1850 return false;
1851 }
1852 }
1853 }
1854
1855 // TODO: __attribute__((unused)) templates?
1856 }
1857
1858 return true;
1859}
1860
1861static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1862 FixItHint &Hint) {
1863 if (isa<LabelDecl>(D)) {
1864 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1865 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1866 true);
1867 if (AfterColon.isInvalid())
1868 return;
1869 Hint = FixItHint::CreateRemoval(
1870 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1871 }
1872}
1873
1874void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1875 if (D->getTypeForDecl()->isDependentType())
1876 return;
1877
1878 for (auto *TmpD : D->decls()) {
1879 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1880 DiagnoseUnusedDecl(T);
1881 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1882 DiagnoseUnusedNestedTypedefs(R);
1883 }
1884}
1885
1886/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1887/// unless they are marked attr(unused).
1888void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1889 if (!ShouldDiagnoseUnusedDecl(D))
1890 return;
1891
1892 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1893 // typedefs can be referenced later on, so the diagnostics are emitted
1894 // at end-of-translation-unit.
1895 UnusedLocalTypedefNameCandidates.insert(TD);
1896 return;
1897 }
1898
1899 FixItHint Hint;
1900 GenerateFixForUnusedDecl(D, Context, Hint);
1901
1902 unsigned DiagID;
1903 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1904 DiagID = diag::warn_unused_exception_param;
1905 else if (isa<LabelDecl>(D))
1906 DiagID = diag::warn_unused_label;
1907 else
1908 DiagID = diag::warn_unused_variable;
1909
1910 Diag(D->getLocation(), DiagID) << D << Hint;
1911}
1912
1913static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1914 // Verify that we have no forward references left. If so, there was a goto
1915 // or address of a label taken, but no definition of it. Label fwd
1916 // definitions are indicated with a null substmt which is also not a resolved
1917 // MS inline assembly label name.
1918 bool Diagnose = false;
1919 if (L->isMSAsmLabel())
1920 Diagnose = !L->isResolvedMSAsmLabel();
1921 else
1922 Diagnose = L->getStmt() == nullptr;
1923 if (Diagnose)
1924 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1925}
1926
1927void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1928 S->mergeNRVOIntoParent();
1929
1930 if (S->decl_empty()) return;
1931 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope
)) && "Scope shouldn't contain decls!") ? static_cast
<void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1932, __PRETTY_FUNCTION__))
1932 "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope
)) && "Scope shouldn't contain decls!") ? static_cast
<void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1932, __PRETTY_FUNCTION__))
;
1933
1934 for (auto *TmpD : S->decls()) {
1935 assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast
<void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1935, __PRETTY_FUNCTION__))
;
1936
1937 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"
) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 1937, __PRETTY_FUNCTION__))
;
1938 NamedDecl *D = cast<NamedDecl>(TmpD);
1939
1940 // Diagnose unused variables in this scope.
1941 if (!S->hasUnrecoverableErrorOccurred()) {
1942 DiagnoseUnusedDecl(D);
1943 if (const auto *RD = dyn_cast<RecordDecl>(D))
1944 DiagnoseUnusedNestedTypedefs(RD);
1945 }
1946
1947 if (!D->getDeclName()) continue;
1948
1949 // If this was a forward reference to a label, verify it was defined.
1950 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1951 CheckPoppedLabel(LD, *this);
1952
1953 // Remove this name from our lexical scope, and warn on it if we haven't
1954 // already.
1955 IdResolver.RemoveDecl(D);
1956 auto ShadowI = ShadowingDecls.find(D);
1957 if (ShadowI != ShadowingDecls.end()) {
1958 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1959 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1960 << D << FD << FD->getParent();
1961 Diag(FD->getLocation(), diag::note_previous_declaration);
1962 }
1963 ShadowingDecls.erase(ShadowI);
1964 }
1965 }
1966}
1967
1968/// Look for an Objective-C class in the translation unit.
1969///
1970/// \param Id The name of the Objective-C class we're looking for. If
1971/// typo-correction fixes this name, the Id will be updated
1972/// to the fixed name.
1973///
1974/// \param IdLoc The location of the name in the translation unit.
1975///
1976/// \param DoTypoCorrection If true, this routine will attempt typo correction
1977/// if there is no class with the given name.
1978///
1979/// \returns The declaration of the named Objective-C class, or NULL if the
1980/// class could not be found.
1981ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1982 SourceLocation IdLoc,
1983 bool DoTypoCorrection) {
1984 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1985 // creation from this context.
1986 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1987
1988 if (!IDecl && DoTypoCorrection) {
1989 // Perform typo correction at the given location, but only if we
1990 // find an Objective-C class name.
1991 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1992 if (TypoCorrection C =
1993 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1994 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1995 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1996 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1997 Id = IDecl->getIdentifier();
1998 }
1999 }
2000 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2001 // This routine must always return a class definition, if any.
2002 if (Def && Def->getDefinition())
2003 Def = Def->getDefinition();
2004 return Def;
2005}
2006
2007/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2008/// from S, where a non-field would be declared. This routine copes
2009/// with the difference between C and C++ scoping rules in structs and
2010/// unions. For example, the following code is well-formed in C but
2011/// ill-formed in C++:
2012/// @code
2013/// struct S6 {
2014/// enum { BAR } e;
2015/// };
2016///
2017/// void test_S6() {
2018/// struct S6 a;
2019/// a.e = BAR;
2020/// }
2021/// @endcode
2022/// For the declaration of BAR, this routine will return a different
2023/// scope. The scope S will be the scope of the unnamed enumeration
2024/// within S6. In C++, this routine will return the scope associated
2025/// with S6, because the enumeration's scope is a transparent
2026/// context but structures can contain non-field names. In C, this
2027/// routine will return the translation unit scope, since the
2028/// enumeration's scope is a transparent context and structures cannot
2029/// contain non-field names.
2030Scope *Sema::getNonFieldDeclScope(Scope *S) {
2031 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2032 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2033 (S->isClassScope() && !getLangOpts().CPlusPlus))
2034 S = S->getParent();
2035 return S;
2036}
2037
2038/// Looks up the declaration of "struct objc_super" and
2039/// saves it for later use in building builtin declaration of
2040/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
2041/// pre-existing declaration exists no action takes place.
2042static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
2043 IdentifierInfo *II) {
2044 if (!II->isStr("objc_msgSendSuper"))
2045 return;
2046 ASTContext &Context = ThisSema.Context;
2047
2048 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
2049 SourceLocation(), Sema::LookupTagName);
2050 ThisSema.LookupName(Result, S);
2051 if (Result.getResultKind() == LookupResult::Found)
2052 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
2053 Context.setObjCSuperType(Context.getTagDeclType(TD));
2054}
2055
2056static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2057 ASTContext::GetBuiltinTypeError Error) {
2058 switch (Error) {
2059 case ASTContext::GE_None:
2060 return "";
2061 case ASTContext::GE_Missing_type:
2062 return BuiltinInfo.getHeaderName(ID);
2063 case ASTContext::GE_Missing_stdio:
2064 return "stdio.h";
2065 case ASTContext::GE_Missing_setjmp:
2066 return "setjmp.h";
2067 case ASTContext::GE_Missing_ucontext:
2068 return "ucontext.h";
2069 }
2070 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 2070)
;
2071}
2072
2073/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2074/// file scope. lazily create a decl for it. ForRedeclaration is true
2075/// if we're creating this built-in in anticipation of redeclaring the
2076/// built-in.
2077NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2078 Scope *S, bool ForRedeclaration,
2079 SourceLocation Loc) {
2080 LookupPredefedObjCSuperType(*this, S, II);
2081
2082 ASTContext::GetBuiltinTypeError Error;
2083 QualType R = Context.GetBuiltinType(ID, Error);
2084 if (Error) {
2085 if (!ForRedeclaration)
2086 return nullptr;
2087
2088 // If we have a builtin without an associated type we should not emit a
2089 // warning when we were not able to find a type for it.
2090 if (Error == ASTContext::GE_Missing_type)
2091 return nullptr;
2092
2093 // If we could not find a type for setjmp it is because the jmp_buf type was
2094 // not defined prior to the setjmp declaration.
2095 if (Error == ASTContext::GE_Missing_setjmp) {
2096 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2097 << Context.BuiltinInfo.getName(ID);
2098 return nullptr;
2099 }
2100
2101 // Generally, we emit a warning that the declaration requires the
2102 // appropriate header.
2103 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2104 << getHeaderName(Context.BuiltinInfo, ID, Error)
2105 << Context.BuiltinInfo.getName(ID);
2106 return nullptr;
2107 }
2108
2109 if (!ForRedeclaration &&
2110 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2111 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2112 Diag(Loc, diag::ext_implicit_lib_function_decl)
2113 << Context.BuiltinInfo.getName(ID) << R;
2114 if (Context.BuiltinInfo.getHeaderName(ID) &&
2115 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2116 Diag(Loc, diag::note_include_header_or_declare)
2117 << Context.BuiltinInfo.getHeaderName(ID)
2118 << Context.BuiltinInfo.getName(ID);
2119 }
2120
2121 if (R.isNull())
2122 return nullptr;
2123
2124 DeclContext *Parent = Context.getTranslationUnitDecl();
2125 if (getLangOpts().CPlusPlus) {
2126 LinkageSpecDecl *CLinkageDecl =
2127 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
2128 LinkageSpecDecl::lang_c, false);
2129 CLinkageDecl->setImplicit();
2130 Parent->addDecl(CLinkageDecl);
2131 Parent = CLinkageDecl;
2132 }
2133
2134 FunctionDecl *New = FunctionDecl::Create(Context,
2135 Parent,
2136 Loc, Loc, II, R, /*TInfo=*/nullptr,
2137 SC_Extern,
2138 false,
2139 R->isFunctionProtoType());
2140 New->setImplicit();
2141
2142 // Create Decl objects for each parameter, adding them to the
2143 // FunctionDecl.
2144 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2145 SmallVector<ParmVarDecl*, 16> Params;
2146 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2147 ParmVarDecl *parm =
2148 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2149 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2150 SC_None, nullptr);
2151 parm->setScopeInfo(0, i);
2152 Params.push_back(parm);
2153 }
2154 New->setParams(Params);
2155 }
2156
2157 AddKnownFunctionAttributes(New);
2158 RegisterLocallyScopedExternCDecl(New, S);
2159
2160 // TUScope is the translation-unit scope to insert this function into.
2161 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2162 // relate Scopes to DeclContexts, and probably eliminate CurContext
2163 // entirely, but we're not there yet.
2164 DeclContext *SavedContext = CurContext;
2165 CurContext = Parent;
2166 PushOnScopeChains(New, TUScope);
2167 CurContext = SavedContext;
2168 return New;
2169}
2170
2171/// Typedef declarations don't have linkage, but they still denote the same
2172/// entity if their types are the same.
2173/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2174/// isSameEntity.
2175static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2176 TypedefNameDecl *Decl,
2177 LookupResult &Previous) {
2178 // This is only interesting when modules are enabled.
2179 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2180 return;
2181
2182 // Empty sets are uninteresting.
2183 if (Previous.empty())
2184 return;
2185
2186 LookupResult::Filter Filter = Previous.makeFilter();
2187 while (Filter.hasNext()) {
2188 NamedDecl *Old = Filter.next();
2189
2190 // Non-hidden declarations are never ignored.
2191 if (S.isVisible(Old))
2192 continue;
2193
2194 // Declarations of the same entity are not ignored, even if they have
2195 // different linkages.
2196 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2197 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2198 Decl->getUnderlyingType()))
2199 continue;
2200
2201 // If both declarations give a tag declaration a typedef name for linkage
2202 // purposes, then they declare the same entity.
2203 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2204 Decl->getAnonDeclWithTypedefName())
2205 continue;
2206 }
2207
2208 Filter.erase();
2209 }
2210
2211 Filter.done();
2212}
2213
2214bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2215 QualType OldType;
2216 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2217 OldType = OldTypedef->getUnderlyingType();
2218 else
2219 OldType = Context.getTypeDeclType(Old);
2220 QualType NewType = New->getUnderlyingType();
2221
2222 if (NewType->isVariablyModifiedType()) {
2223 // Must not redefine a typedef with a variably-modified type.
2224 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2225 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2226 << Kind << NewType;
2227 if (Old->getLocation().isValid())
2228 notePreviousDefinition(Old, New->getLocation());
2229 New->setInvalidDecl();
2230 return true;
2231 }
2232
2233 if (OldType != NewType &&
2234 !OldType->isDependentType() &&
2235 !NewType->isDependentType() &&
2236 !Context.hasSameType(OldType, NewType)) {
2237 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2238 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2239 << Kind << NewType << OldType;
2240 if (Old->getLocation().isValid())
2241 notePreviousDefinition(Old, New->getLocation());
2242 New->setInvalidDecl();
2243 return true;
2244 }
2245 return false;
2246}
2247
2248/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2249/// same name and scope as a previous declaration 'Old'. Figure out
2250/// how to resolve this situation, merging decls or emitting
2251/// diagnostics as appropriate. If there was an error, set New to be invalid.
2252///
2253void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2254 LookupResult &OldDecls) {
2255 // If the new decl is known invalid already, don't bother doing any
2256 // merging checks.
2257 if (New->isInvalidDecl()) return;
2258
2259 // Allow multiple definitions for ObjC built-in typedefs.
2260 // FIXME: Verify the underlying types are equivalent!
2261 if (getLangOpts().ObjC) {
2262 const IdentifierInfo *TypeID = New->getIdentifier();
2263 switch (TypeID->getLength()) {
2264 default: break;
2265 case 2:
2266 {
2267 if (!TypeID->isStr("id"))
2268 break;
2269 QualType T = New->getUnderlyingType();
2270 if (!T->isPointerType())
2271 break;
2272 if (!T->isVoidPointerType()) {
2273 QualType PT = T->castAs<PointerType>()->getPointeeType();
2274 if (!PT->isStructureType())
2275 break;
2276 }
2277 Context.setObjCIdRedefinitionType(T);
2278 // Install the built-in type for 'id', ignoring the current definition.
2279 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2280 return;
2281 }
2282 case 5:
2283 if (!TypeID->isStr("Class"))
2284 break;
2285 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2286 // Install the built-in type for 'Class', ignoring the current definition.
2287 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2288 return;
2289 case 3:
2290 if (!TypeID->isStr("SEL"))
2291 break;
2292 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2293 // Install the built-in type for 'SEL', ignoring the current definition.
2294 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2295 return;
2296 }
2297 // Fall through - the typedef name was not a builtin type.
2298 }
2299
2300 // Verify the old decl was also a type.
2301 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2302 if (!Old) {
2303 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2304 << New->getDeclName();
2305
2306 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2307 if (OldD->getLocation().isValid())
2308 notePreviousDefinition(OldD, New->getLocation());
2309
2310 return New->setInvalidDecl();
2311 }
2312
2313 // If the old declaration is invalid, just give up here.
2314 if (Old->isInvalidDecl())
2315 return New->setInvalidDecl();
2316
2317 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2318 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2319 auto *NewTag = New->getAnonDeclWithTypedefName();
2320 NamedDecl *Hidden = nullptr;
2321 if (OldTag && NewTag &&
2322 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2323 !hasVisibleDefinition(OldTag, &Hidden)) {
2324 // There is a definition of this tag, but it is not visible. Use it
2325 // instead of our tag.
2326 New->setTypeForDecl(OldTD->getTypeForDecl());
2327 if (OldTD->isModed())
2328 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2329 OldTD->getUnderlyingType());
2330 else
2331 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2332
2333 // Make the old tag definition visible.
2334 makeMergedDefinitionVisible(Hidden);
2335
2336 // If this was an unscoped enumeration, yank all of its enumerators
2337 // out of the scope.
2338 if (isa<EnumDecl>(NewTag)) {
2339 Scope *EnumScope = getNonFieldDeclScope(S);
2340 for (auto *D : NewTag->decls()) {
2341 auto *ED = cast<EnumConstantDecl>(D);
2342 assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0
) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 2342, __PRETTY_FUNCTION__))
;
2343 EnumScope->RemoveDecl(ED);
2344 IdResolver.RemoveDecl(ED);
2345 ED->getLexicalDeclContext()->removeDecl(ED);
2346 }
2347 }
2348 }
2349 }
2350
2351 // If the typedef types are not identical, reject them in all languages and
2352 // with any extensions enabled.
2353 if (isIncompatibleTypedef(Old, New))
2354 return;
2355
2356 // The types match. Link up the redeclaration chain and merge attributes if
2357 // the old declaration was a typedef.
2358 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2359 New->setPreviousDecl(Typedef);
2360 mergeDeclAttributes(New, Old);
2361 }
2362
2363 if (getLangOpts().MicrosoftExt)
2364 return;
2365
2366 if (getLangOpts().CPlusPlus) {
2367 // C++ [dcl.typedef]p2:
2368 // In a given non-class scope, a typedef specifier can be used to
2369 // redefine the name of any type declared in that scope to refer
2370 // to the type to which it already refers.
2371 if (!isa<CXXRecordDecl>(CurContext))
2372 return;
2373
2374 // C++0x [dcl.typedef]p4:
2375 // In a given class scope, a typedef specifier can be used to redefine
2376 // any class-name declared in that scope that is not also a typedef-name
2377 // to refer to the type to which it already refers.
2378 //
2379 // This wording came in via DR424, which was a correction to the
2380 // wording in DR56, which accidentally banned code like:
2381 //
2382 // struct S {
2383 // typedef struct A { } A;
2384 // };
2385 //
2386 // in the C++03 standard. We implement the C++0x semantics, which
2387 // allow the above but disallow
2388 //
2389 // struct S {
2390 // typedef int I;
2391 // typedef int I;
2392 // };
2393 //
2394 // since that was the intent of DR56.
2395 if (!isa<TypedefNameDecl>(Old))
2396 return;
2397
2398 Diag(New->getLocation(), diag::err_redefinition)
2399 << New->getDeclName();
2400 notePreviousDefinition(Old, New->getLocation());
2401 return New->setInvalidDecl();
2402 }
2403
2404 // Modules always permit redefinition of typedefs, as does C11.
2405 if (getLangOpts().Modules || getLangOpts().C11)
2406 return;
2407
2408 // If we have a redefinition of a typedef in C, emit a warning. This warning
2409 // is normally mapped to an error, but can be controlled with
2410 // -Wtypedef-redefinition. If either the original or the redefinition is
2411 // in a system header, don't emit this for compatibility with GCC.
2412 if (getDiagnostics().getSuppressSystemWarnings() &&
2413 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2414 (Old->isImplicit() ||
2415 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2416 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2417 return;
2418
2419 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2420 << New->getDeclName();
2421 notePreviousDefinition(Old, New->getLocation());
2422}
2423
2424/// DeclhasAttr - returns true if decl Declaration already has the target
2425/// attribute.
2426static bool DeclHasAttr(const Decl *D, const Attr *A) {
2427 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2428 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2429 for (const auto *i : D->attrs())
2430 if (i->getKind() == A->getKind()) {
2431 if (Ann) {
2432 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2433 return true;
2434 continue;
2435 }
2436 // FIXME: Don't hardcode this check
2437 if (OA && isa<OwnershipAttr>(i))
2438 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2439 return true;
2440 }
2441
2442 return false;
2443}
2444
2445static bool isAttributeTargetADefinition(Decl *D) {
2446 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2447 return VD->isThisDeclarationADefinition();
2448 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2449 return TD->isCompleteDefinition() || TD->isBeingDefined();
2450 return true;
2451}
2452
2453/// Merge alignment attributes from \p Old to \p New, taking into account the
2454/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2455///
2456/// \return \c true if any attributes were added to \p New.
2457static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2458 // Look for alignas attributes on Old, and pick out whichever attribute
2459 // specifies the strictest alignment requirement.
2460 AlignedAttr *OldAlignasAttr = nullptr;
2461 AlignedAttr *OldStrictestAlignAttr = nullptr;
2462 unsigned OldAlign = 0;
2463 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2464 // FIXME: We have no way of representing inherited dependent alignments
2465 // in a case like:
2466 // template<int A, int B> struct alignas(A) X;
2467 // template<int A, int B> struct alignas(B) X {};
2468 // For now, we just ignore any alignas attributes which are not on the
2469 // definition in such a case.
2470 if (I->isAlignmentDependent())
2471 return false;
2472
2473 if (I->isAlignas())
2474 OldAlignasAttr = I;
2475
2476 unsigned Align = I->getAlignment(S.Context);
2477 if (Align > OldAlign) {
2478 OldAlign = Align;
2479 OldStrictestAlignAttr = I;
2480 }
2481 }
2482
2483 // Look for alignas attributes on New.
2484 AlignedAttr *NewAlignasAttr = nullptr;
2485 unsigned NewAlign = 0;
2486 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2487 if (I->isAlignmentDependent())
2488 return false;
2489
2490 if (I->isAlignas())
2491 NewAlignasAttr = I;
2492
2493 unsigned Align = I->getAlignment(S.Context);
2494 if (Align > NewAlign)
2495 NewAlign = Align;
2496 }
2497
2498 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2499 // Both declarations have 'alignas' attributes. We require them to match.
2500 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2501 // fall short. (If two declarations both have alignas, they must both match
2502 // every definition, and so must match each other if there is a definition.)
2503
2504 // If either declaration only contains 'alignas(0)' specifiers, then it
2505 // specifies the natural alignment for the type.
2506 if (OldAlign == 0 || NewAlign == 0) {
2507 QualType Ty;
2508 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2509 Ty = VD->getType();
2510 else
2511 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2512
2513 if (OldAlign == 0)
2514 OldAlign = S.Context.getTypeAlign(Ty);
2515 if (NewAlign == 0)
2516 NewAlign = S.Context.getTypeAlign(Ty);
2517 }
2518
2519 if (OldAlign != NewAlign) {
2520 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2521 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2522 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2523 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2524 }
2525 }
2526
2527 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2528 // C++11 [dcl.align]p6:
2529 // if any declaration of an entity has an alignment-specifier,
2530 // every defining declaration of that entity shall specify an
2531 // equivalent alignment.
2532 // C11 6.7.5/7:
2533 // If the definition of an object does not have an alignment
2534 // specifier, any other declaration of that object shall also
2535 // have no alignment specifier.
2536 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2537 << OldAlignasAttr;
2538 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2539 << OldAlignasAttr;
2540 }
2541
2542 bool AnyAdded = false;
2543
2544 // Ensure we have an attribute representing the strictest alignment.
2545 if (OldAlign > NewAlign) {
2546 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2547 Clone->setInherited(true);
2548 New->addAttr(Clone);
2549 AnyAdded = true;
2550 }
2551
2552 // Ensure we have an alignas attribute if the old declaration had one.
2553 if (OldAlignasAttr && !NewAlignasAttr &&
2554 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2555 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2556 Clone->setInherited(true);
2557 New->addAttr(Clone);
2558 AnyAdded = true;
2559 }
2560
2561 return AnyAdded;
2562}
2563
2564static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2565 const InheritableAttr *Attr,
2566 Sema::AvailabilityMergeKind AMK) {
2567 // This function copies an attribute Attr from a previous declaration to the
2568 // new declaration D if the new declaration doesn't itself have that attribute
2569 // yet or if that attribute allows duplicates.
2570 // If you're adding a new attribute that requires logic different from
2571 // "use explicit attribute on decl if present, else use attribute from
2572 // previous decl", for example if the attribute needs to be consistent
2573 // between redeclarations, you need to call a custom merge function here.
2574 InheritableAttr *NewAttr = nullptr;
2575 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2576 NewAttr = S.mergeAvailabilityAttr(
2577 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2578 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2579 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2580 AA->getPriority());
2581 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2582 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2583 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2584 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2585 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2586 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2587 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2588 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2589 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2590 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2591 FA->getFirstArg());
2592 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2593 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2594 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2595 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2596 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2597 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2598 IA->getInheritanceModel());
2599 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2600 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2601 &S.Context.Idents.get(AA->getSpelling()));
2602 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2603 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2604 isa<CUDAGlobalAttr>(Attr))) {
2605 // CUDA target attributes are part of function signature for
2606 // overloading purposes and must not be merged.
2607 return false;
2608 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2609 NewAttr = S.mergeMinSizeAttr(D, *MA);
2610 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2611 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2612 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2613 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2614 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2615 NewAttr = S.mergeCommonAttr(D, *CommonA);
2616 else if (isa<AlignedAttr>(Attr))
2617 // AlignedAttrs are handled separately, because we need to handle all
2618 // such attributes on a declaration at the same time.
2619 NewAttr = nullptr;
2620 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2621 (AMK == Sema::AMK_Override ||
2622 AMK == Sema::AMK_ProtocolImplementation))
2623 NewAttr = nullptr;
2624 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2625 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2626 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2627 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2628 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2629 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2630 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2631 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2632 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2633 NewAttr = S.mergeImportNameAttr(D, *INA);
2634 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2635 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2636
2637 if (NewAttr) {
2638 NewAttr->setInherited(true);
2639 D->addAttr(NewAttr);
2640 if (isa<MSInheritanceAttr>(NewAttr))
2641 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2642 return true;
2643 }
2644
2645 return false;
2646}
2647
2648static const NamedDecl *getDefinition(const Decl *D) {
2649 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2650 return TD->getDefinition();
2651 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2652 const VarDecl *Def = VD->getDefinition();
2653 if (Def)
2654 return Def;
2655 return VD->getActingDefinition();
2656 }
2657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2658 return FD->getDefinition();
2659 return nullptr;
2660}
2661
2662static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2663 for (const auto *Attribute : D->attrs())
2664 if (Attribute->getKind() == Kind)
2665 return true;
2666 return false;
2667}
2668
2669/// checkNewAttributesAfterDef - If we already have a definition, check that
2670/// there are no new attributes in this declaration.
2671static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2672 if (!New->hasAttrs())
2673 return;
2674
2675 const NamedDecl *Def = getDefinition(Old);
2676 if (!Def || Def == New)
2677 return;
2678
2679 AttrVec &NewAttributes = New->getAttrs();
2680 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2681 const Attr *NewAttribute = NewAttributes[I];
2682
2683 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2685 Sema::SkipBodyInfo SkipBody;
2686 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2687
2688 // If we're skipping this definition, drop the "alias" attribute.
2689 if (SkipBody.ShouldSkip) {
2690 NewAttributes.erase(NewAttributes.begin() + I);
2691 --E;
2692 continue;
2693 }
2694 } else {
2695 VarDecl *VD = cast<VarDecl>(New);
2696 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2697 VarDecl::TentativeDefinition
2698 ? diag::err_alias_after_tentative
2699 : diag::err_redefinition;
2700 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2701 if (Diag == diag::err_redefinition)
2702 S.notePreviousDefinition(Def, VD->getLocation());
2703 else
2704 S.Diag(Def->getLocation(), diag::note_previous_definition);
2705 VD->setInvalidDecl();
2706 }
2707 ++I;
2708 continue;
2709 }
2710
2711 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2712 // Tentative definitions are only interesting for the alias check above.
2713 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2714 ++I;
2715 continue;
2716 }
2717 }
2718
2719 if (hasAttribute(Def, NewAttribute->getKind())) {
2720 ++I;
2721 continue; // regular attr merging will take care of validating this.
2722 }
2723
2724 if (isa<C11NoReturnAttr>(NewAttribute)) {
2725 // C's _Noreturn is allowed to be added to a function after it is defined.
2726 ++I;
2727 continue;
2728 } else if (isa<UuidAttr>(NewAttribute)) {
2729 // msvc will allow a subsequent definition to add an uuid to a class
2730 ++I;
2731 continue;
2732 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2733 if (AA->isAlignas()) {
2734 // C++11 [dcl.align]p6:
2735 // if any declaration of an entity has an alignment-specifier,
2736 // every defining declaration of that entity shall specify an
2737 // equivalent alignment.
2738 // C11 6.7.5/7:
2739 // If the definition of an object does not have an alignment
2740 // specifier, any other declaration of that object shall also
2741 // have no alignment specifier.
2742 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2743 << AA;
2744 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2745 << AA;
2746 NewAttributes.erase(NewAttributes.begin() + I);
2747 --E;
2748 continue;
2749 }
2750 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2751 // If there is a C definition followed by a redeclaration with this
2752 // attribute then there are two different definitions. In C++, prefer the
2753 // standard diagnostics.
2754 if (!S.getLangOpts().CPlusPlus) {
2755 S.Diag(NewAttribute->getLocation(),
2756 diag::err_loader_uninitialized_redeclaration);
2757 S.Diag(Def->getLocation(), diag::note_previous_definition);
2758 NewAttributes.erase(NewAttributes.begin() + I);
2759 --E;
2760 continue;
2761 }
2762 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2763 cast<VarDecl>(New)->isInline() &&
2764 !cast<VarDecl>(New)->isInlineSpecified()) {
2765 // Don't warn about applying selectany to implicitly inline variables.
2766 // Older compilers and language modes would require the use of selectany
2767 // to make such variables inline, and it would have no effect if we
2768 // honored it.
2769 ++I;
2770 continue;
2771 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2772 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2773 // declarations after defintions.
2774 ++I;
2775 continue;
2776 }
2777
2778 S.Diag(NewAttribute->getLocation(),
2779 diag::warn_attribute_precede_definition);
2780 S.Diag(Def->getLocation(), diag::note_previous_definition);
2781 NewAttributes.erase(NewAttributes.begin() + I);
2782 --E;
2783 }
2784}
2785
2786static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2787 const ConstInitAttr *CIAttr,
2788 bool AttrBeforeInit) {
2789 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2790
2791 // Figure out a good way to write this specifier on the old declaration.
2792 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2793 // enough of the attribute list spelling information to extract that without
2794 // heroics.
2795 std::string SuitableSpelling;
2796 if (S.getLangOpts().CPlusPlus20)
2797 SuitableSpelling = std::string(
2798 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2799 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2800 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2801 InsertLoc, {tok::l_square, tok::l_square,
2802 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2803 S.PP.getIdentifierInfo("require_constant_initialization"),
2804 tok::r_square, tok::r_square}));
2805 if (SuitableSpelling.empty())
2806 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2807 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2808 S.PP.getIdentifierInfo("require_constant_initialization"),
2809 tok::r_paren, tok::r_paren}));
2810 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2811 SuitableSpelling = "constinit";
2812 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2813 SuitableSpelling = "[[clang::require_constant_initialization]]";
2814 if (SuitableSpelling.empty())
2815 SuitableSpelling = "__attribute__((require_constant_initialization))";
2816 SuitableSpelling += " ";
2817
2818 if (AttrBeforeInit) {
2819 // extern constinit int a;
2820 // int a = 0; // error (missing 'constinit'), accepted as extension
2821 assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((CIAttr->isConstinit() && "should not diagnose this for attribute"
) ? static_cast<void> (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 2821, __PRETTY_FUNCTION__))
;
2822 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2823 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2824 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2825 } else {
2826 // int a = 0;
2827 // constinit extern int a; // error (missing 'constinit')
2828 S.Diag(CIAttr->getLocation(),
2829 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2830 : diag::warn_require_const_init_added_too_late)
2831 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2832 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2833 << CIAttr->isConstinit()
2834 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2835 }
2836}
2837
2838/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2839void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2840 AvailabilityMergeKind AMK) {
2841 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2842 UsedAttr *NewAttr = OldAttr->clone(Context);
2843 NewAttr->setInherited(true);
2844 New->addAttr(NewAttr);
2845 }
2846
2847 if (!Old->hasAttrs() && !New->hasAttrs())
2848 return;
2849
2850 // [dcl.constinit]p1:
2851 // If the [constinit] specifier is applied to any declaration of a
2852 // variable, it shall be applied to the initializing declaration.
2853 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2854 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2855 if (bool(OldConstInit) != bool(NewConstInit)) {
2856 const auto *OldVD = cast<VarDecl>(Old);
2857 auto *NewVD = cast<VarDecl>(New);
2858
2859 // Find the initializing declaration. Note that we might not have linked
2860 // the new declaration into the redeclaration chain yet.
2861 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2862 if (!InitDecl &&
2863 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2864 InitDecl = NewVD;
2865
2866 if (InitDecl == NewVD) {
2867 // This is the initializing declaration. If it would inherit 'constinit',
2868 // that's ill-formed. (Note that we do not apply this to the attribute
2869 // form).
2870 if (OldConstInit && OldConstInit->isConstinit())
2871 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2872 /*AttrBeforeInit=*/true);
2873 } else if (NewConstInit) {
2874 // This is the first time we've been told that this declaration should
2875 // have a constant initializer. If we already saw the initializing
2876 // declaration, this is too late.
2877 if (InitDecl && InitDecl != NewVD) {
2878 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2879 /*AttrBeforeInit=*/false);
2880 NewVD->dropAttr<ConstInitAttr>();
2881 }
2882 }
2883 }
2884
2885 // Attributes declared post-definition are currently ignored.
2886 checkNewAttributesAfterDef(*this, New, Old);
2887
2888 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2889 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2890 if (!OldA->isEquivalent(NewA)) {
2891 // This redeclaration changes __asm__ label.
2892 Diag(New->getLocation(), diag::err_different_asm_label);
2893 Diag(OldA->getLocation(), diag::note_previous_declaration);
2894 }
2895 } else if (Old->isUsed()) {
2896 // This redeclaration adds an __asm__ label to a declaration that has
2897 // already been ODR-used.
2898 Diag(New->getLocation(), diag::err_late_asm_label_name)
2899 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2900 }
2901 }
2902
2903 // Re-declaration cannot add abi_tag's.
2904 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2905 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2906 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2907 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2908 NewTag) == OldAbiTagAttr->tags_end()) {
2909 Diag(NewAbiTagAttr->getLocation(),
2910 diag::err_new_abi_tag_on_redeclaration)
2911 << NewTag;
2912 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2913 }
2914 }
2915 } else {
2916 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2917 Diag(Old->getLocation(), diag::note_previous_declaration);
2918 }
2919 }
2920
2921 // This redeclaration adds a section attribute.
2922 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2923 if (auto *VD = dyn_cast<VarDecl>(New)) {
2924 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2925 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2926 Diag(Old->getLocation(), diag::note_previous_declaration);
2927 }
2928 }
2929 }
2930
2931 // Redeclaration adds code-seg attribute.
2932 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2933 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2934 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2935 Diag(New->getLocation(), diag::warn_mismatched_section)
2936 << 0 /*codeseg*/;
2937 Diag(Old->getLocation(), diag::note_previous_declaration);
2938 }
2939
2940 if (!Old->hasAttrs())
2941 return;
2942
2943 bool foundAny = New->hasAttrs();
2944
2945 // Ensure that any moving of objects within the allocated map is done before
2946 // we process them.
2947 if (!foundAny) New->setAttrs(AttrVec());
2948
2949 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2950 // Ignore deprecated/unavailable/availability attributes if requested.
2951 AvailabilityMergeKind LocalAMK = AMK_None;
2952 if (isa<DeprecatedAttr>(I) ||
2953 isa<UnavailableAttr>(I) ||
2954 isa<AvailabilityAttr>(I)) {
2955 switch (AMK) {
2956 case AMK_None:
2957 continue;
2958
2959 case AMK_Redeclaration:
2960 case AMK_Override:
2961 case AMK_ProtocolImplementation:
2962 LocalAMK = AMK;
2963 break;
2964 }
2965 }
2966
2967 // Already handled.
2968 if (isa<UsedAttr>(I))
2969 continue;
2970
2971 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2972 foundAny = true;
2973 }
2974
2975 if (mergeAlignedAttrs(*this, New, Old))
2976 foundAny = true;
2977
2978 if (!foundAny) New->dropAttrs();
2979}
2980
2981/// mergeParamDeclAttributes - Copy attributes from the old parameter
2982/// to the new one.
2983static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2984 const ParmVarDecl *oldDecl,
2985 Sema &S) {
2986 // C++11 [dcl.attr.depend]p2:
2987 // The first declaration of a function shall specify the
2988 // carries_dependency attribute for its declarator-id if any declaration
2989 // of the function specifies the carries_dependency attribute.
2990 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2991 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2992 S.Diag(CDA->getLocation(),
2993 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2994 // Find the first declaration of the parameter.
2995 // FIXME: Should we build redeclaration chains for function parameters?
2996 const FunctionDecl *FirstFD =
2997 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2998 const ParmVarDecl *FirstVD =
2999 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3000 S.Diag(FirstVD->getLocation(),
3001 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3002 }
3003
3004 if (!oldDecl->hasAttrs())
3005 return;
3006
3007 bool foundAny = newDecl->hasAttrs();
3008
3009 // Ensure that any moving of objects within the allocated map is
3010 // done before we process them.
3011 if (!foundAny) newDecl->setAttrs(AttrVec());
3012
3013 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3014 if (!DeclHasAttr(newDecl, I)) {
3015 InheritableAttr *newAttr =
3016 cast<InheritableParamAttr>(I->clone(S.Context));
3017 newAttr->setInherited(true);
3018 newDecl->addAttr(newAttr);
3019 foundAny = true;
3020 }
3021 }
3022
3023 if (!foundAny) newDecl->dropAttrs();
3024}
3025
3026static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3027 const ParmVarDecl *OldParam,
3028 Sema &S) {
3029 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3030 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3031 if (*Oldnullability != *Newnullability) {
3032 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3033 << DiagNullabilityKind(
3034 *Newnullability,
3035 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3036 != 0))
3037 << DiagNullabilityKind(
3038 *Oldnullability,
3039 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3040 != 0));
3041 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3042 }
3043 } else {
3044 QualType NewT = NewParam->getType();
3045 NewT = S.Context.getAttributedType(
3046 AttributedType::getNullabilityAttrKind(*Oldnullability),
3047 NewT, NewT);
3048 NewParam->setType(NewT);
3049 }
3050 }
3051}
3052
3053namespace {
3054
3055/// Used in MergeFunctionDecl to keep track of function parameters in
3056/// C.
3057struct GNUCompatibleParamWarning {
3058 ParmVarDecl *OldParm;
3059 ParmVarDecl *NewParm;
3060 QualType PromotedType;
3061};
3062
3063} // end anonymous namespace
3064
3065// Determine whether the previous declaration was a definition, implicit
3066// declaration, or a declaration.
3067template <typename T>
3068static std::pair<diag::kind, SourceLocation>
3069getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3070 diag::kind PrevDiag;
3071 SourceLocation OldLocation = Old->getLocation();
3072 if (Old->isThisDeclarationADefinition())
3073 PrevDiag = diag::note_previous_definition;
3074 else if (Old->isImplicit()) {
3075 PrevDiag = diag::note_previous_implicit_declaration;
3076 if (OldLocation.isInvalid())
3077 OldLocation = New->getLocation();
3078 } else
3079 PrevDiag = diag::note_previous_declaration;
3080 return std::make_pair(PrevDiag, OldLocation);
3081}
3082
3083/// canRedefineFunction - checks if a function can be redefined. Currently,
3084/// only extern inline functions can be redefined, and even then only in
3085/// GNU89 mode.
3086static bool canRedefineFunction(const FunctionDecl *FD,
3087 const LangOptions& LangOpts) {
3088 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3089 !LangOpts.CPlusPlus &&
3090 FD->isInlineSpecified() &&
3091 FD->getStorageClass() == SC_Extern);
3092}
3093
3094const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3095 const AttributedType *AT = T->getAs<AttributedType>();
3096 while (AT && !AT->isCallingConv())
3097 AT = AT->getModifiedType()->getAs<AttributedType>();
3098 return AT;
3099}
3100
3101template <typename T>
3102static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3103 const DeclContext *DC = Old->getDeclContext();
3104 if (DC->isRecord())
47
Calling 'DeclContext::isRecord'
50
Returning from 'DeclContext::isRecord'
51
Taking false branch
3105 return false;
3106
3107 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3108 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
52
Assuming 'OldLinkage' is not equal to CXXLanguageLinkage
3109 return true;
3110 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
53
Assuming 'OldLinkage' is not equal to CLanguageLinkage
3111 return true;
3112 return false;
54
Returning zero, which participates in a condition later
3113}
3114
3115template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3116static bool isExternC(VarTemplateDecl *) { return false; }
3117
3118/// Check whether a redeclaration of an entity introduced by a
3119/// using-declaration is valid, given that we know it's not an overload
3120/// (nor a hidden tag declaration).
3121template<typename ExpectedDecl>
3122static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3123 ExpectedDecl *New) {
3124 // C++11 [basic.scope.declarative]p4:
3125 // Given a set of declarations in a single declarative region, each of
3126 // which specifies the same unqualified name,
3127 // -- they shall all refer to the same entity, or all refer to functions
3128 // and function templates; or
3129 // -- exactly one declaration shall declare a class name or enumeration
3130 // name that is not a typedef name and the other declarations shall all
3131 // refer to the same variable or enumerator, or all refer to functions
3132 // and function templates; in this case the class name or enumeration
3133 // name is hidden (3.3.10).
3134
3135 // C++11 [namespace.udecl]p14:
3136 // If a function declaration in namespace scope or block scope has the
3137 // same name and the same parameter-type-list as a function introduced
3138 // by a using-declaration, and the declarations do not declare the same
3139 // function, the program is ill-formed.
3140
3141 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3142 if (Old &&
3143 !Old->getDeclContext()->getRedeclContext()->Equals(
3144 New->getDeclContext()->getRedeclContext()) &&
3145 !(isExternC(Old) && isExternC(New)))
3146 Old = nullptr;
3147
3148 if (!Old) {
3149 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3150 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3151 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3152 return true;
3153 }
3154 return false;
3155}
3156
3157static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3158 const FunctionDecl *B) {
3159 assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast
<void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 3159, __PRETTY_FUNCTION__))
;
3160
3161 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3162 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3163 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3164 if (AttrA == AttrB)
3165 return true;
3166 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3167 AttrA->isDynamic() == AttrB->isDynamic();
3168 };
3169
3170 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3171}
3172
3173/// If necessary, adjust the semantic declaration context for a qualified
3174/// declaration to name the correct inline namespace within the qualifier.
3175static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3176 DeclaratorDecl *OldD) {
3177 // The only case where we need to update the DeclContext is when
3178 // redeclaration lookup for a qualified name finds a declaration
3179 // in an inline namespace within the context named by the qualifier:
3180 //
3181 // inline namespace N { int f(); }
3182 // int ::f(); // Sema DC needs adjusting from :: to N::.
3183 //
3184 // For unqualified declarations, the semantic context *can* change
3185 // along the redeclaration chain (for local extern declarations,
3186 // extern "C" declarations, and friend declarations in particular).
3187 if (!NewD->getQualifier())
3188 return;
3189
3190 // NewD is probably already in the right context.
3191 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3192 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3193 if (NamedDC->Equals(SemaDC))
3194 return;
3195
3196 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 3198, __PRETTY_FUNCTION__))
3197 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 3198, __PRETTY_FUNCTION__))
3198 "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->
isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration"
) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 3198, __PRETTY_FUNCTION__))
;
3199
3200 auto *LexDC = NewD->getLexicalDeclContext();
3201 auto FixSemaDC = [=](NamedDecl *D) {
3202 if (!D)
3203 return;
3204 D->setDeclContext(SemaDC);
3205 D->setLexicalDeclContext(LexDC);
3206 };
3207
3208 FixSemaDC(NewD);
3209 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3210 FixSemaDC(FD->getDescribedFunctionTemplate());
3211 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3212 FixSemaDC(VD->getDescribedVarTemplate());
3213}
3214
3215/// MergeFunctionDecl - We just parsed a function 'New' from
3216/// declarator D which has the same name and scope as a previous
3217/// declaration 'Old'. Figure out how to resolve this situation,
3218/// merging decls or emitting diagnostics as appropriate.
3219///
3220/// In C++, New and Old must be declarations that are not
3221/// overloaded. Use IsOverload to determine whether New and Old are
3222/// overloaded, and to select the Old declaration that New should be
3223/// merged with.
3224///
3225/// Returns true if there was an error, false otherwise.
3226bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3227 Scope *S, bool MergeTypeWithOld) {
3228 // Verify the old decl was also a function.
3229 FunctionDecl *Old = OldD->getAsFunction();
3230 if (!Old) {
1
Assuming 'Old' is non-null
2
Taking false branch
3231 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3232 if (New->getFriendObjectKind()) {
3233 Diag(New->getLocation(), diag::err_using_decl_friend);
3234 Diag(Shadow->getTargetDecl()->getLocation(),
3235 diag::note_using_decl_target);
3236 Diag(Shadow->getUsingDecl()->getLocation(),
3237 diag::note_using_decl) << 0;
3238 return true;
3239 }
3240
3241 // Check whether the two declarations might declare the same function.
3242 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3243 return true;
3244 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3245 } else {
3246 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3247 << New->getDeclName();
3248 notePreviousDefinition(OldD, New->getLocation());
3249 return true;
3250 }
3251 }
3252
3253 // If the old declaration is invalid, just give up here.
3254 if (Old->isInvalidDecl())
3
Assuming the condition is false
4
Taking false branch
3255 return true;
3256
3257 // Disallow redeclaration of some builtins.
3258 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
5
Assuming the condition is false
6
Taking false branch
3259 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3260 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3261 << Old << Old->getType();
3262 return true;
3263 }
3264
3265 diag::kind PrevDiag;
3266 SourceLocation OldLocation;
3267 std::tie(PrevDiag, OldLocation) =
3268 getNoteDiagForInvalidRedeclaration(Old, New);
3269
3270 // Don't complain about this if we're in GNU89 mode and the old function
3271 // is an extern inline function.
3272 // Don't complain about specializations. They are not supposed to have
3273 // storage classes.
3274 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
7
Assuming 'New' is not a 'CXXMethodDecl'
8
Assuming 'Old' is not a 'CXXMethodDecl'
3275 New->getStorageClass() == SC_Static &&
9
Assuming the condition is false
3276 Old->hasExternalFormalLinkage() &&
3277 !New->getTemplateSpecializationInfo() &&
3278 !canRedefineFunction(Old, getLangOpts())) {
3279 if (getLangOpts().MicrosoftExt) {
3280 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3281 Diag(OldLocation, PrevDiag);
3282 } else {
3283 Diag(New->getLocation(), diag::err_static_non_static) << New;
3284 Diag(OldLocation, PrevDiag);
3285 return true;
3286 }
3287 }
3288
3289 if (New->hasAttr<InternalLinkageAttr>() &&
3290 !Old->hasAttr<InternalLinkageAttr>()) {
3291 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3292 << New->getDeclName();
3293 notePreviousDefinition(Old, New->getLocation());
3294 New->dropAttr<InternalLinkageAttr>();
3295 }
3296
3297 if (CheckRedeclarationModuleOwnership(New, Old))
10
Calling 'Sema::CheckRedeclarationModuleOwnership'
22
Returning from 'Sema::CheckRedeclarationModuleOwnership'
23
Taking false branch
3298 return true;
3299
3300 if (!getLangOpts().CPlusPlus) {
24
Assuming field 'CPlusPlus' is not equal to 0
25
Taking false branch
3301 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3302 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3303 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3304 << New << OldOvl;
3305
3306 // Try our best to find a decl that actually has the overloadable
3307 // attribute for the note. In most cases (e.g. programs with only one
3308 // broken declaration/definition), this won't matter.
3309 //
3310 // FIXME: We could do this if we juggled some extra state in
3311 // OverloadableAttr, rather than just removing it.
3312 const Decl *DiagOld = Old;
3313 if (OldOvl) {
3314 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3315 const auto *A = D->getAttr<OverloadableAttr>();
3316 return A && !A->isImplicit();
3317 });
3318 // If we've implicitly added *all* of the overloadable attrs to this
3319 // chain, emitting a "previous redecl" note is pointless.
3320 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3321 }
3322
3323 if (DiagOld)
3324 Diag(DiagOld->getLocation(),
3325 diag::note_attribute_overloadable_prev_overload)
3326 << OldOvl;
3327
3328 if (OldOvl)
3329 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3330 else
3331 New->dropAttr<OverloadableAttr>();
3332 }
3333 }
3334
3335 // If a function is first declared with a calling convention, but is later
3336 // declared or defined without one, all following decls assume the calling
3337 // convention of the first.
3338 //
3339 // It's OK if a function is first declared without a calling convention,
3340 // but is later declared or defined with the default calling convention.
3341 //
3342 // To test if either decl has an explicit calling convention, we look for
3343 // AttributedType sugar nodes on the type as written. If they are missing or
3344 // were canonicalized away, we assume the calling convention was implicit.
3345 //
3346 // Note also that we DO NOT return at this point, because we still have
3347 // other tests to run.
3348 QualType OldQType = Context.getCanonicalType(Old->getType());
3349 QualType NewQType = Context.getCanonicalType(New->getType());
3350 const FunctionType *OldType = cast<FunctionType>(OldQType);
3351 const FunctionType *NewType = cast<FunctionType>(NewQType);
3352 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3353 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3354 bool RequiresAdjustment = false;
3355
3356 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
26
Assuming the condition is false
27
Taking false branch
3357 FunctionDecl *First = Old->getFirstDecl();
3358 const FunctionType *FT =
3359 First->getType().getCanonicalType()->castAs<FunctionType>();
3360 FunctionType::ExtInfo FI = FT->getExtInfo();
3361 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3362 if (!NewCCExplicit) {
3363 // Inherit the CC from the previous declaration if it was specified
3364 // there but not here.
3365 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3366 RequiresAdjustment = true;
3367 } else if (New->getBuiltinID()) {
3368 // Calling Conventions on a Builtin aren't really useful and setting a
3369 // default calling convention and cdecl'ing some builtin redeclarations is
3370 // common, so warn and ignore the calling convention on the redeclaration.
3371 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3372 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3373 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3374 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3375 RequiresAdjustment = true;
3376 } else {
3377 // Calling conventions aren't compatible, so complain.
3378 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3379 Diag(New->getLocation(), diag::err_cconv_change)
3380 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3381 << !FirstCCExplicit
3382 << (!FirstCCExplicit ? "" :
3383 FunctionType::getNameForCallConv(FI.getCC()));
3384
3385 // Put the note on the first decl, since it is the one that matters.
3386 Diag(First->getLocation(), diag::note_previous_declaration);
3387 return true;
3388 }
3389 }
3390
3391 // FIXME: diagnose the other way around?
3392 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
28
Assuming the condition is false
3393 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3394 RequiresAdjustment = true;
3395 }
3396
3397 // Merge regparm attribute.
3398 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
29
Taking false branch
3399 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3400 if (NewTypeInfo.getHasRegParm()) {
3401 Diag(New->getLocation(), diag::err_regparm_mismatch)
3402 << NewType->getRegParmType()
3403 << OldType->getRegParmType();
3404 Diag(OldLocation, diag::note_previous_declaration);
3405 return true;
3406 }
3407
3408 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3409 RequiresAdjustment = true;
3410 }
3411
3412 // Merge ns_returns_retained attribute.
3413 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
30
Assuming the condition is false
31
Taking false branch
3414 if (NewTypeInfo.getProducesResult()) {
3415 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3416 << "'ns_returns_retained'";
3417 Diag(OldLocation, diag::note_previous_declaration);
3418 return true;
3419 }
3420
3421 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3422 RequiresAdjustment = true;
3423 }
3424
3425 if (OldTypeInfo.getNoCallerSavedRegs() !=
32
Assuming the condition is false
33
Taking false branch
3426 NewTypeInfo.getNoCallerSavedRegs()) {
3427 if (NewTypeInfo.getNoCallerSavedRegs()) {
3428 AnyX86NoCallerSavedRegistersAttr *Attr =
3429 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3430 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3431 Diag(OldLocation, diag::note_previous_declaration);
3432 return true;
3433 }
3434
3435 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3436 RequiresAdjustment = true;
3437 }
3438
3439 if (RequiresAdjustment
33.1
'RequiresAdjustment' is false
33.1
'RequiresAdjustment' is false
) {
34
Taking false branch
3440 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3441 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3442 New->setType(QualType(AdjustedType, 0));
3443 NewQType = Context.getCanonicalType(New->getType());
3444 }
3445
3446 // If this redeclaration makes the function inline, we may need to add it to
3447 // UndefinedButUsed.
3448 if (!Old->isInlined() && New->isInlined() &&
35
Assuming the condition is false
3449 !New->hasAttr<GNUInlineAttr>() &&
3450 !getLangOpts().GNUInline &&
3451 Old->isUsed(false) &&
3452 !Old->isDefined() && !New->isThisDeclarationADefinition())
3453 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3454 SourceLocation()));
3455
3456 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3457 // about it.
3458 if (New->hasAttr<GNUInlineAttr>() &&
3459 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3460 UndefinedButUsed.erase(Old->getCanonicalDecl());
3461 }
3462
3463 // If pass_object_size params don't match up perfectly, this isn't a valid
3464 // redeclaration.
3465 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
36
Assuming the condition is false
3466 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3467 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3468 << New->getDeclName();
3469 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3470 return true;
3471 }
3472
3473 if (getLangOpts().CPlusPlus
36.1
Field 'CPlusPlus' is not equal to 0
36.1
Field 'CPlusPlus' is not equal to 0
) {
37
Taking true branch
3474 // C++1z [over.load]p2
3475 // Certain function declarations cannot be overloaded:
3476 // -- Function declarations that differ only in the return type,
3477 // the exception specification, or both cannot be overloaded.
3478
3479 // Check the exception specifications match. This may recompute the type of
3480 // both Old and New if it resolved exception specifications, so grab the
3481 // types again after this. Because this updates the type, we do this before
3482 // any of the other checks below, which may update the "de facto" NewQType
3483 // but do not necessarily update the type of New.
3484 if (CheckEquivalentExceptionSpec(Old, New))
38
Assuming the condition is false
39
Taking false branch
3485 return true;
3486 OldQType = Context.getCanonicalType(Old->getType());
3487 NewQType = Context.getCanonicalType(New->getType());
3488
3489 // Go back to the type source info to compare the declared return types,
3490 // per C++1y [dcl.type.auto]p13:
3491 // Redeclarations or specializations of a function or function template
3492 // with a declared return type that uses a placeholder type shall also
3493 // use that placeholder, not a deduced type.
3494 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3495 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3496 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
40
Assuming the condition is false
3497 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3498 OldDeclaredReturnType)) {
3499 QualType ResQT;
3500 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3501 OldDeclaredReturnType->isObjCObjectPointerType())
3502 // FIXME: This does the wrong thing for a deduced return type.
3503 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3504 if (ResQT.isNull()) {
3505 if (New->isCXXClassMember() && New->isOutOfLine())
3506 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3507 << New << New->getReturnTypeSourceRange();
3508 else
3509 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3510 << New->getReturnTypeSourceRange();
3511 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3512 << Old->getReturnTypeSourceRange();
3513 return true;
3514 }
3515 else
3516 NewQType = ResQT;
3517 }
3518
3519 QualType OldReturnType = OldType->getReturnType();
3520 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3521 if (OldReturnType != NewReturnType) {
41
Taking false branch
3522 // If this function has a deduced return type and has already been
3523 // defined, copy the deduced value from the old declaration.
3524 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3525 if (OldAT && OldAT->isDeduced()) {
3526 New->setType(
3527 SubstAutoType(New->getType(),
3528 OldAT->isDependentType() ? Context.DependentTy
3529 : OldAT->getDeducedType()));
3530 NewQType = Context.getCanonicalType(
3531 SubstAutoType(NewQType,
3532 OldAT->isDependentType() ? Context.DependentTy
3533 : OldAT->getDeducedType()));
3534 }
3535 }
3536
3537 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
42
Assuming 'Old' is not a 'CXXMethodDecl'
3538 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
43
Assuming 'New' is not a 'CXXMethodDecl'
3539 if (OldMethod
43.1
'OldMethod' is null
43.1
'OldMethod' is null
&& NewMethod) {
3540 // Preserve triviality.
3541 NewMethod->setTrivial(OldMethod->isTrivial());
3542
3543 // MSVC allows explicit template specialization at class scope:
3544 // 2 CXXMethodDecls referring to the same function will be injected.
3545 // We don't want a redeclaration error.
3546 bool IsClassScopeExplicitSpecialization =
3547 OldMethod->isFunctionTemplateSpecialization() &&
3548 NewMethod->isFunctionTemplateSpecialization();
3549 bool isFriend = NewMethod->getFriendObjectKind();
3550
3551 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3552 !IsClassScopeExplicitSpecialization) {
3553 // -- Member function declarations with the same name and the
3554 // same parameter types cannot be overloaded if any of them
3555 // is a static member function declaration.
3556 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3557 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3558 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3559 return true;
3560 }
3561
3562 // C++ [class.mem]p1:
3563 // [...] A member shall not be declared twice in the
3564 // member-specification, except that a nested class or member
3565 // class template can be declared and then later defined.
3566 if (!inTemplateInstantiation()) {
3567 unsigned NewDiag;
3568 if (isa<CXXConstructorDecl>(OldMethod))
3569 NewDiag = diag::err_constructor_redeclared;
3570 else if (isa<CXXDestructorDecl>(NewMethod))
3571 NewDiag = diag::err_destructor_redeclared;
3572 else if (isa<CXXConversionDecl>(NewMethod))
3573 NewDiag = diag::err_conv_function_redeclared;
3574 else
3575 NewDiag = diag::err_member_redeclared;
3576
3577 Diag(New->getLocation(), NewDiag);
3578 } else {
3579 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3580 << New << New->getType();
3581 }
3582 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3583 return true;
3584
3585 // Complain if this is an explicit declaration of a special
3586 // member that was initially declared implicitly.
3587 //
3588 // As an exception, it's okay to befriend such methods in order
3589 // to permit the implicit constructor/destructor/operator calls.
3590 } else if (OldMethod->isImplicit()) {
3591 if (isFriend) {
3592 NewMethod->setImplicit();
3593 } else {
3594 Diag(NewMethod->getLocation(),
3595 diag::err_definition_of_implicitly_declared_member)
3596 << New << getSpecialMember(OldMethod);
3597 return true;
3598 }
3599 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3600 Diag(NewMethod->getLocation(),
3601 diag::err_definition_of_explicitly_defaulted_member)
3602 << getSpecialMember(OldMethod);
3603 return true;
3604 }
3605 }
3606
3607 // C++11 [dcl.attr.noreturn]p1:
3608 // The first declaration of a function shall specify the noreturn
3609 // attribute if any declaration of that function specifies the noreturn
3610 // attribute.
3611 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3612 if (NRA
43.2
'NRA' is null
43.2
'NRA' is null
&& !Old->hasAttr<CXX11NoReturnAttr>()) {
3613 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3614 Diag(Old->getFirstDecl()->getLocation(),
3615 diag::note_noreturn_missing_first_decl);
3616 }
3617
3618 // C++11 [dcl.attr.depend]p2:
3619 // The first declaration of a function shall specify the
3620 // carries_dependency attribute for its declarator-id if any declaration
3621 // of the function specifies the carries_dependency attribute.
3622 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3623 if (CDA
43.3
'CDA' is null
43.3
'CDA' is null
&& !Old->hasAttr<CarriesDependencyAttr>()) {
3624 Diag(CDA->getLocation(),
3625 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3626 Diag(Old->getFirstDecl()->getLocation(),
3627 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3628 }
3629
3630 // (C++98 8.3.5p3):
3631 // All declarations for a function shall agree exactly in both the
3632 // return type and the parameter-type-list.
3633 // We also want to respect all the extended bits except noreturn.
3634
3635 // noreturn should now match unless the old type info didn't have it.
3636 QualType OldQTypeForComparison = OldQType;
3637 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
44
Assuming the condition is false
45
Taking false branch
3638 auto *OldType = OldQType->castAs<FunctionProtoType>();
3639 const FunctionType *OldTypeForComparison
3640 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3641 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3642 assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void>
(0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 3642, __PRETTY_FUNCTION__))
;
3643 }
3644
3645 if (haveIncompatibleLanguageLinkages(Old, New)) {
46
Calling 'haveIncompatibleLanguageLinkages<clang::FunctionDecl>'
55
Returning from 'haveIncompatibleLanguageLinkages<clang::FunctionDecl>'
56
Taking false branch
3646 // As a special case, retain the language linkage from previous
3647 // declarations of a friend function as an extension.
3648 //
3649 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3650 // and is useful because there's otherwise no way to specify language
3651 // linkage within class scope.
3652 //
3653 // Check cautiously as the friend object kind isn't yet complete.
3654 if (New->getFriendObjectKind() != Decl::FOK_None) {
3655 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3656 Diag(OldLocation, PrevDiag);
3657 } else {
3658 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3659 Diag(OldLocation, PrevDiag);
3660 return true;
3661 }
3662 }
3663
3664 // If the function types are compatible, merge the declarations. Ignore the
3665 // exception specifier because it was already checked above in
3666 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3667 // about incompatible types under -fms-compatibility.
3668 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
57
Assuming the condition is false
58
Taking false branch
3669 NewQType))
3670 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3671
3672 // If the types are imprecise (due to dependent constructs in friends or
3673 // local extern declarations), it's OK if they differ. We'll check again
3674 // during instantiation.
3675 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
59
Calling 'Sema::canFullyTypeCheckRedeclaration'
65
Returning from 'Sema::canFullyTypeCheckRedeclaration'
66
Taking false branch
3676 return false;
3677
3678 // Fall through for conflicting redeclarations and redefinitions.
3679 }
3680
3681 // C: Function types need to be compatible, not identical. This handles
3682 // duplicate function decls like "void f(int); void f(enum X);" properly.
3683 if (!getLangOpts().CPlusPlus &&
67
Assuming field 'CPlusPlus' is 0
69
Taking true branch
3684 Context.typesAreCompatible(OldQType, NewQType)) {
68
Assuming the condition is true
3685 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
70
Assuming the object is not a 'FunctionType'
3686 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
71
Assuming the object is not a 'FunctionType'
72
'NewFuncType' initialized to a null pointer value
3687 const FunctionProtoType *OldProto = nullptr;
3688 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
73
Assuming 'MergeTypeWithOld' is true
74
Assuming 'NewFuncType' is a 'FunctionNoProtoType'
76
Taking true branch
3689 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
75
Assuming 'OldProto' is non-null
3690 // The old declaration provided a function prototype, but the
3691 // new declaration does not. Merge in the prototype.
3692 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C"
) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 3692, __PRETTY_FUNCTION__))
;
77
'?' condition is true
3693 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3694 NewQType =
3695 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
78
Called C++ object pointer is null
3696 OldProto->getExtProtoInfo());
3697 New->setType(NewQType);
3698 New->setHasInheritedPrototype();
3699
3700 // Synthesize parameters with the same types.
3701 SmallVector<ParmVarDecl*, 16> Params;
3702 for (const auto &ParamType : OldProto->param_types()) {
3703 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3704 SourceLocation(), nullptr,
3705 ParamType, /*TInfo=*/nullptr,
3706 SC_None, nullptr);
3707 Param->setScopeInfo(0, Params.size());
3708 Param->setImplicit();
3709 Params.push_back(Param);
3710 }
3711
3712 New->setParams(Params);
3713 }
3714
3715 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3716 }
3717
3718 // Check if the function types are compatible when pointer size address
3719 // spaces are ignored.
3720 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3721 return false;
3722
3723 // GNU C permits a K&R definition to follow a prototype declaration
3724 // if the declared types of the parameters in the K&R definition
3725 // match the types in the prototype declaration, even when the
3726 // promoted types of the parameters from the K&R definition differ
3727 // from the types in the prototype. GCC then keeps the types from
3728 // the prototype.
3729 //
3730 // If a variadic prototype is followed by a non-variadic K&R definition,
3731 // the K&R definition becomes variadic. This is sort of an edge case, but
3732 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3733 // C99 6.9.1p8.
3734 if (!getLangOpts().CPlusPlus &&
3735 Old->hasPrototype() && !New->hasPrototype() &&
3736 New->getType()->getAs<FunctionProtoType>() &&
3737 Old->getNumParams() == New->getNumParams()) {
3738 SmallVector<QualType, 16> ArgTypes;
3739 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3740 const FunctionProtoType *OldProto
3741 = Old->getType()->getAs<FunctionProtoType>();
3742 const FunctionProtoType *NewProto
3743 = New->getType()->getAs<FunctionProtoType>();
3744
3745 // Determine whether this is the GNU C extension.
3746 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3747 NewProto->getReturnType());
3748 bool LooseCompatible = !MergedReturn.isNull();
3749 for (unsigned Idx = 0, End = Old->getNumParams();
3750 LooseCompatible && Idx != End; ++Idx) {
3751 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3752 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3753 if (Context.typesAreCompatible(OldParm->getType(),
3754 NewProto->getParamType(Idx))) {
3755 ArgTypes.push_back(NewParm->getType());
3756 } else if (Context.typesAreCompatible(OldParm->getType(),
3757 NewParm->getType(),
3758 /*CompareUnqualified=*/true)) {
3759 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3760 NewProto->getParamType(Idx) };
3761 Warnings.push_back(Warn);
3762 ArgTypes.push_back(NewParm->getType());
3763 } else
3764 LooseCompatible = false;
3765 }
3766
3767 if (LooseCompatible) {
3768 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3769 Diag(Warnings[Warn].NewParm->getLocation(),
3770 diag::ext_param_promoted_not_compatible_with_prototype)
3771 << Warnings[Warn].PromotedType
3772 << Warnings[Warn].OldParm->getType();
3773 if (Warnings[Warn].OldParm->getLocation().isValid())
3774 Diag(Warnings[Warn].OldParm->getLocation(),
3775 diag::note_previous_declaration);
3776 }
3777
3778 if (MergeTypeWithOld)
3779 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3780 OldProto->getExtProtoInfo()));
3781 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3782 }
3783
3784 // Fall through to diagnose conflicting types.
3785 }
3786
3787 // A function that has already been declared has been redeclared or
3788 // defined with a different type; show an appropriate diagnostic.
3789
3790 // If the previous declaration was an implicitly-generated builtin
3791 // declaration, then at the very least we should use a specialized note.
3792 unsigned BuiltinID;
3793 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3794 // If it's actually a library-defined builtin function like 'malloc'
3795 // or 'printf', just warn about the incompatible redeclaration.
3796 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3797 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3798 Diag(OldLocation, diag::note_previous_builtin_declaration)
3799 << Old << Old->getType();
3800
3801 // If this is a global redeclaration, just forget hereafter
3802 // about the "builtin-ness" of the function.
3803 //
3804 // Doing this for local extern declarations is problematic. If
3805 // the builtin declaration remains visible, a second invalid
3806 // local declaration will produce a hard error; if it doesn't
3807 // remain visible, a single bogus local redeclaration (which is
3808 // actually only a warning) could break all the downstream code.
3809 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3810 New->getIdentifier()->revertBuiltin();
3811
3812 return false;
3813 }
3814
3815 PrevDiag = diag::note_previous_builtin_declaration;
3816 }
3817
3818 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3819 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3820 return true;
3821}
3822
3823/// Completes the merge of two function declarations that are
3824/// known to be compatible.
3825///
3826/// This routine handles the merging of attributes and other
3827/// properties of function declarations from the old declaration to
3828/// the new declaration, once we know that New is in fact a
3829/// redeclaration of Old.
3830///
3831/// \returns false
3832bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3833 Scope *S, bool MergeTypeWithOld) {
3834 // Merge the attributes
3835 mergeDeclAttributes(New, Old);
3836
3837 // Merge "pure" flag.
3838 if (Old->isPure())
3839 New->setPure();
3840
3841 // Merge "used" flag.
3842 if (Old->getMostRecentDecl()->isUsed(false))
3843 New->setIsUsed();
3844
3845 // Merge attributes from the parameters. These can mismatch with K&R
3846 // declarations.
3847 if (New->getNumParams() == Old->getNumParams())
3848 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3849 ParmVarDecl *NewParam = New->getParamDecl(i);
3850 ParmVarDecl *OldParam = Old->getParamDecl(i);
3851 mergeParamDeclAttributes(NewParam, OldParam, *this);
3852 mergeParamDeclTypes(NewParam, OldParam, *this);
3853 }
3854
3855 if (getLangOpts().CPlusPlus)
3856 return MergeCXXFunctionDecl(New, Old, S);
3857
3858 // Merge the function types so the we get the composite types for the return
3859 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3860 // was visible.
3861 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3862 if (!Merged.isNull() && MergeTypeWithOld)
3863 New->setType(Merged);
3864
3865 return false;
3866}
3867
3868void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3869 ObjCMethodDecl *oldMethod) {
3870 // Merge the attributes, including deprecated/unavailable
3871 AvailabilityMergeKind MergeKind =
3872 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3873 ? AMK_ProtocolImplementation
3874 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3875 : AMK_Override;
3876
3877 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3878
3879 // Merge attributes from the parameters.
3880 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3881 oe = oldMethod->param_end();
3882 for (ObjCMethodDecl::param_iterator
3883 ni = newMethod->param_begin(), ne = newMethod->param_end();
3884 ni != ne && oi != oe; ++ni, ++oi)
3885 mergeParamDeclAttributes(*ni, *oi, *this);
3886
3887 CheckObjCMethodOverride(newMethod, oldMethod);
3888}
3889
3890static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3891 assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType()
)) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 3891, __PRETTY_FUNCTION__))
;
3892
3893 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3894 ? diag::err_redefinition_different_type
3895 : diag::err_redeclaration_different_type)
3896 << New->getDeclName() << New->getType() << Old->getType();
3897
3898 diag::kind PrevDiag;
3899 SourceLocation OldLocation;
3900 std::tie(PrevDiag, OldLocation)
3901 = getNoteDiagForInvalidRedeclaration(Old, New);
3902 S.Diag(OldLocation, PrevDiag);
3903 New->setInvalidDecl();
3904}
3905
3906/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3907/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3908/// emitting diagnostics as appropriate.
3909///
3910/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3911/// to here in AddInitializerToDecl. We can't check them before the initializer
3912/// is attached.
3913void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3914 bool MergeTypeWithOld) {
3915 if (New->isInvalidDecl() || Old->isInvalidDecl())
3916 return;
3917
3918 QualType MergedT;
3919 if (getLangOpts().CPlusPlus) {
3920 if (New->getType()->isUndeducedType()) {
3921 // We don't know what the new type is until the initializer is attached.
3922 return;
3923 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3924 // These could still be something that needs exception specs checked.
3925 return MergeVarDeclExceptionSpecs(New, Old);
3926 }
3927 // C++ [basic.link]p10:
3928 // [...] the types specified by all declarations referring to a given
3929 // object or function shall be identical, except that declarations for an
3930 // array object can specify array types that differ by the presence or
3931 // absence of a major array bound (8.3.4).
3932 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3933 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3934 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3935
3936 // We are merging a variable declaration New into Old. If it has an array
3937 // bound, and that bound differs from Old's bound, we should diagnose the
3938 // mismatch.
3939 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3940 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3941 PrevVD = PrevVD->getPreviousDecl()) {
3942 QualType PrevVDTy = PrevVD->getType();
3943 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3944 continue;
3945
3946 if (!Context.hasSameType(New->getType(), PrevVDTy))
3947 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3948 }
3949 }
3950
3951 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3952 if (Context.hasSameType(OldArray->getElementType(),
3953 NewArray->getElementType()))
3954 MergedT = New->getType();
3955 }
3956 // FIXME: Check visibility. New is hidden but has a complete type. If New
3957 // has no array bound, it should not inherit one from Old, if Old is not
3958 // visible.
3959 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3960 if (Context.hasSameType(OldArray->getElementType(),
3961 NewArray->getElementType()))
3962 MergedT = Old->getType();
3963 }
3964 }
3965 else if (New->getType()->isObjCObjectPointerType() &&
3966 Old->getType()->isObjCObjectPointerType()) {
3967 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3968 Old->getType());
3969 }
3970 } else {
3971 // C 6.2.7p2:
3972 // All declarations that refer to the same object or function shall have
3973 // compatible type.
3974 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3975 }
3976 if (MergedT.isNull()) {
3977 // It's OK if we couldn't merge types if either type is dependent, for a
3978 // block-scope variable. In other cases (static data members of class
3979 // templates, variable templates, ...), we require the types to be
3980 // equivalent.
3981 // FIXME: The C++ standard doesn't say anything about this.
3982 if ((New->getType()->isDependentType() ||
3983 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3984 // If the old type was dependent, we can't merge with it, so the new type
3985 // becomes dependent for now. We'll reproduce the original type when we
3986 // instantiate the TypeSourceInfo for the variable.
3987 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3988 New->setType(Context.DependentTy);
3989 return;
3990 }
3991 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3992 }
3993
3994 // Don't actually update the type on the new declaration if the old
3995 // declaration was an extern declaration in a different scope.
3996 if (MergeTypeWithOld)
3997 New->setType(MergedT);
3998}
3999
4000static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4001 LookupResult &Previous) {
4002 // C11 6.2.7p4:
4003 // For an identifier with internal or external linkage declared
4004 // in a scope in which a prior declaration of that identifier is
4005 // visible, if the prior declaration specifies internal or
4006 // external linkage, the type of the identifier at the later
4007 // declaration becomes the composite type.
4008 //
4009 // If the variable isn't visible, we do not merge with its type.
4010 if (Previous.isShadowed())
4011 return false;
4012
4013 if (S.getLangOpts().CPlusPlus) {
4014 // C++11 [dcl.array]p3:
4015 // If there is a preceding declaration of the entity in the same
4016 // scope in which the bound was specified, an omitted array bound
4017 // is taken to be the same as in that earlier declaration.
4018 return NewVD->isPreviousDeclInSameBlockScope() ||
4019 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4020 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4021 } else {
4022 // If the old declaration was function-local, don't merge with its
4023 // type unless we're in the same function.
4024 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4025 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4026 }
4027}
4028
4029/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4030/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4031/// situation, merging decls or emitting diagnostics as appropriate.
4032///
4033/// Tentative definition rules (C99 6.9.2p2) are checked by
4034/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4035/// definitions here, since the initializer hasn't been attached.
4036///
4037void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4038 // If the new decl is already invalid, don't do any other checking.
4039 if (New->isInvalidDecl())
4040 return;
4041
4042 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4043 return;
4044
4045 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4046
4047 // Verify the old decl was also a variable or variable template.
4048 VarDecl *Old = nullptr;
4049 VarTemplateDecl *OldTemplate = nullptr;
4050 if (Previous.isSingleResult()) {
4051 if (NewTemplate) {
4052 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4053 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4054
4055 if (auto *Shadow =
4056 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4057 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4058 return New->setInvalidDecl();
4059 } else {
4060 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4061
4062 if (auto *Shadow =
4063 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4064 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4065 return New->setInvalidDecl();
4066 }
4067 }
4068 if (!Old) {
4069 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4070 << New->getDeclName();
4071 notePreviousDefinition(Previous.getRepresentativeDecl(),
4072 New->getLocation());
4073 return New->setInvalidDecl();
4074 }
4075
4076 // Ensure the template parameters are compatible.
4077 if (NewTemplate &&
4078 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4079 OldTemplate->getTemplateParameters(),
4080 /*Complain=*/true, TPL_TemplateMatch))
4081 return New->setInvalidDecl();
4082
4083 // C++ [class.mem]p1:
4084 // A member shall not be declared twice in the member-specification [...]
4085 //
4086 // Here, we need only consider static data members.
4087 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4088 Diag(New->getLocation(), diag::err_duplicate_member)
4089 << New->getIdentifier();
4090 Diag(Old->getLocation(), diag::note_previous_declaration);
4091 New->setInvalidDecl();
4092 }
4093
4094 mergeDeclAttributes(New, Old);
4095 // Warn if an already-declared variable is made a weak_import in a subsequent
4096 // declaration
4097 if (New->hasAttr<WeakImportAttr>() &&
4098 Old->getStorageClass() == SC_None &&
4099 !Old->hasAttr<WeakImportAttr>()) {
4100 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4101 notePreviousDefinition(Old, New->getLocation());
4102 // Remove weak_import attribute on new declaration.
4103 New->dropAttr<WeakImportAttr>();
4104 }
4105
4106 if (New->hasAttr<InternalLinkageAttr>() &&
4107 !Old->hasAttr<InternalLinkageAttr>()) {
4108 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4109 << New->getDeclName();
4110 notePreviousDefinition(Old, New->getLocation());
4111 New->dropAttr<InternalLinkageAttr>();
4112 }
4113
4114 // Merge the types.
4115 VarDecl *MostRecent = Old->getMostRecentDecl();
4116 if (MostRecent != Old) {
4117 MergeVarDeclTypes(New, MostRecent,
4118 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4119 if (New->isInvalidDecl())
4120 return;
4121 }
4122
4123 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4124 if (New->isInvalidDecl())
4125 return;
4126
4127 diag::kind PrevDiag;
4128 SourceLocation OldLocation;
4129 std::tie(PrevDiag, OldLocation) =
4130 getNoteDiagForInvalidRedeclaration(Old, New);
4131
4132 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4133 if (New->getStorageClass() == SC_Static &&
4134 !New->isStaticDataMember() &&
4135 Old->hasExternalFormalLinkage()) {
4136 if (getLangOpts().MicrosoftExt) {
4137 Diag(New->getLocation(), diag::ext_static_non_static)
4138 << New->getDeclName();
4139 Diag(OldLocation, PrevDiag);
4140 } else {
4141 Diag(New->getLocation(), diag::err_static_non_static)
4142 << New->getDeclName();
4143 Diag(OldLocation, PrevDiag);
4144 return New->setInvalidDecl();
4145 }
4146 }
4147 // C99 6.2.2p4:
4148 // For an identifier declared with the storage-class specifier
4149 // extern in a scope in which a prior declaration of that
4150 // identifier is visible,23) if the prior declaration specifies
4151 // internal or external linkage, the linkage of the identifier at
4152 // the later declaration is the same as the linkage specified at
4153 // the prior declaration. If no prior declaration is visible, or
4154 // if the prior declaration specifies no linkage, then the
4155 // identifier has external linkage.
4156 if (New->hasExternalStorage() && Old->hasLinkage())
4157 /* Okay */;
4158 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4159 !New->isStaticDataMember() &&
4160 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4161 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4162 Diag(OldLocation, PrevDiag);
4163 return New->setInvalidDecl();
4164 }
4165
4166 // Check if extern is followed by non-extern and vice-versa.
4167 if (New->hasExternalStorage() &&
4168 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4169 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4170 Diag(OldLocation, PrevDiag);
4171 return New->setInvalidDecl();
4172 }
4173 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4174 !New->hasExternalStorage()) {
4175 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4176 Diag(OldLocation, PrevDiag);
4177 return New->setInvalidDecl();
4178 }
4179
4180 if (CheckRedeclarationModuleOwnership(New, Old))
4181 return;
4182
4183 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4184
4185 // FIXME: The test for external storage here seems wrong? We still
4186 // need to check for mismatches.
4187 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4188 // Don't complain about out-of-line definitions of static members.
4189 !(Old->getLexicalDeclContext()->isRecord() &&
4190 !New->getLexicalDeclContext()->isRecord())) {
4191 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4192 Diag(OldLocation, PrevDiag);
4193 return New->setInvalidDecl();
4194 }
4195
4196 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4197 if (VarDecl *Def = Old->getDefinition()) {
4198 // C++1z [dcl.fcn.spec]p4:
4199 // If the definition of a variable appears in a translation unit before
4200 // its first declaration as inline, the program is ill-formed.
4201 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4202 Diag(Def->getLocation(), diag::note_previous_definition);
4203 }
4204 }
4205
4206 // If this redeclaration makes the variable inline, we may need to add it to
4207 // UndefinedButUsed.
4208 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4209 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4210 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4211 SourceLocation()));
4212
4213 if (New->getTLSKind() != Old->getTLSKind()) {
4214 if (!Old->getTLSKind()) {
4215 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4216 Diag(OldLocation, PrevDiag);
4217 } else if (!New->getTLSKind()) {
4218 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4219 Diag(OldLocation, PrevDiag);
4220 } else {
4221 // Do not allow redeclaration to change the variable between requiring
4222 // static and dynamic initialization.
4223 // FIXME: GCC allows this, but uses the TLS keyword on the first
4224 // declaration to determine the kind. Do we need to be compatible here?
4225 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4226 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4227 Diag(OldLocation, PrevDiag);
4228 }
4229 }
4230
4231 // C++ doesn't have tentative definitions, so go right ahead and check here.
4232 if (getLangOpts().CPlusPlus &&
4233 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4234 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4235 Old->getCanonicalDecl()->isConstexpr()) {
4236 // This definition won't be a definition any more once it's been merged.
4237 Diag(New->getLocation(),
4238 diag::warn_deprecated_redundant_constexpr_static_def);
4239 } else if (VarDecl *Def = Old->getDefinition()) {
4240 if (checkVarDeclRedefinition(Def, New))
4241 return;
4242 }
4243 }
4244
4245 if (haveIncompatibleLanguageLinkages(Old, New)) {
4246 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4247 Diag(OldLocation, PrevDiag);
4248 New->setInvalidDecl();
4249 return;
4250 }
4251
4252 // Merge "used" flag.
4253 if (Old->getMostRecentDecl()->isUsed(false))
4254 New->setIsUsed();
4255
4256 // Keep a chain of previous declarations.
4257 New->setPreviousDecl(Old);
4258 if (NewTemplate)
4259 NewTemplate->setPreviousDecl(OldTemplate);
4260 adjustDeclContextForDeclaratorDecl(New, Old);
4261
4262 // Inherit access appropriately.
4263 New->setAccess(Old->getAccess());
4264 if (NewTemplate)
4265 NewTemplate->setAccess(New->getAccess());
4266
4267 if (Old->isInline())
4268 New->setImplicitlyInline();
4269}
4270
4271void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4272 SourceManager &SrcMgr = getSourceManager();
4273 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4274 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4275 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4276 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4277 auto &HSI = PP.getHeaderSearchInfo();
4278 StringRef HdrFilename =
4279 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4280
4281 auto noteFromModuleOrInclude = [&](Module *Mod,
4282 SourceLocation IncLoc) -> bool {
4283 // Redefinition errors with modules are common with non modular mapped
4284 // headers, example: a non-modular header H in module A that also gets
4285 // included directly in a TU. Pointing twice to the same header/definition
4286 // is confusing, try to get better diagnostics when modules is on.
4287 if (IncLoc.isValid()) {
4288 if (Mod) {
4289 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4290 << HdrFilename.str() << Mod->getFullModuleName();
4291 if (!Mod->DefinitionLoc.isInvalid())
4292 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4293 << Mod->getFullModuleName();
4294 } else {
4295 Diag(IncLoc, diag::note_redefinition_include_same_file)
4296 << HdrFilename.str();
4297 }
4298 return true;
4299 }
4300
4301 return false;
4302 };
4303
4304 // Is it the same file and same offset? Provide more information on why
4305 // this leads to a redefinition error.
4306 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4307 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4308 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4309 bool EmittedDiag =
4310 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4311 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4312
4313 // If the header has no guards, emit a note suggesting one.
4314 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4315 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4316
4317 if (EmittedDiag)
4318 return;
4319 }
4320
4321 // Redefinition coming from different files or couldn't do better above.
4322 if (Old->getLocation().isValid())
4323 Diag(Old->getLocation(), diag::note_previous_definition);
4324}
4325
4326/// We've just determined that \p Old and \p New both appear to be definitions
4327/// of the same variable. Either diagnose or fix the problem.
4328bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4329 if (!hasVisibleDefinition(Old) &&
4330 (New->getFormalLinkage() == InternalLinkage ||
4331 New->isInline() ||
4332 New->getDescribedVarTemplate() ||
4333 New->getNumTemplateParameterLists() ||
4334 New->getDeclContext()->isDependentContext())) {
4335 // The previous definition is hidden, and multiple definitions are
4336 // permitted (in separate TUs). Demote this to a declaration.
4337 New->demoteThisDefinitionToDeclaration();
4338
4339 // Make the canonical definition visible.
4340 if (auto *OldTD = Old->getDescribedVarTemplate())
4341 makeMergedDefinitionVisible(OldTD);
4342 makeMergedDefinitionVisible(Old);
4343 return false;
4344 } else {
4345 Diag(New->getLocation(), diag::err_redefinition) << New;
4346 notePreviousDefinition(Old, New->getLocation());
4347 New->setInvalidDecl();
4348 return true;
4349 }
4350}
4351
4352/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4353/// no declarator (e.g. "struct foo;") is parsed.
4354Decl *
4355Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4356 RecordDecl *&AnonRecord) {
4357 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4358 AnonRecord);
4359}
4360
4361// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4362// disambiguate entities defined in different scopes.
4363// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4364// compatibility.
4365// We will pick our mangling number depending on which version of MSVC is being
4366// targeted.
4367static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4368 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4369 ? S->getMSCurManglingNumber()
4370 : S->getMSLastManglingNumber();
4371}
4372
4373void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4374 if (!Context.getLangOpts().CPlusPlus)
4375 return;
4376
4377 if (isa<CXXRecordDecl>(Tag->getParent())) {
4378 // If this tag is the direct child of a class, number it if
4379 // it is anonymous.
4380 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4381 return;
4382 MangleNumberingContext &MCtx =
4383 Context.getManglingNumberContext(Tag->getParent());
4384 Context.setManglingNumber(
4385 Tag, MCtx.getManglingNumber(
4386 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4387 return;
4388 }
4389
4390 // If this tag isn't a direct child of a class, number it if it is local.
4391 MangleNumberingContext *MCtx;
4392 Decl *ManglingContextDecl;
4393 std::tie(MCtx, ManglingContextDecl) =
4394 getCurrentMangleNumberContext(Tag->getDeclContext());
4395 if (MCtx) {
4396 Context.setManglingNumber(
4397 Tag, MCtx->getManglingNumber(
4398 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4399 }
4400}
4401
4402namespace {
4403struct NonCLikeKind {
4404 enum {
4405 None,
4406 BaseClass,
4407 DefaultMemberInit,
4408 Lambda,
4409 Friend,
4410 OtherMember,
4411 Invalid,
4412 } Kind = None;
4413 SourceRange Range;
4414
4415 explicit operator bool() { return Kind != None; }
4416};
4417}
4418
4419/// Determine whether a class is C-like, according to the rules of C++
4420/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4421static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4422 if (RD->isInvalidDecl())
4423 return {NonCLikeKind::Invalid, {}};
4424
4425 // C++ [dcl.typedef]p9: [P1766R1]
4426 // An unnamed class with a typedef name for linkage purposes shall not
4427 //
4428 // -- have any base classes
4429 if (RD->getNumBases())
4430 return {NonCLikeKind::BaseClass,
4431 SourceRange(RD->bases_begin()->getBeginLoc(),
4432 RD->bases_end()[-1].getEndLoc())};
4433 bool Invalid = false;
4434 for (Decl *D : RD->decls()) {
4435 // Don't complain about things we already diagnosed.
4436 if (D->isInvalidDecl()) {
4437 Invalid = true;
4438 continue;
4439 }
4440
4441 // -- have any [...] default member initializers
4442 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4443 if (FD->hasInClassInitializer()) {
4444 auto *Init = FD->getInClassInitializer();
4445 return {NonCLikeKind::DefaultMemberInit,
4446 Init ? Init->getSourceRange() : D->getSourceRange()};
4447 }
4448 continue;
4449 }
4450
4451 // FIXME: We don't allow friend declarations. This violates the wording of
4452 // P1766, but not the intent.
4453 if (isa<FriendDecl>(D))
4454 return {NonCLikeKind::Friend, D->getSourceRange()};
4455
4456 // -- declare any members other than non-static data members, member
4457 // enumerations, or member classes,
4458 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4459 isa<EnumDecl>(D))
4460 continue;
4461 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4462 if (!MemberRD) {
4463 if (D->isImplicit())
4464 continue;
4465 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4466 }
4467
4468 // -- contain a lambda-expression,
4469 if (MemberRD->isLambda())
4470 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4471
4472 // and all member classes shall also satisfy these requirements
4473 // (recursively).
4474 if (MemberRD->isThisDeclarationADefinition()) {
4475 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4476 return Kind;
4477 }
4478 }
4479
4480 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4481}
4482
4483void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4484 TypedefNameDecl *NewTD) {
4485 if (TagFromDeclSpec->isInvalidDecl())
4486 return;
4487
4488 // Do nothing if the tag already has a name for linkage purposes.
4489 if (TagFromDeclSpec->hasNameForLinkage())
4490 return;
4491
4492 // A well-formed anonymous tag must always be a TUK_Definition.
4493 assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast
<void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4493, __PRETTY_FUNCTION__))
;
4494
4495 // The type must match the tag exactly; no qualifiers allowed.
4496 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4497 Context.getTagDeclType(TagFromDeclSpec))) {
4498 if (getLangOpts().CPlusPlus)
4499 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4500 return;
4501 }
4502
4503 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4504 // An unnamed class with a typedef name for linkage purposes shall [be
4505 // C-like].
4506 //
4507 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4508 // shouldn't happen, but there are constructs that the language rule doesn't
4509 // disallow for which we can't reasonably avoid computing linkage early.
4510 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4511 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4512 : NonCLikeKind();
4513 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4514 if (NonCLike || ChangesLinkage) {
4515 if (NonCLike.Kind == NonCLikeKind::Invalid)
4516 return;
4517
4518 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4519 if (ChangesLinkage) {
4520 // If the linkage changes, we can't accept this as an extension.
4521 if (NonCLike.Kind == NonCLikeKind::None)
4522 DiagID = diag::err_typedef_changes_linkage;
4523 else
4524 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4525 }
4526
4527 SourceLocation FixitLoc =
4528 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4529 llvm::SmallString<40> TextToInsert;
4530 TextToInsert += ' ';
4531 TextToInsert += NewTD->getIdentifier()->getName();
4532
4533 Diag(FixitLoc, DiagID)
4534 << isa<TypeAliasDecl>(NewTD)
4535 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4536 if (NonCLike.Kind != NonCLikeKind::None) {
4537 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4538 << NonCLike.Kind - 1 << NonCLike.Range;
4539 }
4540 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4541 << NewTD << isa<TypeAliasDecl>(NewTD);
4542
4543 if (ChangesLinkage)
4544 return;
4545 }
4546
4547 // Otherwise, set this as the anon-decl typedef for the tag.
4548 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4549}
4550
4551static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4552 switch (T) {
4553 case DeclSpec::TST_class:
4554 return 0;
4555 case DeclSpec::TST_struct:
4556 return 1;
4557 case DeclSpec::TST_interface:
4558 return 2;
4559 case DeclSpec::TST_union:
4560 return 3;
4561 case DeclSpec::TST_enum:
4562 return 4;
4563 default:
4564 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4564)
;
4565 }
4566}
4567
4568/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4569/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4570/// parameters to cope with template friend declarations.
4571Decl *
4572Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4573 MultiTemplateParamsArg TemplateParams,
4574 bool IsExplicitInstantiation,
4575 RecordDecl *&AnonRecord) {
4576 Decl *TagD = nullptr;
4577 TagDecl *Tag = nullptr;
4578 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4579 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4580 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4581 DS.getTypeSpecType() == DeclSpec::TST_union ||
4582 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4583 TagD = DS.getRepAsDecl();
4584
4585 if (!TagD) // We probably had an error
4586 return nullptr;
4587
4588 // Note that the above type specs guarantee that the
4589 // type rep is a Decl, whereas in many of the others
4590 // it's a Type.
4591 if (isa<TagDecl>(TagD))
4592 Tag = cast<TagDecl>(TagD);
4593 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4594 Tag = CTD->getTemplatedDecl();
4595 }
4596
4597 if (Tag) {
4598 handleTagNumbering(Tag, S);
4599 Tag->setFreeStanding();
4600 if (Tag->isInvalidDecl())
4601 return Tag;
4602 }
4603
4604 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4605 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4606 // or incomplete types shall not be restrict-qualified."
4607 if (TypeQuals & DeclSpec::TQ_restrict)
4608 Diag(DS.getRestrictSpecLoc(),
4609 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4610 << DS.getSourceRange();
4611 }
4612
4613 if (DS.isInlineSpecified())
4614 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4615 << getLangOpts().CPlusPlus17;
4616
4617 if (DS.hasConstexprSpecifier()) {
4618 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4619 // and definitions of functions and variables.
4620 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4621 // the declaration of a function or function template
4622 if (Tag)
4623 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4624 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4625 << DS.getConstexprSpecifier();
4626 else
4627 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4628 << DS.getConstexprSpecifier();
4629 // Don't emit warnings after this error.
4630 return TagD;
4631 }
4632
4633 DiagnoseFunctionSpecifiers(DS);
4634
4635 if (DS.isFriendSpecified()) {
4636 // If we're dealing with a decl but not a TagDecl, assume that
4637 // whatever routines created it handled the friendship aspect.
4638 if (TagD && !Tag)
4639 return nullptr;
4640 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4641 }
4642
4643 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4644 bool IsExplicitSpecialization =
4645 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4646 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4647 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4648 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4649 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4650 // nested-name-specifier unless it is an explicit instantiation
4651 // or an explicit specialization.
4652 //
4653 // FIXME: We allow class template partial specializations here too, per the
4654 // obvious intent of DR1819.
4655 //
4656 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4657 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4658 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4659 return nullptr;
4660 }
4661
4662 // Track whether this decl-specifier declares anything.
4663 bool DeclaresAnything = true;
4664
4665 // Handle anonymous struct definitions.
4666 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4667 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4668 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4669 if (getLangOpts().CPlusPlus ||
4670 Record->getDeclContext()->isRecord()) {
4671 // If CurContext is a DeclContext that can contain statements,
4672 // RecursiveASTVisitor won't visit the decls that
4673 // BuildAnonymousStructOrUnion() will put into CurContext.
4674 // Also store them here so that they can be part of the
4675 // DeclStmt that gets created in this case.
4676 // FIXME: Also return the IndirectFieldDecls created by
4677 // BuildAnonymousStructOr union, for the same reason?
4678 if (CurContext->isFunctionOrMethod())
4679 AnonRecord = Record;
4680 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4681 Context.getPrintingPolicy());
4682 }
4683
4684 DeclaresAnything = false;
4685 }
4686 }
4687
4688 // C11 6.7.2.1p2:
4689 // A struct-declaration that does not declare an anonymous structure or
4690 // anonymous union shall contain a struct-declarator-list.
4691 //
4692 // This rule also existed in C89 and C99; the grammar for struct-declaration
4693 // did not permit a struct-declaration without a struct-declarator-list.
4694 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4695 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4696 // Check for Microsoft C extension: anonymous struct/union member.
4697 // Handle 2 kinds of anonymous struct/union:
4698 // struct STRUCT;
4699 // union UNION;
4700 // and
4701 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4702 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4703 if ((Tag && Tag->getDeclName()) ||
4704 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4705 RecordDecl *Record = nullptr;
4706 if (Tag)
4707 Record = dyn_cast<RecordDecl>(Tag);
4708 else if (const RecordType *RT =
4709 DS.getRepAsType().get()->getAsStructureType())
4710 Record = RT->getDecl();
4711 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4712 Record = UT->getDecl();
4713
4714 if (Record && getLangOpts().MicrosoftExt) {
4715 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4716 << Record->isUnion() << DS.getSourceRange();
4717 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4718 }
4719
4720 DeclaresAnything = false;
4721 }
4722 }
4723
4724 // Skip all the checks below if we have a type error.
4725 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4726 (TagD && TagD->isInvalidDecl()))
4727 return TagD;
4728
4729 if (getLangOpts().CPlusPlus &&
4730 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4731 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4732 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4733 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4734 DeclaresAnything = false;
4735
4736 if (!DS.isMissingDeclaratorOk()) {
4737 // Customize diagnostic for a typedef missing a name.
4738 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4739 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4740 << DS.getSourceRange();
4741 else
4742 DeclaresAnything = false;
4743 }
4744
4745 if (DS.isModulePrivateSpecified() &&
4746 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4747 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4748 << Tag->getTagKind()
4749 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4750
4751 ActOnDocumentableDecl(TagD);
4752
4753 // C 6.7/2:
4754 // A declaration [...] shall declare at least a declarator [...], a tag,
4755 // or the members of an enumeration.
4756 // C++ [dcl.dcl]p3:
4757 // [If there are no declarators], and except for the declaration of an
4758 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4759 // names into the program, or shall redeclare a name introduced by a
4760 // previous declaration.
4761 if (!DeclaresAnything) {
4762 // In C, we allow this as a (popular) extension / bug. Don't bother
4763 // producing further diagnostics for redundant qualifiers after this.
4764 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4765 ? diag::err_no_declarators
4766 : diag::ext_no_declarators)
4767 << DS.getSourceRange();
4768 return TagD;
4769 }
4770
4771 // C++ [dcl.stc]p1:
4772 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4773 // init-declarator-list of the declaration shall not be empty.
4774 // C++ [dcl.fct.spec]p1:
4775 // If a cv-qualifier appears in a decl-specifier-seq, the
4776 // init-declarator-list of the declaration shall not be empty.
4777 //
4778 // Spurious qualifiers here appear to be valid in C.
4779 unsigned DiagID = diag::warn_standalone_specifier;
4780 if (getLangOpts().CPlusPlus)
4781 DiagID = diag::ext_standalone_specifier;
4782
4783 // Note that a linkage-specification sets a storage class, but
4784 // 'extern "C" struct foo;' is actually valid and not theoretically
4785 // useless.
4786 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4787 if (SCS == DeclSpec::SCS_mutable)
4788 // Since mutable is not a viable storage class specifier in C, there is
4789 // no reason to treat it as an extension. Instead, diagnose as an error.
4790 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4791 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4792 Diag(DS.getStorageClassSpecLoc(), DiagID)
4793 << DeclSpec::getSpecifierName(SCS);
4794 }
4795
4796 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4797 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4798 << DeclSpec::getSpecifierName(TSCS);
4799 if (DS.getTypeQualifiers()) {
4800 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4801 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4802 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4803 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4804 // Restrict is covered above.
4805 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4806 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4807 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4808 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4809 }
4810
4811 // Warn about ignored type attributes, for example:
4812 // __attribute__((aligned)) struct A;
4813 // Attributes should be placed after tag to apply to type declaration.
4814 if (!DS.getAttributes().empty()) {
4815 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4816 if (TypeSpecType == DeclSpec::TST_class ||
4817 TypeSpecType == DeclSpec::TST_struct ||
4818 TypeSpecType == DeclSpec::TST_interface ||
4819 TypeSpecType == DeclSpec::TST_union ||
4820 TypeSpecType == DeclSpec::TST_enum) {
4821 for (const ParsedAttr &AL : DS.getAttributes())
4822 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4823 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4824 }
4825 }
4826
4827 return TagD;
4828}
4829
4830/// We are trying to inject an anonymous member into the given scope;
4831/// check if there's an existing declaration that can't be overloaded.
4832///
4833/// \return true if this is a forbidden redeclaration
4834static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4835 Scope *S,
4836 DeclContext *Owner,
4837 DeclarationName Name,
4838 SourceLocation NameLoc,
4839 bool IsUnion) {
4840 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4841 Sema::ForVisibleRedeclaration);
4842 if (!SemaRef.LookupName(R, S)) return false;
4843
4844 // Pick a representative declaration.
4845 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4846 assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast
<void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4846, __PRETTY_FUNCTION__))
;
4847
4848 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4849 return false;
4850
4851 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4852 << IsUnion << Name;
4853 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4854
4855 return true;
4856}
4857
4858/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4859/// anonymous struct or union AnonRecord into the owning context Owner
4860/// and scope S. This routine will be invoked just after we realize
4861/// that an unnamed union or struct is actually an anonymous union or
4862/// struct, e.g.,
4863///
4864/// @code
4865/// union {
4866/// int i;
4867/// float f;
4868/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4869/// // f into the surrounding scope.x
4870/// @endcode
4871///
4872/// This routine is recursive, injecting the names of nested anonymous
4873/// structs/unions into the owning context and scope as well.
4874static bool
4875InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4876 RecordDecl *AnonRecord, AccessSpecifier AS,
4877 SmallVectorImpl<NamedDecl *> &Chaining) {
4878 bool Invalid = false;
4879
4880 // Look every FieldDecl and IndirectFieldDecl with a name.
4881 for (auto *D : AnonRecord->decls()) {
4882 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4883 cast<NamedDecl>(D)->getDeclName()) {
4884 ValueDecl *VD = cast<ValueDecl>(D);
4885 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4886 VD->getLocation(),
4887 AnonRecord->isUnion())) {
4888 // C++ [class.union]p2:
4889 // The names of the members of an anonymous union shall be
4890 // distinct from the names of any other entity in the
4891 // scope in which the anonymous union is declared.
4892 Invalid = true;
4893 } else {
4894 // C++ [class.union]p2:
4895 // For the purpose of name lookup, after the anonymous union
4896 // definition, the members of the anonymous union are
4897 // considered to have been defined in the scope in which the
4898 // anonymous union is declared.
4899 unsigned OldChainingSize = Chaining.size();
4900 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4901 Chaining.append(IF->chain_begin(), IF->chain_end());
4902 else
4903 Chaining.push_back(VD);
4904
4905 assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail
("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4905, __PRETTY_FUNCTION__))
;
4906 NamedDecl **NamedChain =
4907 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4908 for (unsigned i = 0; i < Chaining.size(); i++)
4909 NamedChain[i] = Chaining[i];
4910
4911 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4912 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4913 VD->getType(), {NamedChain, Chaining.size()});
4914
4915 for (const auto *Attr : VD->attrs())
4916 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4917
4918 IndirectField->setAccess(AS);
4919 IndirectField->setImplicit();
4920 SemaRef.PushOnScopeChains(IndirectField, S);
4921
4922 // That includes picking up the appropriate access specifier.
4923 if (AS != AS_none) IndirectField->setAccess(AS);
4924
4925 Chaining.resize(OldChainingSize);
4926 }
4927 }
4928 }
4929
4930 return Invalid;
4931}
4932
4933/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4934/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4935/// illegal input values are mapped to SC_None.
4936static StorageClass
4937StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4938 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4939 assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."
) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4940, __PRETTY_FUNCTION__))
4940 "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl."
) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4940, __PRETTY_FUNCTION__))
;
4941 switch (StorageClassSpec) {
4942 case DeclSpec::SCS_unspecified: return SC_None;
4943 case DeclSpec::SCS_extern:
4944 if (DS.isExternInLinkageSpec())
4945 return SC_None;
4946 return SC_Extern;
4947 case DeclSpec::SCS_static: return SC_Static;
4948 case DeclSpec::SCS_auto: return SC_Auto;
4949 case DeclSpec::SCS_register: return SC_Register;
4950 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4951 // Illegal SCSs map to None: error reporting is up to the caller.
4952 case DeclSpec::SCS_mutable: // Fall through.
4953 case DeclSpec::SCS_typedef: return SC_None;
4954 }
4955 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4955)
;
4956}
4957
4958static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4959 assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4959, __PRETTY_FUNCTION__))
;
4960
4961 for (const auto *I : Record->decls()) {
4962 const auto *FD = dyn_cast<FieldDecl>(I);
4963 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4964 FD = IFD->getAnonField();
4965 if (FD && FD->hasInClassInitializer())
4966 return FD->getLocation();
4967 }
4968
4969 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 4969)
;
4970}
4971
4972static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4973 SourceLocation DefaultInitLoc) {
4974 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4975 return;
4976
4977 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4978 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4979}
4980
4981static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4982 CXXRecordDecl *AnonUnion) {
4983 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4984 return;
4985
4986 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4987}
4988
4989/// BuildAnonymousStructOrUnion - Handle the declaration of an
4990/// anonymous structure or union. Anonymous unions are a C++ feature
4991/// (C++ [class.union]) and a C11 feature; anonymous structures
4992/// are a C11 feature and GNU C++ extension.
4993Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4994 AccessSpecifier AS,
4995 RecordDecl *Record,
4996 const PrintingPolicy &Policy) {
4997 DeclContext *Owner = Record->getDeclContext();
4998
4999 // Diagnose whether this anonymous struct/union is an extension.
5000 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5001 Diag(Record->getLocation(), diag::ext_anonymous_union);
5002 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5003 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5004 else if (!Record->isUnion() && !getLangOpts().C11)
5005 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5006
5007 // C and C++ require different kinds of checks for anonymous
5008 // structs/unions.
5009 bool Invalid = false;
5010 if (getLangOpts().CPlusPlus) {
5011 const char *PrevSpec = nullptr;
5012 if (Record->isUnion()) {
5013 // C++ [class.union]p6:
5014 // C++17 [class.union.anon]p2:
5015 // Anonymous unions declared in a named namespace or in the
5016 // global namespace shall be declared static.
5017 unsigned DiagID;
5018 DeclContext *OwnerScope = Owner->getRedeclContext();
5019 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5020 (OwnerScope->isTranslationUnit() ||
5021 (OwnerScope->isNamespace() &&
5022 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5023 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5024 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5025
5026 // Recover by adding 'static'.
5027 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5028 PrevSpec, DiagID, Policy);
5029 }
5030 // C++ [class.union]p6:
5031 // A storage class is not allowed in a declaration of an
5032 // anonymous union in a class scope.
5033 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5034 isa<RecordDecl>(Owner)) {
5035 Diag(DS.getStorageClassSpecLoc(),
5036 diag::err_anonymous_union_with_storage_spec)
5037 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5038
5039 // Recover by removing the storage specifier.
5040 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5041 SourceLocation(),
5042 PrevSpec, DiagID, Context.getPrintingPolicy());
5043 }
5044 }
5045
5046 // Ignore const/volatile/restrict qualifiers.
5047 if (DS.getTypeQualifiers()) {
5048 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5049 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5050 << Record->isUnion() << "const"
5051 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5052 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5053 Diag(DS.getVolatileSpecLoc(),
5054 diag::ext_anonymous_struct_union_qualified)
5055 << Record->isUnion() << "volatile"
5056 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5057 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5058 Diag(DS.getRestrictSpecLoc(),
5059 diag::ext_anonymous_struct_union_qualified)
5060 << Record->isUnion() << "restrict"
5061 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5062 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5063 Diag(DS.getAtomicSpecLoc(),
5064 diag::ext_anonymous_struct_union_qualified)
5065 << Record->isUnion() << "_Atomic"
5066 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5067 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5068 Diag(DS.getUnalignedSpecLoc(),
5069 diag::ext_anonymous_struct_union_qualified)
5070 << Record->isUnion() << "__unaligned"
5071 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5072
5073 DS.ClearTypeQualifiers();
5074 }
5075
5076 // C++ [class.union]p2:
5077 // The member-specification of an anonymous union shall only
5078 // define non-static data members. [Note: nested types and
5079 // functions cannot be declared within an anonymous union. ]
5080 for (auto *Mem : Record->decls()) {
5081 // Ignore invalid declarations; we already diagnosed them.
5082 if (Mem->isInvalidDecl())
5083 continue;
5084
5085 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5086 // C++ [class.union]p3:
5087 // An anonymous union shall not have private or protected
5088 // members (clause 11).
5089 assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0
) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 5089, __PRETTY_FUNCTION__))
;
5090 if (FD->getAccess() != AS_public) {
5091 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5092 << Record->isUnion() << (FD->getAccess() == AS_protected);
5093 Invalid = true;
5094 }
5095
5096 // C++ [class.union]p1
5097 // An object of a class with a non-trivial constructor, a non-trivial
5098 // copy constructor, a non-trivial destructor, or a non-trivial copy
5099 // assignment operator cannot be a member of a union, nor can an
5100 // array of such objects.
5101 if (CheckNontrivialField(FD))
5102 Invalid = true;
5103 } else if (Mem->isImplicit()) {
5104 // Any implicit members are fine.
5105 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5106 // This is a type that showed up in an
5107 // elaborated-type-specifier inside the anonymous struct or
5108 // union, but which actually declares a type outside of the
5109 // anonymous struct or union. It's okay.
5110 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5111 if (!MemRecord->isAnonymousStructOrUnion() &&
5112 MemRecord->getDeclName()) {
5113 // Visual C++ allows type definition in anonymous struct or union.
5114 if (getLangOpts().MicrosoftExt)
5115 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5116 << Record->isUnion();
5117 else {
5118 // This is a nested type declaration.
5119 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5120 << Record->isUnion();
5121 Invalid = true;
5122 }
5123 } else {
5124 // This is an anonymous type definition within another anonymous type.
5125 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5126 // not part of standard C++.
5127 Diag(MemRecord->getLocation(),
5128 diag::ext_anonymous_record_with_anonymous_type)
5129 << Record->isUnion();
5130 }
5131 } else if (isa<AccessSpecDecl>(Mem)) {
5132 // Any access specifier is fine.
5133 } else if (isa<StaticAssertDecl>(Mem)) {
5134 // In C++1z, static_assert declarations are also fine.
5135 } else {
5136 // We have something that isn't a non-static data
5137 // member. Complain about it.
5138 unsigned DK = diag::err_anonymous_record_bad_member;
5139 if (isa<TypeDecl>(Mem))
5140 DK = diag::err_anonymous_record_with_type;
5141 else if (isa<FunctionDecl>(Mem))
5142 DK = diag::err_anonymous_record_with_function;
5143 else if (isa<VarDecl>(Mem))
5144 DK = diag::err_anonymous_record_with_static;
5145
5146 // Visual C++ allows type definition in anonymous struct or union.
5147 if (getLangOpts().MicrosoftExt &&
5148 DK == diag::err_anonymous_record_with_type)
5149 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5150 << Record->isUnion();
5151 else {
5152 Diag(Mem->getLocation(), DK) << Record->isUnion();
5153 Invalid = true;
5154 }
5155 }
5156 }
5157
5158 // C++11 [class.union]p8 (DR1460):
5159 // At most one variant member of a union may have a
5160 // brace-or-equal-initializer.
5161 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5162 Owner->isRecord())
5163 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5164 cast<CXXRecordDecl>(Record));
5165 }
5166
5167 if (!Record->isUnion() && !Owner->isRecord()) {
5168 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5169 << getLangOpts().CPlusPlus;
5170 Invalid = true;
5171 }
5172
5173 // C++ [dcl.dcl]p3:
5174 // [If there are no declarators], and except for the declaration of an
5175 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5176 // names into the program
5177 // C++ [class.mem]p2:
5178 // each such member-declaration shall either declare at least one member
5179 // name of the class or declare at least one unnamed bit-field
5180 //
5181 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5182 if (getLangOpts().CPlusPlus && Record->field_empty())
5183 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5184
5185 // Mock up a declarator.
5186 Declarator Dc(DS, DeclaratorContext::MemberContext);
5187 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5188 assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union"
) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 5188, __PRETTY_FUNCTION__))
;
5189
5190 // Create a declaration for this anonymous struct/union.
5191 NamedDecl *Anon = nullptr;
5192 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5193 Anon = FieldDecl::Create(
5194 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5195 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5196 /*BitWidth=*/nullptr, /*Mutable=*/false,
5197 /*InitStyle=*/ICIS_NoInit);
5198 Anon->setAccess(AS);
5199 ProcessDeclAttributes(S, Anon, Dc);
5200
5201 if (getLangOpts().CPlusPlus)
5202 FieldCollector->Add(cast<FieldDecl>(Anon));
5203 } else {
5204 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5205 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5206 if (SCSpec == DeclSpec::SCS_mutable) {
5207 // mutable can only appear on non-static class members, so it's always
5208 // an error here
5209 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5210 Invalid = true;
5211 SC = SC_None;
5212 }
5213
5214 assert(DS.getAttributes().empty() && "No attribute expected")((DS.getAttributes().empty() && "No attribute expected"
) ? static_cast<void> (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 5214, __PRETTY_FUNCTION__))
;
5215 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5216 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5217 Context.getTypeDeclType(Record), TInfo, SC);
5218
5219 // Default-initialize the implicit variable. This initialization will be
5220 // trivial in almost all cases, except if a union member has an in-class
5221 // initializer:
5222 // union { int n = 0; };
5223 ActOnUninitializedDecl(Anon);
5224 }
5225 Anon->setImplicit();
5226
5227 // Mark this as an anonymous struct/union type.
5228 Record->setAnonymousStructOrUnion(true);
5229
5230 // Add the anonymous struct/union object to the current
5231 // context. We'll be referencing this object when we refer to one of
5232 // its members.
5233 Owner->addDecl(Anon);
5234
5235 // Inject the members of the anonymous struct/union into the owning
5236 // context and into the identifier resolver chain for name lookup
5237 // purposes.
5238 SmallVector<NamedDecl*, 2> Chain;
5239 Chain.push_back(Anon);
5240
5241 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5242 Invalid = true;
5243
5244 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5245 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5246 MangleNumberingContext *MCtx;
5247 Decl *ManglingContextDecl;
5248 std::tie(MCtx, ManglingContextDecl) =
5249 getCurrentMangleNumberContext(NewVD->getDeclContext());
5250 if (MCtx) {
5251 Context.setManglingNumber(
5252 NewVD, MCtx->getManglingNumber(
5253 NewVD, getMSManglingNumber(getLangOpts(), S)));
5254 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5255 }
5256 }
5257 }
5258
5259 if (Invalid)
5260 Anon->setInvalidDecl();
5261
5262 return Anon;
5263}
5264
5265/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5266/// Microsoft C anonymous structure.
5267/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5268/// Example:
5269///
5270/// struct A { int a; };
5271/// struct B { struct A; int b; };
5272///
5273/// void foo() {
5274/// B var;
5275/// var.a = 3;
5276/// }
5277///
5278Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5279 RecordDecl *Record) {
5280 assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void
> (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 5280, __PRETTY_FUNCTION__))
;
5281
5282 // Mock up a declarator.
5283 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5284 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5285 assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct"
) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 5285, __PRETTY_FUNCTION__))
;
5286
5287 auto *ParentDecl = cast<RecordDecl>(CurContext);
5288 QualType RecTy = Context.getTypeDeclType(Record);
5289
5290 // Create a declaration for this anonymous struct.
5291 NamedDecl *Anon =
5292 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5293 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5294 /*BitWidth=*/nullptr, /*Mutable=*/false,
5295 /*InitStyle=*/ICIS_NoInit);
5296 Anon->setImplicit();
5297
5298 // Add the anonymous struct object to the current context.
5299 CurContext->addDecl(Anon);
5300
5301 // Inject the members of the anonymous struct into the current
5302 // context and into the identifier resolver chain for name lookup
5303 // purposes.
5304 SmallVector<NamedDecl*, 2> Chain;
5305 Chain.push_back(Anon);
5306
5307 RecordDecl *RecordDef = Record->getDefinition();
5308 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5309 diag::err_field_incomplete_or_sizeless) ||
5310 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5311 AS_none, Chain)) {
5312 Anon->setInvalidDecl();
5313 ParentDecl->setInvalidDecl();
5314 }
5315
5316 return Anon;
5317}
5318
5319/// GetNameForDeclarator - Determine the full declaration name for the
5320/// given Declarator.
5321DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5322 return GetNameFromUnqualifiedId(D.getName());
5323}
5324
5325/// Retrieves the declaration name from a parsed unqualified-id.
5326DeclarationNameInfo
5327Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5328 DeclarationNameInfo NameInfo;
5329 NameInfo.setLoc(Name.StartLocation);
5330
5331 switch (Name.getKind()) {
5332
5333 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5334 case UnqualifiedIdKind::IK_Identifier:
5335 NameInfo.setName(Name.Identifier);
5336 return NameInfo;
5337
5338 case UnqualifiedIdKind::IK_DeductionGuideName: {
5339 // C++ [temp.deduct.guide]p3:
5340 // The simple-template-id shall name a class template specialization.
5341 // The template-name shall be the same identifier as the template-name
5342 // of the simple-template-id.
5343 // These together intend to imply that the template-name shall name a
5344 // class template.
5345 // FIXME: template<typename T> struct X {};
5346 // template<typename T> using Y = X<T>;
5347 // Y(int) -> Y<int>;
5348 // satisfies these rules but does not name a class template.
5349 TemplateName TN = Name.TemplateName.get().get();
5350 auto *Template = TN.getAsTemplateDecl();
5351 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5352 Diag(Name.StartLocation,
5353 diag::err_deduction_guide_name_not_class_template)
5354 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5355 if (Template)
5356 Diag(Template->getLocation(), diag::note_template_decl_here);
5357 return DeclarationNameInfo();
5358 }
5359
5360 NameInfo.setName(
5361 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5362 return NameInfo;
5363 }
5364
5365 case UnqualifiedIdKind::IK_OperatorFunctionId:
5366 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5367 Name.OperatorFunctionId.Operator));
5368 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5369 = Name.OperatorFunctionId.SymbolLocations[0];
5370 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5371 = Name.EndLocation.getRawEncoding();
5372 return NameInfo;
5373
5374 case UnqualifiedIdKind::IK_LiteralOperatorId:
5375 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5376 Name.Identifier));
5377 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5378 return NameInfo;
5379
5380 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5381 TypeSourceInfo *TInfo;
5382 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5383 if (Ty.isNull())
5384 return DeclarationNameInfo();
5385 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5386 Context.getCanonicalType(Ty)));
5387 NameInfo.setNamedTypeInfo(TInfo);
5388 return NameInfo;
5389 }
5390
5391 case UnqualifiedIdKind::IK_ConstructorName: {
5392 TypeSourceInfo *TInfo;
5393 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5394 if (Ty.isNull())
5395 return DeclarationNameInfo();
5396 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5397 Context.getCanonicalType(Ty)));
5398 NameInfo.setNamedTypeInfo(TInfo);
5399 return NameInfo;
5400 }
5401
5402 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5403 // In well-formed code, we can only have a constructor
5404 // template-id that refers to the current context, so go there
5405 // to find the actual type being constructed.
5406 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5407 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5408 return DeclarationNameInfo();
5409
5410 // Determine the type of the class being constructed.
5411 QualType CurClassType = Context.getTypeDeclType(CurClass);
5412
5413 // FIXME: Check two things: that the template-id names the same type as
5414 // CurClassType, and that the template-id does not occur when the name
5415 // was qualified.
5416
5417 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5418 Context.getCanonicalType(CurClassType)));
5419 // FIXME: should we retrieve TypeSourceInfo?
5420 NameInfo.setNamedTypeInfo(nullptr);
5421 return NameInfo;
5422 }
5423
5424 case UnqualifiedIdKind::IK_DestructorName: {
5425 TypeSourceInfo *TInfo;
5426 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5427 if (Ty.isNull())
5428 return DeclarationNameInfo();
5429 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5430 Context.getCanonicalType(Ty)));
5431 NameInfo.setNamedTypeInfo(TInfo);
5432 return NameInfo;
5433 }
5434
5435 case UnqualifiedIdKind::IK_TemplateId: {
5436 TemplateName TName = Name.TemplateId->Template.get();
5437 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5438 return Context.getNameForTemplate(TName, TNameLoc);
5439 }
5440
5441 } // switch (Name.getKind())
5442
5443 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 5443)
;
5444}
5445
5446static QualType getCoreType(QualType Ty) {
5447 do {
5448 if (Ty->isPointerType() || Ty->isReferenceType())
5449 Ty = Ty->getPointeeType();
5450 else if (Ty->isArrayType())
5451 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5452 else
5453 return Ty.withoutLocalFastQualifiers();
5454 } while (true);
5455}
5456
5457/// hasSimilarParameters - Determine whether the C++ functions Declaration
5458/// and Definition have "nearly" matching parameters. This heuristic is
5459/// used to improve diagnostics in the case where an out-of-line function
5460/// definition doesn't match any declaration within the class or namespace.
5461/// Also sets Params to the list of indices to the parameters that differ
5462/// between the declaration and the definition. If hasSimilarParameters
5463/// returns true and Params is empty, then all of the parameters match.
5464static bool hasSimilarParameters(ASTContext &Context,
5465 FunctionDecl *Declaration,
5466 FunctionDecl *Definition,
5467 SmallVectorImpl<unsigned> &Params) {
5468 Params.clear();
5469 if (Declaration->param_size() != Definition->param_size())
5470 return false;
5471 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5472 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5473 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5474
5475 // The parameter types are identical
5476 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5477 continue;
5478
5479 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5480 QualType DefParamBaseTy = getCoreType(DefParamTy);
5481 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5482 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5483
5484 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5485 (DeclTyName && DeclTyName == DefTyName))
5486 Params.push_back(Idx);
5487 else // The two parameters aren't even close
5488 return false;
5489 }
5490
5491 return true;
5492}
5493
5494/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5495/// declarator needs to be rebuilt in the current instantiation.
5496/// Any bits of declarator which appear before the name are valid for
5497/// consideration here. That's specifically the type in the decl spec
5498/// and the base type in any member-pointer chunks.
5499static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5500 DeclarationName Name) {
5501 // The types we specifically need to rebuild are:
5502 // - typenames, typeofs, and decltypes
5503 // - types which will become injected class names
5504 // Of course, we also need to rebuild any type referencing such a
5505 // type. It's safest to just say "dependent", but we call out a
5506 // few cases here.
5507
5508 DeclSpec &DS = D.getMutableDeclSpec();
5509 switch (DS.getTypeSpecType()) {
5510 case DeclSpec::TST_typename:
5511 case DeclSpec::TST_typeofType:
5512 case DeclSpec::TST_underlyingType:
5513 case DeclSpec::TST_atomic: {
5514 // Grab the type from the parser.
5515 TypeSourceInfo *TSI = nullptr;
5516 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5517 if (T.isNull() || !T->isDependentType()) break;
5518
5519 // Make sure there's a type source info. This isn't really much
5520 // of a waste; most dependent types should have type source info
5521 // attached already.
5522 if (!TSI)
5523 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5524
5525 // Rebuild the type in the current instantiation.
5526 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5527 if (!TSI) return true;
5528
5529 // Store the new type back in the decl spec.
5530 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5531 DS.UpdateTypeRep(LocType);
5532 break;
5533 }
5534
5535 case DeclSpec::TST_decltype:
5536 case DeclSpec::TST_typeofExpr: {
5537 Expr *E = DS.getRepAsExpr();
5538 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5539 if (Result.isInvalid()) return true;
5540 DS.UpdateExprRep(Result.get());
5541 break;
5542 }
5543
5544 default:
5545 // Nothing to do for these decl specs.
5546 break;
5547 }
5548
5549 // It doesn't matter what order we do this in.
5550 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5551 DeclaratorChunk &Chunk = D.getTypeObject(I);
5552
5553 // The only type information in the declarator which can come
5554 // before the declaration name is the base type of a member
5555 // pointer.
5556 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5557 continue;
5558
5559 // Rebuild the scope specifier in-place.
5560 CXXScopeSpec &SS = Chunk.Mem.Scope();
5561 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5562 return true;
5563 }
5564
5565 return false;
5566}
5567
5568Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5569 D.setFunctionDefinitionKind(FDK_Declaration);
5570 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5571
5572 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5573 Dcl && Dcl->getDeclContext()->isFileContext())
5574 Dcl->setTopLevelDeclInObjCContainer();
5575
5576 if (getLangOpts().OpenCL)
5577 setCurrentOpenCLExtensionForDecl(Dcl);
5578
5579 return Dcl;
5580}
5581
5582/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5583/// If T is the name of a class, then each of the following shall have a
5584/// name different from T:
5585/// - every static data member of class T;
5586/// - every member function of class T
5587/// - every member of class T that is itself a type;
5588/// \returns true if the declaration name violates these rules.
5589bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5590 DeclarationNameInfo NameInfo) {
5591 DeclarationName Name = NameInfo.getName();
5592
5593 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5594 while (Record && Record->isAnonymousStructOrUnion())
5595 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5596 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5597 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5598 return true;
5599 }
5600
5601 return false;
5602}
5603
5604/// Diagnose a declaration whose declarator-id has the given
5605/// nested-name-specifier.
5606///
5607/// \param SS The nested-name-specifier of the declarator-id.
5608///
5609/// \param DC The declaration context to which the nested-name-specifier
5610/// resolves.
5611///
5612/// \param Name The name of the entity being declared.
5613///
5614/// \param Loc The location of the name of the entity being declared.
5615///
5616/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5617/// we're declaring an explicit / partial specialization / instantiation.
5618///
5619/// \returns true if we cannot safely recover from this error, false otherwise.
5620bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5621 DeclarationName Name,
5622 SourceLocation Loc, bool IsTemplateId) {
5623 DeclContext *Cur = CurContext;
5624 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5625 Cur = Cur->getParent();
5626
5627 // If the user provided a superfluous scope specifier that refers back to the
5628 // class in which the entity is already declared, diagnose and ignore it.
5629 //
5630 // class X {
5631 // void X::f();
5632 // };
5633 //
5634 // Note, it was once ill-formed to give redundant qualification in all
5635 // contexts, but that rule was removed by DR482.
5636 if (Cur->Equals(DC)) {
5637 if (Cur->isRecord()) {
5638 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5639 : diag::err_member_extra_qualification)
5640 << Name << FixItHint::CreateRemoval(SS.getRange());
5641 SS.clear();
5642 } else {
5643 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5644 }
5645 return false;
5646 }
5647
5648 // Check whether the qualifying scope encloses the scope of the original
5649 // declaration. For a template-id, we perform the checks in
5650 // CheckTemplateSpecializationScope.
5651 if (!Cur->Encloses(DC) && !IsTemplateId) {
5652 if (Cur->isRecord())
5653 Diag(Loc, diag::err_member_qualification)
5654 << Name << SS.getRange();
5655 else if (isa<TranslationUnitDecl>(DC))
5656 Diag(Loc, diag::err_invalid_declarator_global_scope)
5657 << Name << SS.getRange();
5658 else if (isa<FunctionDecl>(Cur))
5659 Diag(Loc, diag::err_invalid_declarator_in_function)
5660 << Name << SS.getRange();
5661 else if (isa<BlockDecl>(Cur))
5662 Diag(Loc, diag::err_invalid_declarator_in_block)
5663 << Name << SS.getRange();
5664 else
5665 Diag(Loc, diag::err_invalid_declarator_scope)
5666 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5667
5668 return true;
5669 }
5670
5671 if (Cur->isRecord()) {
5672 // Cannot qualify members within a class.
5673 Diag(Loc, diag::err_member_qualification)
5674 << Name << SS.getRange();
5675 SS.clear();
5676
5677 // C++ constructors and destructors with incorrect scopes can break
5678 // our AST invariants by having the wrong underlying types. If
5679 // that's the case, then drop this declaration entirely.
5680 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5681 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5682 !Context.hasSameType(Name.getCXXNameType(),
5683 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5684 return true;
5685
5686 return false;
5687 }
5688
5689 // C++11 [dcl.meaning]p1:
5690 // [...] "The nested-name-specifier of the qualified declarator-id shall
5691 // not begin with a decltype-specifer"
5692 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5693 while (SpecLoc.getPrefix())
5694 SpecLoc = SpecLoc.getPrefix();
5695 if (dyn_cast_or_null<DecltypeType>(
5696 SpecLoc.getNestedNameSpecifier()->getAsType()))
5697 Diag(Loc, diag::err_decltype_in_declarator)
5698 << SpecLoc.getTypeLoc().getSourceRange();
5699
5700 return false;
5701}
5702
5703NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5704 MultiTemplateParamsArg TemplateParamLists) {
5705 // TODO: consider using NameInfo for diagnostic.
5706 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5707 DeclarationName Name = NameInfo.getName();
5708
5709 // All of these full declarators require an identifier. If it doesn't have
5710 // one, the ParsedFreeStandingDeclSpec action should be used.
5711 if (D.isDecompositionDeclarator()) {
5712 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5713 } else if (!Name) {
5714 if (!D.isInvalidType()) // Reject this if we think it is valid.
5715 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5716 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5717 return nullptr;
5718 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5719 return nullptr;
5720
5721 // The scope passed in may not be a decl scope. Zip up the scope tree until
5722 // we find one that is.
5723 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5724 (S->getFlags() & Scope::TemplateParamScope) != 0)
5725 S = S->getParent();
5726
5727 DeclContext *DC = CurContext;
5728 if (D.getCXXScopeSpec().isInvalid())
5729 D.setInvalidType();
5730 else if (D.getCXXScopeSpec().isSet()) {
5731 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5732 UPPC_DeclarationQualifier))
5733 return nullptr;
5734
5735 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5736 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5737 if (!DC || isa<EnumDecl>(DC)) {
5738 // If we could not compute the declaration context, it's because the
5739 // declaration context is dependent but does not refer to a class,
5740 // class template, or class template partial specialization. Complain
5741 // and return early, to avoid the coming semantic disaster.
5742 Diag(D.getIdentifierLoc(),
5743 diag::err_template_qualified_declarator_no_match)
5744 << D.getCXXScopeSpec().getScopeRep()
5745 << D.getCXXScopeSpec().getRange();
5746 return nullptr;
5747 }
5748 bool IsDependentContext = DC->isDependentContext();
5749
5750 if (!IsDependentContext &&
5751 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5752 return nullptr;
5753
5754 // If a class is incomplete, do not parse entities inside it.
5755 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5756 Diag(D.getIdentifierLoc(),
5757 diag::err_member_def_undefined_record)
5758 << Name << DC << D.getCXXScopeSpec().getRange();
5759 return nullptr;
5760 }
5761 if (!D.getDeclSpec().isFriendSpecified()) {
5762 if (diagnoseQualifiedDeclaration(
5763 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5764 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5765 if (DC->isRecord())
5766 return nullptr;
5767
5768 D.setInvalidType();
5769 }
5770 }
5771
5772 // Check whether we need to rebuild the type of the given
5773 // declaration in the current instantiation.
5774 if (EnteringContext && IsDependentContext &&
5775 TemplateParamLists.size() != 0) {
5776 ContextRAII SavedContext(*this, DC);
5777 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5778 D.setInvalidType();
5779 }
5780 }
5781
5782 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5783 QualType R = TInfo->getType();
5784
5785 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5786 UPPC_DeclarationType))
5787 D.setInvalidType();
5788
5789 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5790 forRedeclarationInCurContext());
5791
5792 // See if this is a redefinition of a variable in the same scope.
5793 if (!D.getCXXScopeSpec().isSet()) {
5794 bool IsLinkageLookup = false;
5795 bool CreateBuiltins = false;
5796
5797 // If the declaration we're planning to build will be a function
5798 // or object with linkage, then look for another declaration with
5799 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5800 //
5801 // If the declaration we're planning to build will be declared with
5802 // external linkage in the translation unit, create any builtin with
5803 // the same name.
5804 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5805 /* Do nothing*/;
5806 else if (CurContext->isFunctionOrMethod() &&
5807 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5808 R->isFunctionType())) {
5809 IsLinkageLookup = true;
5810 CreateBuiltins =
5811 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5812 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5813 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5814 CreateBuiltins = true;
5815
5816 if (IsLinkageLookup) {
5817 Previous.clear(LookupRedeclarationWithLinkage);
5818 Previous.setRedeclarationKind(ForExternalRedeclaration);
5819 }
5820
5821 LookupName(Previous, S, CreateBuiltins);
5822 } else { // Something like "int foo::x;"
5823 LookupQualifiedName(Previous, DC);
5824
5825 // C++ [dcl.meaning]p1:
5826 // When the declarator-id is qualified, the declaration shall refer to a
5827 // previously declared member of the class or namespace to which the
5828 // qualifier refers (or, in the case of a namespace, of an element of the
5829 // inline namespace set of that namespace (7.3.1)) or to a specialization
5830 // thereof; [...]
5831 //
5832 // Note that we already checked the context above, and that we do not have
5833 // enough information to make sure that Previous contains the declaration
5834 // we want to match. For example, given:
5835 //
5836 // class X {
5837 // void f();
5838 // void f(float);
5839 // };
5840 //
5841 // void X::f(int) { } // ill-formed
5842 //
5843 // In this case, Previous will point to the overload set
5844 // containing the two f's declared in X, but neither of them
5845 // matches.
5846
5847 // C++ [dcl.meaning]p1:
5848 // [...] the member shall not merely have been introduced by a
5849 // using-declaration in the scope of the class or namespace nominated by
5850 // the nested-name-specifier of the declarator-id.
5851 RemoveUsingDecls(Previous);
5852 }
5853
5854 if (Previous.isSingleResult() &&
5855 Previous.getFoundDecl()->isTemplateParameter()) {
5856 // Maybe we will complain about the shadowed template parameter.
5857 if (!D.isInvalidType())
5858 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5859 Previous.getFoundDecl());
5860
5861 // Just pretend that we didn't see the previous declaration.
5862 Previous.clear();
5863 }
5864
5865 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5866 // Forget that the previous declaration is the injected-class-name.
5867 Previous.clear();
5868
5869 // In C++, the previous declaration we find might be a tag type
5870 // (class or enum). In this case, the new declaration will hide the
5871 // tag type. Note that this applies to functions, function templates, and
5872 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5873 if (Previous.isSingleTagDecl() &&
5874 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5875 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5876 Previous.clear();
5877
5878 // Check that there are no default arguments other than in the parameters
5879 // of a function declaration (C++ only).
5880 if (getLangOpts().CPlusPlus)
5881 CheckExtraCXXDefaultArguments(D);
5882
5883 NamedDecl *New;
5884
5885 bool AddToScope = true;
5886 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5887 if (TemplateParamLists.size()) {
5888 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5889 return nullptr;
5890 }
5891
5892 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5893 } else if (R->isFunctionType()) {
5894 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5895 TemplateParamLists,
5896 AddToScope);
5897 } else {
5898 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5899 AddToScope);
5900 }
5901
5902 if (!New)
5903 return nullptr;
5904
5905 // If this has an identifier and is not a function template specialization,
5906 // add it to the scope stack.
5907 if (New->getDeclName() && AddToScope)
5908 PushOnScopeChains(New, S);
5909
5910 if (isInOpenMPDeclareTargetContext())
5911 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5912
5913 return New;
5914}
5915
5916/// Helper method to turn variable array types into constant array
5917/// types in certain situations which would otherwise be errors (for
5918/// GCC compatibility).
5919static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5920 ASTContext &Context,
5921 bool &SizeIsNegative,
5922 llvm::APSInt &Oversized) {
5923 // This method tries to turn a variable array into a constant
5924 // array even when the size isn't an ICE. This is necessary
5925 // for compatibility with code that depends on gcc's buggy
5926 // constant expression folding, like struct {char x[(int)(char*)2];}
5927 SizeIsNegative = false;
5928 Oversized = 0;
5929
5930 if (T->isDependentType())
5931 return QualType();
5932
5933 QualifierCollector Qs;
5934 const Type *Ty = Qs.strip(T);
5935
5936 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5937 QualType Pointee = PTy->getPointeeType();
5938 QualType FixedType =
5939 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5940 Oversized);
5941 if (FixedType.isNull()) return FixedType;
5942 FixedType = Context.getPointerType(FixedType);
5943 return Qs.apply(Context, FixedType);
5944 }
5945 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5946 QualType Inner = PTy->getInnerType();
5947 QualType FixedType =
5948 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5949 Oversized);
5950 if (FixedType.isNull()) return FixedType;
5951 FixedType = Context.getParenType(FixedType);
5952 return Qs.apply(Context, FixedType);
5953 }
5954
5955 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5956 if (!VLATy)
5957 return QualType();
5958 // FIXME: We should probably handle this case
5959 if (VLATy->getElementType()->isVariablyModifiedType())
5960 return QualType();
5961
5962 Expr::EvalResult Result;
5963 if (!VLATy->getSizeExpr() ||
5964 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5965 return QualType();
5966
5967 llvm::APSInt Res = Result.Val.getInt();
5968
5969 // Check whether the array size is negative.
5970 if (Res.isSigned() && Res.isNegative()) {
5971 SizeIsNegative = true;
5972 return QualType();
5973 }
5974
5975 // Check whether the array is too large to be addressed.
5976 unsigned ActiveSizeBits
5977 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5978 Res);
5979 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5980 Oversized = Res;
5981 return QualType();
5982 }
5983
5984 return Context.getConstantArrayType(
5985 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5986}
5987
5988static void
5989FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5990 SrcTL = SrcTL.getUnqualifiedLoc();
5991 DstTL = DstTL.getUnqualifiedLoc();
5992 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5993 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5994 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5995 DstPTL.getPointeeLoc());
5996 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5997 return;
5998 }
5999 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6000 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6001 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6002 DstPTL.getInnerLoc());
6003 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6004 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6005 return;
6006 }
6007 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6008 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6009 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6010 TypeLoc DstElemTL = DstATL.getElementLoc();
6011 DstElemTL.initializeFullCopy(SrcElemTL);
6012 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6013 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6014 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6015}
6016
6017/// Helper method to turn variable array types into constant array
6018/// types in certain situations which would otherwise be errors (for
6019/// GCC compatibility).
6020static TypeSourceInfo*
6021TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6022 ASTContext &Context,
6023 bool &SizeIsNegative,
6024 llvm::APSInt &Oversized) {
6025 QualType FixedTy
6026 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6027 SizeIsNegative, Oversized);
6028 if (FixedTy.isNull())
6029 return nullptr;
6030 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6031 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6032 FixedTInfo->getTypeLoc());
6033 return FixedTInfo;
6034}
6035
6036/// Register the given locally-scoped extern "C" declaration so
6037/// that it can be found later for redeclarations. We include any extern "C"
6038/// declaration that is not visible in the translation unit here, not just
6039/// function-scope declarations.
6040void
6041Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6042 if (!getLangOpts().CPlusPlus &&
6043 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6044 // Don't need to track declarations in the TU in C.
6045 return;
6046
6047 // Note that we have a locally-scoped external with this name.
6048 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6049}
6050
6051NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6052 // FIXME: We can have multiple results via __attribute__((overloadable)).
6053 auto Result = Context.getExternCContextDecl()->lookup(Name);
6054 return Result.empty() ? nullptr : *Result.begin();
6055}
6056
6057/// Diagnose function specifiers on a declaration of an identifier that
6058/// does not identify a function.
6059void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6060 // FIXME: We should probably indicate the identifier in question to avoid
6061 // confusion for constructs like "virtual int a(), b;"
6062 if (DS.isVirtualSpecified())
6063 Diag(DS.getVirtualSpecLoc(),
6064 diag::err_virtual_non_function);
6065
6066 if (DS.hasExplicitSpecifier())
6067 Diag(DS.getExplicitSpecLoc(),
6068 diag::err_explicit_non_function);
6069
6070 if (DS.isNoreturnSpecified())
6071 Diag(DS.getNoreturnSpecLoc(),
6072 diag::err_noreturn_non_function);
6073}
6074
6075NamedDecl*
6076Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6077 TypeSourceInfo *TInfo, LookupResult &Previous) {
6078 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6079 if (D.getCXXScopeSpec().isSet()) {
6080 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6081 << D.getCXXScopeSpec().getRange();
6082 D.setInvalidType();
6083 // Pretend we didn't see the scope specifier.
6084 DC = CurContext;
6085 Previous.clear();
6086 }
6087
6088 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6089
6090 if (D.getDeclSpec().isInlineSpecified())
6091 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6092 << getLangOpts().CPlusPlus17;
6093 if (D.getDeclSpec().hasConstexprSpecifier())
6094 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6095 << 1 << D.getDeclSpec().getConstexprSpecifier();
6096
6097 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6098 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6099 Diag(D.getName().StartLocation,
6100 diag::err_deduction_guide_invalid_specifier)
6101 << "typedef";
6102 else
6103 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6104 << D.getName().getSourceRange();
6105 return nullptr;
6106 }
6107
6108 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6109 if (!NewTD) return nullptr;
6110
6111 // Handle attributes prior to checking for duplicates in MergeVarDecl
6112 ProcessDeclAttributes(S, NewTD, D);
6113
6114 CheckTypedefForVariablyModifiedType(S, NewTD);
6115
6116 bool Redeclaration = D.isRedeclaration();
6117 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6118 D.setRedeclaration(Redeclaration);
6119 return ND;
6120}
6121
6122void
6123Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6124 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6125 // then it shall have block scope.
6126 // Note that variably modified types must be fixed before merging the decl so
6127 // that redeclarations will match.
6128 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6129 QualType T = TInfo->getType();
6130 if (T->isVariablyModifiedType()) {
6131 setFunctionHasBranchProtectedScope();
6132
6133 if (S->getFnParent() == nullptr) {
6134 bool SizeIsNegative;
6135 llvm::APSInt Oversized;
6136 TypeSourceInfo *FixedTInfo =
6137 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6138 SizeIsNegative,
6139 Oversized);
6140 if (FixedTInfo) {
6141 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6142 NewTD->setTypeSourceInfo(FixedTInfo);
6143 } else {
6144 if (SizeIsNegative)
6145 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6146 else if (T->isVariableArrayType())
6147 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6148 else if (Oversized.getBoolValue())
6149 Diag(NewTD->getLocation(), diag::err_array_too_large)
6150 << Oversized.toString(10);
6151 else
6152 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6153 NewTD->setInvalidDecl();
6154 }
6155 }
6156 }
6157}
6158
6159/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6160/// declares a typedef-name, either using the 'typedef' type specifier or via
6161/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6162NamedDecl*
6163Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6164 LookupResult &Previous, bool &Redeclaration) {
6165
6166 // Find the shadowed declaration before filtering for scope.
6167 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6168
6169 // Merge the decl with the existing one if appropriate. If the decl is
6170 // in an outer scope, it isn't the same thing.
6171 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6172 /*AllowInlineNamespace*/false);
6173 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6174 if (!Previous.empty()) {
6175 Redeclaration = true;
6176 MergeTypedefNameDecl(S, NewTD, Previous);
6177 } else {
6178 inferGslPointerAttribute(NewTD);
6179 }
6180
6181 if (ShadowedDecl && !Redeclaration)
6182 CheckShadow(NewTD, ShadowedDecl, Previous);
6183
6184 // If this is the C FILE type, notify the AST context.
6185 if (IdentifierInfo *II = NewTD->getIdentifier())
6186 if (!NewTD->isInvalidDecl() &&
6187 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6188 if (II->isStr("FILE"))
6189 Context.setFILEDecl(NewTD);
6190 else if (II->isStr("jmp_buf"))
6191 Context.setjmp_bufDecl(NewTD);
6192 else if (II->isStr("sigjmp_buf"))
6193 Context.setsigjmp_bufDecl(NewTD);
6194 else if (II->isStr("ucontext_t"))
6195 Context.setucontext_tDecl(NewTD);
6196 }
6197
6198 return NewTD;
6199}
6200
6201/// Determines whether the given declaration is an out-of-scope
6202/// previous declaration.
6203///
6204/// This routine should be invoked when name lookup has found a
6205/// previous declaration (PrevDecl) that is not in the scope where a
6206/// new declaration by the same name is being introduced. If the new
6207/// declaration occurs in a local scope, previous declarations with
6208/// linkage may still be considered previous declarations (C99
6209/// 6.2.2p4-5, C++ [basic.link]p6).
6210///
6211/// \param PrevDecl the previous declaration found by name
6212/// lookup
6213///
6214/// \param DC the context in which the new declaration is being
6215/// declared.
6216///
6217/// \returns true if PrevDecl is an out-of-scope previous declaration
6218/// for a new delcaration with the same name.
6219static bool
6220isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6221 ASTContext &Context) {
6222 if (!PrevDecl)
6223 return false;
6224
6225 if (!PrevDecl->hasLinkage())
6226 return false;
6227
6228 if (Context.getLangOpts().CPlusPlus) {
6229 // C++ [basic.link]p6:
6230 // If there is a visible declaration of an entity with linkage
6231 // having the same name and type, ignoring entities declared
6232 // outside the innermost enclosing namespace scope, the block
6233 // scope declaration declares that same entity and receives the
6234 // linkage of the previous declaration.
6235 DeclContext *OuterContext = DC->getRedeclContext();
6236 if (!OuterContext->isFunctionOrMethod())
6237 // This rule only applies to block-scope declarations.
6238 return false;
6239
6240 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6241 if (PrevOuterContext->isRecord())
6242 // We found a member function: ignore it.
6243 return false;
6244
6245 // Find the innermost enclosing namespace for the new and
6246 // previous declarations.
6247 OuterContext = OuterContext->getEnclosingNamespaceContext();
6248 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6249
6250 // The previous declaration is in a different namespace, so it
6251 // isn't the same function.
6252 if (!OuterContext->Equals(PrevOuterContext))
6253 return false;
6254 }
6255
6256 return true;
6257}
6258
6259static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6260 CXXScopeSpec &SS = D.getCXXScopeSpec();
6261 if (!SS.isSet()) return;
6262 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6263}
6264
6265bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6266 QualType type = decl->getType();
6267 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6268 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6269 // Various kinds of declaration aren't allowed to be __autoreleasing.
6270 unsigned kind = -1U;
6271 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6272 if (var->hasAttr<BlocksAttr>())
6273 kind = 0; // __block
6274 else if (!var->hasLocalStorage())
6275 kind = 1; // global
6276 } else if (isa<ObjCIvarDecl>(decl)) {
6277 kind = 3; // ivar
6278 } else if (isa<FieldDecl>(decl)) {
6279 kind = 2; // field
6280 }
6281
6282 if (kind != -1U) {
6283 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6284 << kind;
6285 }
6286 } else if (lifetime == Qualifiers::OCL_None) {
6287 // Try to infer lifetime.
6288 if (!type->isObjCLifetimeType())
6289 return false;
6290
6291 lifetime = type->getObjCARCImplicitLifetime();
6292 type = Context.getLifetimeQualifiedType(type, lifetime);
6293 decl->setType(type);
6294 }
6295
6296 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6297 // Thread-local variables cannot have lifetime.
6298 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6299 var->getTLSKind()) {
6300 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6301 << var->getType();
6302 return true;
6303 }
6304 }
6305
6306 return false;
6307}
6308
6309void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6310 if (Decl->getType().hasAddressSpace())
6311 return;
6312 if (Decl->getType()->isDependentType())
6313 return;
6314 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6315 QualType Type = Var->getType();
6316 if (Type->isSamplerT() || Type->isVoidType())
6317 return;
6318 LangAS ImplAS = LangAS::opencl_private;
6319 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6320 Var->hasGlobalStorage())
6321 ImplAS = LangAS::opencl_global;
6322 // If the original type from a decayed type is an array type and that array
6323 // type has no address space yet, deduce it now.
6324 if (auto DT = dyn_cast<DecayedType>(Type)) {
6325 auto OrigTy = DT->getOriginalType();
6326 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6327 // Add the address space to the original array type and then propagate
6328 // that to the element type through `getAsArrayType`.
6329 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6330 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6331 // Re-generate the decayed type.
6332 Type = Context.getDecayedType(OrigTy);
6333 }
6334 }
6335 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6336 // Apply any qualifiers (including address space) from the array type to
6337 // the element type. This implements C99 6.7.3p8: "If the specification of
6338 // an array type includes any type qualifiers, the element type is so
6339 // qualified, not the array type."
6340 if (Type->isArrayType())
6341 Type = QualType(Context.getAsArrayType(Type), 0);
6342 Decl->setType(Type);
6343 }
6344}
6345
6346static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6347 // Ensure that an auto decl is deduced otherwise the checks below might cache
6348 // the wrong linkage.
6349 assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast
<void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 6349, __PRETTY_FUNCTION__))
;
6350
6351 // 'weak' only applies to declarations with external linkage.
6352 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6353 if (!ND.isExternallyVisible()) {
6354 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6355 ND.dropAttr<WeakAttr>();
6356 }
6357 }
6358 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6359 if (ND.isExternallyVisible()) {
6360 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6361 ND.dropAttr<WeakRefAttr>();
6362 ND.dropAttr<AliasAttr>();
6363 }
6364 }
6365
6366 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6367 if (VD->hasInit()) {
6368 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6369 assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 6370, __PRETTY_FUNCTION__))
6370 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 6370, __PRETTY_FUNCTION__))
;
6371 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6372 VD->dropAttr<AliasAttr>();
6373 }
6374 }
6375 }
6376
6377 // 'selectany' only applies to externally visible variable declarations.
6378 // It does not apply to functions.
6379 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6380 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6381 S.Diag(Attr->getLocation(),
6382 diag::err_attribute_selectany_non_extern_data);
6383 ND.dropAttr<SelectAnyAttr>();
6384 }
6385 }
6386
6387 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6388 auto *VD = dyn_cast<VarDecl>(&ND);
6389 bool IsAnonymousNS = false;
6390 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6391 if (VD) {
6392 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6393 while (NS && !IsAnonymousNS) {
6394 IsAnonymousNS = NS->isAnonymousNamespace();
6395 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6396 }
6397 }
6398 // dll attributes require external linkage. Static locals may have external
6399 // linkage but still cannot be explicitly imported or exported.
6400 // In Microsoft mode, a variable defined in anonymous namespace must have
6401 // external linkage in order to be exported.
6402 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6403 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6404 (!AnonNSInMicrosoftMode &&
6405 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6406 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6407 << &ND << Attr;
6408 ND.setInvalidDecl();
6409 }
6410 }
6411
6412 // Virtual functions cannot be marked as 'notail'.
6413 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6414 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6415 if (MD->isVirtual()) {
6416 S.Diag(ND.getLocation(),
6417 diag::err_invalid_attribute_on_virtual_function)
6418 << Attr;
6419 ND.dropAttr<NotTailCalledAttr>();
6420 }
6421
6422 // Check the attributes on the function type, if any.
6423 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6424 // Don't declare this variable in the second operand of the for-statement;
6425 // GCC miscompiles that by ending its lifetime before evaluating the
6426 // third operand. See gcc.gnu.org/PR86769.
6427 AttributedTypeLoc ATL;
6428 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6429 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6430 TL = ATL.getModifiedLoc()) {
6431 // The [[lifetimebound]] attribute can be applied to the implicit object
6432 // parameter of a non-static member function (other than a ctor or dtor)
6433 // by applying it to the function type.
6434 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6435 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6436 if (!MD || MD->isStatic()) {
6437 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6438 << !MD << A->getRange();
6439 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6440 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6441 << isa<CXXDestructorDecl>(MD) << A->getRange();
6442 }
6443 }
6444 }
6445 }
6446}
6447
6448static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6449 NamedDecl *NewDecl,
6450 bool IsSpecialization,
6451 bool IsDefinition) {
6452 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6453 return;
6454
6455 bool IsTemplate = false;
6456 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6457 OldDecl = OldTD->getTemplatedDecl();
6458 IsTemplate = true;
6459 if (!IsSpecialization)
6460 IsDefinition = false;
6461 }
6462 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6463 NewDecl = NewTD->getTemplatedDecl();
6464 IsTemplate = true;
6465 }
6466
6467 if (!OldDecl || !NewDecl)
6468 return;
6469
6470 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6471 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6472 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6473 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6474
6475 // dllimport and dllexport are inheritable attributes so we have to exclude
6476 // inherited attribute instances.
6477 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6478 (NewExportAttr && !NewExportAttr->isInherited());
6479
6480 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6481 // the only exception being explicit specializations.
6482 // Implicitly generated declarations are also excluded for now because there
6483 // is no other way to switch these to use dllimport or dllexport.
6484 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6485
6486 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6487 // Allow with a warning for free functions and global variables.
6488 bool JustWarn = false;
6489 if (!OldDecl->isCXXClassMember()) {
6490 auto *VD = dyn_cast<VarDecl>(OldDecl);
6491 if (VD && !VD->getDescribedVarTemplate())
6492 JustWarn = true;
6493 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6494 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6495 JustWarn = true;
6496 }
6497
6498 // We cannot change a declaration that's been used because IR has already
6499 // been emitted. Dllimported functions will still work though (modulo
6500 // address equality) as they can use the thunk.
6501 if (OldDecl->isUsed())
6502 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6503 JustWarn = false;
6504
6505 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6506 : diag::err_attribute_dll_redeclaration;
6507 S.Diag(NewDecl->getLocation(), DiagID)
6508 << NewDecl
6509 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6510 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6511 if (!JustWarn) {
6512 NewDecl->setInvalidDecl();
6513 return;
6514 }
6515 }
6516
6517 // A redeclaration is not allowed to drop a dllimport attribute, the only
6518 // exceptions being inline function definitions (except for function
6519 // templates), local extern declarations, qualified friend declarations or
6520 // special MSVC extension: in the last case, the declaration is treated as if
6521 // it were marked dllexport.
6522 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6523 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6524 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6525 // Ignore static data because out-of-line definitions are diagnosed
6526 // separately.
6527 IsStaticDataMember = VD->isStaticDataMember();
6528 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6529 VarDecl::DeclarationOnly;
6530 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6531 IsInline = FD->isInlined();
6532 IsQualifiedFriend = FD->getQualifier() &&
6533 FD->getFriendObjectKind() == Decl::FOK_Declared;
6534 }
6535
6536 if (OldImportAttr && !HasNewAttr &&
6537 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6538 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6539 if (IsMicrosoft && IsDefinition) {
6540 S.Diag(NewDecl->getLocation(),
6541 diag::warn_redeclaration_without_import_attribute)
6542 << NewDecl;
6543 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6544 NewDecl->dropAttr<DLLImportAttr>();
6545 NewDecl->addAttr(
6546 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6547 } else {
6548 S.Diag(NewDecl->getLocation(),
6549 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6550 << NewDecl << OldImportAttr;
6551 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6552 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6553 OldDecl->dropAttr<DLLImportAttr>();
6554 NewDecl->dropAttr<DLLImportAttr>();
6555 }
6556 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6557 // In MinGW, seeing a function declared inline drops the dllimport
6558 // attribute.
6559 OldDecl->dropAttr<DLLImportAttr>();
6560 NewDecl->dropAttr<DLLImportAttr>();
6561 S.Diag(NewDecl->getLocation(),
6562 diag::warn_dllimport_dropped_from_inline_function)
6563 << NewDecl << OldImportAttr;
6564 }
6565
6566 // A specialization of a class template member function is processed here
6567 // since it's a redeclaration. If the parent class is dllexport, the
6568 // specialization inherits that attribute. This doesn't happen automatically
6569 // since the parent class isn't instantiated until later.
6570 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6571 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6572 !NewImportAttr && !NewExportAttr) {
6573 if (const DLLExportAttr *ParentExportAttr =
6574 MD->getParent()->getAttr<DLLExportAttr>()) {
6575 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6576 NewAttr->setInherited(true);
6577 NewDecl->addAttr(NewAttr);
6578 }
6579 }
6580 }
6581}
6582
6583/// Given that we are within the definition of the given function,
6584/// will that definition behave like C99's 'inline', where the
6585/// definition is discarded except for optimization purposes?
6586static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6587 // Try to avoid calling GetGVALinkageForFunction.
6588
6589 // All cases of this require the 'inline' keyword.
6590 if (!FD->isInlined()) return false;
6591
6592 // This is only possible in C++ with the gnu_inline attribute.
6593 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6594 return false;
6595
6596 // Okay, go ahead and call the relatively-more-expensive function.
6597 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6598}
6599
6600/// Determine whether a variable is extern "C" prior to attaching
6601/// an initializer. We can't just call isExternC() here, because that
6602/// will also compute and cache whether the declaration is externally
6603/// visible, which might change when we attach the initializer.
6604///
6605/// This can only be used if the declaration is known to not be a
6606/// redeclaration of an internal linkage declaration.
6607///
6608/// For instance:
6609///
6610/// auto x = []{};
6611///
6612/// Attaching the initializer here makes this declaration not externally
6613/// visible, because its type has internal linkage.
6614///
6615/// FIXME: This is a hack.
6616template<typename T>
6617static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6618 if (S.getLangOpts().CPlusPlus) {
6619 // In C++, the overloadable attribute negates the effects of extern "C".
6620 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6621 return false;
6622
6623 // So do CUDA's host/device attributes.
6624 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6625 D->template hasAttr<CUDAHostAttr>()))
6626 return false;
6627 }
6628 return D->isExternC();
6629}
6630
6631static bool shouldConsiderLinkage(const VarDecl *VD) {
6632 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6633 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6634 isa<OMPDeclareMapperDecl>(DC))
6635 return VD->hasExternalStorage();
6636 if (DC->isFileContext())
6637 return true;
6638 if (DC->isRecord())
6639 return false;
6640 if (isa<RequiresExprBodyDecl>(DC))
6641 return false;
6642 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 6642)
;
6643}
6644
6645static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6646 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6647 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6648 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6649 return true;
6650 if (DC->isRecord())
6651 return false;
6652 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 6652)
;
6653}
6654
6655static bool hasParsedAttr(Scope *S, const Declarator &PD,
6656 ParsedAttr::Kind Kind) {
6657 // Check decl attributes on the DeclSpec.
6658 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6659 return true;
6660
6661 // Walk the declarator structure, checking decl attributes that were in a type
6662 // position to the decl itself.
6663 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6664 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6665 return true;
6666 }
6667
6668 // Finally, check attributes on the decl itself.
6669 return PD.getAttributes().hasAttribute(Kind);
6670}
6671
6672/// Adjust the \c DeclContext for a function or variable that might be a
6673/// function-local external declaration.
6674bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6675 if (!DC->isFunctionOrMethod())
6676 return false;
6677
6678 // If this is a local extern function or variable declared within a function
6679 // template, don't add it into the enclosing namespace scope until it is
6680 // instantiated; it might have a dependent type right now.
6681 if (DC->isDependentContext())
6682 return true;
6683
6684 // C++11 [basic.link]p7:
6685 // When a block scope declaration of an entity with linkage is not found to
6686 // refer to some other declaration, then that entity is a member of the
6687 // innermost enclosing namespace.
6688 //
6689 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6690 // semantically-enclosing namespace, not a lexically-enclosing one.
6691 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6692 DC = DC->getParent();
6693 return true;
6694}
6695
6696/// Returns true if given declaration has external C language linkage.
6697static bool isDeclExternC(const Decl *D) {
6698 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6699 return FD->isExternC();
6700 if (const auto *VD = dyn_cast<VarDecl>(D))
6701 return VD->isExternC();
6702
6703 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 6703)
;
6704}
6705/// Returns true if there hasn't been any invalid type diagnosed.
6706static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6707 DeclContext *DC, QualType R) {
6708 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6709 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6710 // argument.
6711 if (R->isImageType() || R->isPipeType()) {
6712 Se.Diag(D.getIdentifierLoc(),
6713 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6714 << R;
6715 D.setInvalidType();
6716 return false;
6717 }
6718
6719 // OpenCL v1.2 s6.9.r:
6720 // The event type cannot be used to declare a program scope variable.
6721 // OpenCL v2.0 s6.9.q:
6722 // The clk_event_t and reserve_id_t types cannot be declared in program
6723 // scope.
6724 if (NULL__null == S->getParent()) {
6725 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6726 Se.Diag(D.getIdentifierLoc(),
6727 diag::err_invalid_type_for_program_scope_var)
6728 << R;
6729 D.setInvalidType();
6730 return false;
6731 }
6732 }
6733
6734 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6735 QualType NR = R;
6736 while (NR->isPointerType()) {
6737 if (NR->isFunctionPointerType()) {
6738 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6739 D.setInvalidType();
6740 return false;
6741 }
6742 NR = NR->getPointeeType();
6743 }
6744
6745 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6746 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6747 // half array type (unless the cl_khr_fp16 extension is enabled).
6748 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6749 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6750 D.setInvalidType();
6751 return false;
6752 }
6753 }
6754
6755 // OpenCL v1.2 s6.9.r:
6756 // The event type cannot be used with the __local, __constant and __global
6757 // address space qualifiers.
6758 if (R->isEventT()) {
6759 if (R.getAddressSpace() != LangAS::opencl_private) {
6760 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6761 D.setInvalidType();
6762 return false;
6763 }
6764 }
6765
6766 // C++ for OpenCL does not allow the thread_local storage qualifier.
6767 // OpenCL C does not support thread_local either, and
6768 // also reject all other thread storage class specifiers.
6769 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6770 if (TSC != TSCS_unspecified) {
6771 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6772 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6773 diag::err_opencl_unknown_type_specifier)
6774 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6775 << DeclSpec::getSpecifierName(TSC) << 1;
6776 D.setInvalidType();
6777 return false;
6778 }
6779
6780 if (R->isSamplerT()) {
6781 // OpenCL v1.2 s6.9.b p4:
6782 // The sampler type cannot be used with the __local and __global address
6783 // space qualifiers.
6784 if (R.getAddressSpace() == LangAS::opencl_local ||
6785 R.getAddressSpace() == LangAS::opencl_global) {
6786 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6787 D.setInvalidType();
6788 }
6789
6790 // OpenCL v1.2 s6.12.14.1:
6791 // A global sampler must be declared with either the constant address
6792 // space qualifier or with the const qualifier.
6793 if (DC->isTranslationUnit() &&
6794 !(R.getAddressSpace() == LangAS::opencl_constant ||
6795 R.isConstQualified())) {
6796 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6797 D.setInvalidType();
6798 }
6799 if (D.isInvalidType())
6800 return false;
6801 }
6802 return true;
6803}
6804
6805NamedDecl *Sema::ActOnVariableDeclarator(
6806 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6807 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6808 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6809 QualType R = TInfo->getType();
6810 DeclarationName Name = GetNameForDeclarator(D).getName();
6811
6812 IdentifierInfo *II = Name.getAsIdentifierInfo();
6813
6814 if (D.isDecompositionDeclarator()) {
6815 // Take the name of the first declarator as our name for diagnostic
6816 // purposes.
6817 auto &Decomp = D.getDecompositionDeclarator();
6818 if (!Decomp.bindings().empty()) {
6819 II = Decomp.bindings()[0].Name;
6820 Name = II;
6821 }
6822 } else if (!II) {
6823 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6824 return nullptr;
6825 }
6826
6827
6828 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6829 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6830
6831 // dllimport globals without explicit storage class are treated as extern. We
6832 // have to change the storage class this early to get the right DeclContext.
6833 if (SC == SC_None && !DC->isRecord() &&
6834 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6835 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6836 SC = SC_Extern;
6837
6838 DeclContext *OriginalDC = DC;
6839 bool IsLocalExternDecl = SC == SC_Extern &&
6840 adjustContextForLocalExternDecl(DC);
6841
6842 if (SCSpec == DeclSpec::SCS_mutable) {
6843 // mutable can only appear on non-static class members, so it's always
6844 // an error here
6845 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6846 D.setInvalidType();
6847 SC = SC_None;
6848 }
6849
6850 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6851 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6852 D.getDeclSpec().getStorageClassSpecLoc())) {
6853 // In C++11, the 'register' storage class specifier is deprecated.
6854 // Suppress the warning in system macros, it's used in macros in some
6855 // popular C system headers, such as in glibc's htonl() macro.
6856 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6857 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6858 : diag::warn_deprecated_register)
6859 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6860 }
6861
6862 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6863
6864 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6865 // C99 6.9p2: The storage-class specifiers auto and register shall not
6866 // appear in the declaration specifiers in an external declaration.
6867 // Global Register+Asm is a GNU extension we support.
6868 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6869 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6870 D.setInvalidType();
6871 }
6872 }
6873
6874 bool IsMemberSpecialization = false;
6875 bool IsVariableTemplateSpecialization = false;
6876 bool IsPartialSpecialization = false;
6877 bool IsVariableTemplate = false;
6878 VarDecl *NewVD = nullptr;
6879 VarTemplateDecl *NewTemplate = nullptr;
6880 TemplateParameterList *TemplateParams = nullptr;
6881 if (!getLangOpts().CPlusPlus) {
6882 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6883 II, R, TInfo, SC);
6884
6885 if (R->getContainedDeducedType())
6886 ParsingInitForAutoVars.insert(NewVD);
6887
6888 if (D.isInvalidType())
6889 NewVD->setInvalidDecl();
6890
6891 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6892 NewVD->hasLocalStorage())
6893 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6894 NTCUC_AutoVar, NTCUK_Destruct);
6895 } else {
6896 bool Invalid = false;
6897
6898 if (DC->isRecord() && !CurContext->isRecord()) {
6899 // This is an out-of-line definition of a static data member.
6900 switch (SC) {
6901 case SC_None:
6902 break;
6903 case SC_Static:
6904 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6905 diag::err_static_out_of_line)
6906 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6907 break;
6908 case SC_Auto:
6909 case SC_Register:
6910 case SC_Extern:
6911 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6912 // to names of variables declared in a block or to function parameters.
6913 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6914 // of class members
6915
6916 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6917 diag::err_storage_class_for_static_member)
6918 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6919 break;
6920 case SC_PrivateExtern:
6921 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 6921)
;
6922 }
6923 }
6924
6925 if (SC == SC_Static && CurContext->isRecord()) {
6926 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6927 // Walk up the enclosing DeclContexts to check for any that are
6928 // incompatible with static data members.
6929 const DeclContext *FunctionOrMethod = nullptr;
6930 const CXXRecordDecl *AnonStruct = nullptr;
6931 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6932 if (Ctxt->isFunctionOrMethod()) {
6933 FunctionOrMethod = Ctxt;
6934 break;
6935 }
6936 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6937 if (ParentDecl && !ParentDecl->getDeclName()) {
6938 AnonStruct = ParentDecl;
6939 break;
6940 }
6941 }
6942 if (FunctionOrMethod) {
6943 // C++ [class.static.data]p5: A local class shall not have static data
6944 // members.
6945 Diag(D.getIdentifierLoc(),
6946 diag::err_static_data_member_not_allowed_in_local_class)
6947 << Name << RD->getDeclName() << RD->getTagKind();
6948 } else if (AnonStruct) {
6949 // C++ [class.static.data]p4: Unnamed classes and classes contained
6950 // directly or indirectly within unnamed classes shall not contain
6951 // static data members.
6952 Diag(D.getIdentifierLoc(),
6953 diag::err_static_data_member_not_allowed_in_anon_struct)
6954 << Name << AnonStruct->getTagKind();
6955 Invalid = true;
6956 } else if (RD->isUnion()) {
6957 // C++98 [class.union]p1: If a union contains a static data member,
6958 // the program is ill-formed. C++11 drops this restriction.
6959 Diag(D.getIdentifierLoc(),
6960 getLangOpts().CPlusPlus11
6961 ? diag::warn_cxx98_compat_static_data_member_in_union
6962 : diag::ext_static_data_member_in_union) << Name;
6963 }
6964 }
6965 }
6966
6967 // Match up the template parameter lists with the scope specifier, then
6968 // determine whether we have a template or a template specialization.
6969 bool InvalidScope = false;
6970 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6971 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6972 D.getCXXScopeSpec(),
6973 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6974 ? D.getName().TemplateId
6975 : nullptr,
6976 TemplateParamLists,
6977 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6978 Invalid |= InvalidScope;
6979
6980 if (TemplateParams) {
6981 if (!TemplateParams->size() &&
6982 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6983 // There is an extraneous 'template<>' for this variable. Complain
6984 // about it, but allow the declaration of the variable.
6985 Diag(TemplateParams->getTemplateLoc(),
6986 diag::err_template_variable_noparams)
6987 << II
6988 << SourceRange(TemplateParams->getTemplateLoc(),
6989 TemplateParams->getRAngleLoc());
6990 TemplateParams = nullptr;
6991 } else {
6992 // Check that we can declare a template here.
6993 if (CheckTemplateDeclScope(S, TemplateParams))
6994 return nullptr;
6995
6996 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6997 // This is an explicit specialization or a partial specialization.
6998 IsVariableTemplateSpecialization = true;
6999 IsPartialSpecialization = TemplateParams->size() > 0;
7000 } else { // if (TemplateParams->size() > 0)
7001 // This is a template declaration.
7002 IsVariableTemplate = true;
7003
7004 // Only C++1y supports variable templates (N3651).
7005 Diag(D.getIdentifierLoc(),
7006 getLangOpts().CPlusPlus14
7007 ? diag::warn_cxx11_compat_variable_template
7008 : diag::ext_variable_template);
7009 }
7010 }
7011 } else {
7012 // Check that we can declare a member specialization here.
7013 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7014 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7015 return nullptr;
7016 assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7018, __PRETTY_FUNCTION__))
7017 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7018, __PRETTY_FUNCTION__))
7018 "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7018, __PRETTY_FUNCTION__))
;
7019 }
7020
7021 if (IsVariableTemplateSpecialization) {
7022 SourceLocation TemplateKWLoc =
7023 TemplateParamLists.size() > 0
7024 ? TemplateParamLists[0]->getTemplateLoc()
7025 : SourceLocation();
7026 DeclResult Res = ActOnVarTemplateSpecialization(
7027 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7028 IsPartialSpecialization);
7029 if (Res.isInvalid())
7030 return nullptr;
7031 NewVD = cast<VarDecl>(Res.get());
7032 AddToScope = false;
7033 } else if (D.isDecompositionDeclarator()) {
7034 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7035 D.getIdentifierLoc(), R, TInfo, SC,
7036 Bindings);
7037 } else
7038 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7039 D.getIdentifierLoc(), II, R, TInfo, SC);
7040
7041 // If this is supposed to be a variable template, create it as such.
7042 if (IsVariableTemplate) {
7043 NewTemplate =
7044 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7045 TemplateParams, NewVD);
7046 NewVD->setDescribedVarTemplate(NewTemplate);
7047 }
7048
7049 // If this decl has an auto type in need of deduction, make a note of the
7050 // Decl so we can diagnose uses of it in its own initializer.
7051 if (R->getContainedDeducedType())
7052 ParsingInitForAutoVars.insert(NewVD);
7053
7054 if (D.isInvalidType() || Invalid) {
7055 NewVD->setInvalidDecl();
7056 if (NewTemplate)
7057 NewTemplate->setInvalidDecl();
7058 }
7059
7060 SetNestedNameSpecifier(*this, NewVD, D);
7061
7062 // If we have any template parameter lists that don't directly belong to
7063 // the variable (matching the scope specifier), store them.
7064 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7065 if (TemplateParamLists.size() > VDTemplateParamLists)
7066 NewVD->setTemplateParameterListsInfo(
7067 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7068 }
7069
7070 if (D.getDeclSpec().isInlineSpecified()) {
7071 if (!getLangOpts().CPlusPlus) {
7072 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7073 << 0;
7074 } else if (CurContext->isFunctionOrMethod()) {
7075 // 'inline' is not allowed on block scope variable declaration.
7076 Diag(D.getDeclSpec().getInlineSpecLoc(),
7077 diag::err_inline_declaration_block_scope) << Name
7078 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7079 } else {
7080 Diag(D.getDeclSpec().getInlineSpecLoc(),
7081 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7082 : diag::ext_inline_variable);
7083 NewVD->setInlineSpecified();
7084 }
7085 }
7086
7087 // Set the lexical context. If the declarator has a C++ scope specifier, the
7088 // lexical context will be different from the semantic context.
7089 NewVD->setLexicalDeclContext(CurContext);
7090 if (NewTemplate)
7091 NewTemplate->setLexicalDeclContext(CurContext);
7092
7093 if (IsLocalExternDecl) {
7094 if (D.isDecompositionDeclarator())
7095 for (auto *B : Bindings)
7096 B->setLocalExternDecl();
7097 else
7098 NewVD->setLocalExternDecl();
7099 }
7100
7101 bool EmitTLSUnsupportedError = false;
7102 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7103 // C++11 [dcl.stc]p4:
7104 // When thread_local is applied to a variable of block scope the
7105 // storage-class-specifier static is implied if it does not appear
7106 // explicitly.
7107 // Core issue: 'static' is not implied if the variable is declared
7108 // 'extern'.
7109 if (NewVD->hasLocalStorage() &&
7110 (SCSpec != DeclSpec::SCS_unspecified ||
7111 TSCS != DeclSpec::TSCS_thread_local ||
7112 !DC->isFunctionOrMethod()))
7113 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7114 diag::err_thread_non_global)
7115 << DeclSpec::getSpecifierName(TSCS);
7116 else if (!Context.getTargetInfo().isTLSSupported()) {
7117 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7118 getLangOpts().SYCLIsDevice) {
7119 // Postpone error emission until we've collected attributes required to
7120 // figure out whether it's a host or device variable and whether the
7121 // error should be ignored.
7122 EmitTLSUnsupportedError = true;
7123 // We still need to mark the variable as TLS so it shows up in AST with
7124 // proper storage class for other tools to use even if we're not going
7125 // to emit any code for it.
7126 NewVD->setTSCSpec(TSCS);
7127 } else
7128 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7129 diag::err_thread_unsupported);
7130 } else
7131 NewVD->setTSCSpec(TSCS);
7132 }
7133
7134 switch (D.getDeclSpec().getConstexprSpecifier()) {
7135 case CSK_unspecified:
7136 break;
7137
7138 case CSK_consteval:
7139 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7140 diag::err_constexpr_wrong_decl_kind)
7141 << D.getDeclSpec().getConstexprSpecifier();
7142 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7143
7144 case CSK_constexpr:
7145 NewVD->setConstexpr(true);
7146 MaybeAddCUDAConstantAttr(NewVD);
7147 // C++1z [dcl.spec.constexpr]p1:
7148 // A static data member declared with the constexpr specifier is
7149 // implicitly an inline variable.
7150 if (NewVD->isStaticDataMember() &&
7151 (getLangOpts().CPlusPlus17 ||
7152 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7153 NewVD->setImplicitlyInline();
7154 break;
7155
7156 case CSK_constinit:
7157 if (!NewVD->hasGlobalStorage())
7158 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7159 diag::err_constinit_local_variable);
7160 else
7161 NewVD->addAttr(ConstInitAttr::Create(
7162 Context, D.getDeclSpec().getConstexprSpecLoc(),
7163 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7164 break;
7165 }
7166
7167 // C99 6.7.4p3
7168 // An inline definition of a function with external linkage shall
7169 // not contain a definition of a modifiable object with static or
7170 // thread storage duration...
7171 // We only apply this when the function is required to be defined
7172 // elsewhere, i.e. when the function is not 'extern inline'. Note
7173 // that a local variable with thread storage duration still has to
7174 // be marked 'static'. Also note that it's possible to get these
7175 // semantics in C++ using __attribute__((gnu_inline)).
7176 if (SC == SC_Static && S->getFnParent() != nullptr &&
7177 !NewVD->getType().isConstQualified()) {
7178 FunctionDecl *CurFD = getCurFunctionDecl();
7179 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7180 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7181 diag::warn_static_local_in_extern_inline);
7182 MaybeSuggestAddingStaticToDecl(CurFD);
7183 }
7184 }
7185
7186 if (D.getDeclSpec().isModulePrivateSpecified()) {
7187 if (IsVariableTemplateSpecialization)
7188 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7189 << (IsPartialSpecialization ? 1 : 0)
7190 << FixItHint::CreateRemoval(
7191 D.getDeclSpec().getModulePrivateSpecLoc());
7192 else if (IsMemberSpecialization)
7193 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7194 << 2
7195 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7196 else if (NewVD->hasLocalStorage())
7197 Diag(NewVD->getLocation(), diag::err_module_private_local)
7198 << 0 << NewVD
7199 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7200 << FixItHint::CreateRemoval(
7201 D.getDeclSpec().getModulePrivateSpecLoc());
7202 else {
7203 NewVD->setModulePrivate();
7204 if (NewTemplate)
7205 NewTemplate->setModulePrivate();
7206 for (auto *B : Bindings)
7207 B->setModulePrivate();
7208 }
7209 }
7210
7211 if (getLangOpts().OpenCL) {
7212
7213 deduceOpenCLAddressSpace(NewVD);
7214
7215 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7216 }
7217
7218 // Handle attributes prior to checking for duplicates in MergeVarDecl
7219 ProcessDeclAttributes(S, NewVD, D);
7220
7221 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7222 getLangOpts().SYCLIsDevice) {
7223 if (EmitTLSUnsupportedError &&
7224 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7225 (getLangOpts().OpenMPIsDevice &&
7226 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7227 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7228 diag::err_thread_unsupported);
7229
7230 if (EmitTLSUnsupportedError &&
7231 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7232 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7233 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7234 // storage [duration]."
7235 if (SC == SC_None && S->getFnParent() != nullptr &&
7236 (NewVD->hasAttr<CUDASharedAttr>() ||
7237 NewVD->hasAttr<CUDAConstantAttr>())) {
7238 NewVD->setStorageClass(SC_Static);
7239 }
7240 }
7241
7242 // Ensure that dllimport globals without explicit storage class are treated as
7243 // extern. The storage class is set above using parsed attributes. Now we can
7244 // check the VarDecl itself.
7245 assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7247, __PRETTY_FUNCTION__))
7246 NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7247, __PRETTY_FUNCTION__))
7247 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7247, __PRETTY_FUNCTION__))
;
7248
7249 // In auto-retain/release, infer strong retension for variables of
7250 // retainable type.
7251 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7252 NewVD->setInvalidDecl();
7253
7254 // Handle GNU asm-label extension (encoded as an attribute).
7255 if (Expr *E = (Expr*)D.getAsmLabel()) {
7256 // The parser guarantees this is a string.
7257 StringLiteral *SE = cast<StringLiteral>(E);
7258 StringRef Label = SE->getString();
7259 if (S->getFnParent() != nullptr) {
7260 switch (SC) {
7261 case SC_None:
7262 case SC_Auto:
7263 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7264 break;
7265 case SC_Register:
7266 // Local Named register
7267 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7268 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7269 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7270 break;
7271 case SC_Static:
7272 case SC_Extern:
7273 case SC_PrivateExtern:
7274 break;
7275 }
7276 } else if (SC == SC_Register) {
7277 // Global Named register
7278 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7279 const auto &TI = Context.getTargetInfo();
7280 bool HasSizeMismatch;
7281
7282 if (!TI.isValidGCCRegisterName(Label))
7283 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7284 else if (!TI.validateGlobalRegisterVariable(Label,
7285 Context.getTypeSize(R),
7286 HasSizeMismatch))
7287 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7288 else if (HasSizeMismatch)
7289 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7290 }
7291
7292 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7293 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7294 NewVD->setInvalidDecl(true);
7295 }
7296 }
7297
7298 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7299 /*IsLiteralLabel=*/true,
7300 SE->getStrTokenLoc(0)));
7301 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7302 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7303 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7304 if (I != ExtnameUndeclaredIdentifiers.end()) {
7305 if (isDeclExternC(NewVD)) {
7306 NewVD->addAttr(I->second);
7307 ExtnameUndeclaredIdentifiers.erase(I);
7308 } else
7309 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7310 << /*Variable*/1 << NewVD;
7311 }
7312 }
7313
7314 // Find the shadowed declaration before filtering for scope.
7315 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7316 ? getShadowedDeclaration(NewVD, Previous)
7317 : nullptr;
7318
7319 // Don't consider existing declarations that are in a different
7320 // scope and are out-of-semantic-context declarations (if the new
7321 // declaration has linkage).
7322 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7323 D.getCXXScopeSpec().isNotEmpty() ||
7324 IsMemberSpecialization ||
7325 IsVariableTemplateSpecialization);
7326
7327 // Check whether the previous declaration is in the same block scope. This
7328 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7329 if (getLangOpts().CPlusPlus &&
7330 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7331 NewVD->setPreviousDeclInSameBlockScope(
7332 Previous.isSingleResult() && !Previous.isShadowed() &&
7333 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7334
7335 if (!getLangOpts().CPlusPlus) {
7336 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7337 } else {
7338 // If this is an explicit specialization of a static data member, check it.
7339 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7340 CheckMemberSpecialization(NewVD, Previous))
7341 NewVD->setInvalidDecl();
7342
7343 // Merge the decl with the existing one if appropriate.
7344 if (!Previous.empty()) {
7345 if (Previous.isSingleResult() &&
7346 isa<FieldDecl>(Previous.getFoundDecl()) &&
7347 D.getCXXScopeSpec().isSet()) {
7348 // The user tried to define a non-static data member
7349 // out-of-line (C++ [dcl.meaning]p1).
7350 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7351 << D.getCXXScopeSpec().getRange();
7352 Previous.clear();
7353 NewVD->setInvalidDecl();
7354 }
7355 } else if (D.getCXXScopeSpec().isSet()) {
7356 // No previous declaration in the qualifying scope.
7357 Diag(D.getIdentifierLoc(), diag::err_no_member)
7358 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7359 << D.getCXXScopeSpec().getRange();
7360 NewVD->setInvalidDecl();
7361 }
7362
7363 if (!IsVariableTemplateSpecialization)
7364 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7365
7366 if (NewTemplate) {
7367 VarTemplateDecl *PrevVarTemplate =
7368 NewVD->getPreviousDecl()
7369 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7370 : nullptr;
7371
7372 // Check the template parameter list of this declaration, possibly
7373 // merging in the template parameter list from the previous variable
7374 // template declaration.
7375 if (CheckTemplateParameterList(
7376 TemplateParams,
7377 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7378 : nullptr,
7379 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7380 DC->isDependentContext())
7381 ? TPC_ClassTemplateMember
7382 : TPC_VarTemplate))
7383 NewVD->setInvalidDecl();
7384
7385 // If we are providing an explicit specialization of a static variable
7386 // template, make a note of that.
7387 if (PrevVarTemplate &&
7388 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7389 PrevVarTemplate->setMemberSpecialization();
7390 }
7391 }
7392
7393 // Diagnose shadowed variables iff this isn't a redeclaration.
7394 if (ShadowedDecl && !D.isRedeclaration())
7395 CheckShadow(NewVD, ShadowedDecl, Previous);
7396
7397 ProcessPragmaWeak(S, NewVD);
7398
7399 // If this is the first declaration of an extern C variable, update
7400 // the map of such variables.
7401 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7402 isIncompleteDeclExternC(*this, NewVD))
7403 RegisterLocallyScopedExternCDecl(NewVD, S);
7404
7405 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7406 MangleNumberingContext *MCtx;
7407 Decl *ManglingContextDecl;
7408 std::tie(MCtx, ManglingContextDecl) =
7409 getCurrentMangleNumberContext(NewVD->getDeclContext());
7410 if (MCtx) {
7411 Context.setManglingNumber(
7412 NewVD, MCtx->getManglingNumber(
7413 NewVD, getMSManglingNumber(getLangOpts(), S)));
7414 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7415 }
7416 }
7417
7418 // Special handling of variable named 'main'.
7419 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7420 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7421 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7422
7423 // C++ [basic.start.main]p3
7424 // A program that declares a variable main at global scope is ill-formed.
7425 if (getLangOpts().CPlusPlus)
7426 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7427
7428 // In C, and external-linkage variable named main results in undefined
7429 // behavior.
7430 else if (NewVD->hasExternalFormalLinkage())
7431 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7432 }
7433
7434 if (D.isRedeclaration() && !Previous.empty()) {
7435 NamedDecl *Prev = Previous.getRepresentativeDecl();
7436 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7437 D.isFunctionDefinition());
7438 }
7439
7440 if (NewTemplate) {
7441 if (NewVD->isInvalidDecl())
7442 NewTemplate->setInvalidDecl();
7443 ActOnDocumentableDecl(NewTemplate);
7444 return NewTemplate;
7445 }
7446
7447 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7448 CompleteMemberSpecialization(NewVD, Previous);
7449
7450 return NewVD;
7451}
7452
7453/// Enum describing the %select options in diag::warn_decl_shadow.
7454enum ShadowedDeclKind {
7455 SDK_Local,
7456 SDK_Global,
7457 SDK_StaticMember,
7458 SDK_Field,
7459 SDK_Typedef,
7460 SDK_Using
7461};
7462
7463/// Determine what kind of declaration we're shadowing.
7464static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7465 const DeclContext *OldDC) {
7466 if (isa<TypeAliasDecl>(ShadowedDecl))
7467 return SDK_Using;
7468 else if (isa<TypedefDecl>(ShadowedDecl))
7469 return SDK_Typedef;
7470 else if (isa<RecordDecl>(OldDC))
7471 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7472
7473 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7474}
7475
7476/// Return the location of the capture if the given lambda captures the given
7477/// variable \p VD, or an invalid source location otherwise.
7478static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7479 const VarDecl *VD) {
7480 for (const Capture &Capture : LSI->Captures) {
7481 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7482 return Capture.getLocation();
7483 }
7484 return SourceLocation();
7485}
7486
7487static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7488 const LookupResult &R) {
7489 // Only diagnose if we're shadowing an unambiguous field or variable.
7490 if (R.getResultKind() != LookupResult::Found)
7491 return false;
7492
7493 // Return false if warning is ignored.
7494 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7495}
7496
7497/// Return the declaration shadowed by the given variable \p D, or null
7498/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7499NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7500 const LookupResult &R) {
7501 if (!shouldWarnIfShadowedDecl(Diags, R))
7502 return nullptr;
7503
7504 // Don't diagnose declarations at file scope.
7505 if (D->hasGlobalStorage())
7506 return nullptr;
7507
7508 NamedDecl *ShadowedDecl = R.getFoundDecl();
7509 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7510 ? ShadowedDecl
7511 : nullptr;
7512}
7513
7514/// Return the declaration shadowed by the given typedef \p D, or null
7515/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7516NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7517 const LookupResult &R) {
7518 // Don't warn if typedef declaration is part of a class
7519 if (D->getDeclContext()->isRecord())
7520 return nullptr;
7521
7522 if (!shouldWarnIfShadowedDecl(Diags, R))
7523 return nullptr;
7524
7525 NamedDecl *ShadowedDecl = R.getFoundDecl();
7526 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7527}
7528
7529/// Diagnose variable or built-in function shadowing. Implements
7530/// -Wshadow.
7531///
7532/// This method is called whenever a VarDecl is added to a "useful"
7533/// scope.
7534///
7535/// \param ShadowedDecl the declaration that is shadowed by the given variable
7536/// \param R the lookup of the name
7537///
7538void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7539 const LookupResult &R) {
7540 DeclContext *NewDC = D->getDeclContext();
7541
7542 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7543 // Fields are not shadowed by variables in C++ static methods.
7544 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7545 if (MD->isStatic())
7546 return;
7547
7548 // Fields shadowed by constructor parameters are a special case. Usually
7549 // the constructor initializes the field with the parameter.
7550 if (isa<CXXConstructorDecl>(NewDC))
7551 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7552 // Remember that this was shadowed so we can either warn about its
7553 // modification or its existence depending on warning settings.
7554 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7555 return;
7556 }
7557 }
7558
7559 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7560 if (shadowedVar->isExternC()) {
7561 // For shadowing external vars, make sure that we point to the global
7562 // declaration, not a locally scoped extern declaration.
7563 for (auto I : shadowedVar->redecls())
7564 if (I->isFileVarDecl()) {
7565 ShadowedDecl = I;
7566 break;
7567 }
7568 }
7569
7570 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7571
7572 unsigned WarningDiag = diag::warn_decl_shadow;
7573 SourceLocation CaptureLoc;
7574 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7575 isa<CXXMethodDecl>(NewDC)) {
7576 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7577 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7578 if (RD->getLambdaCaptureDefault() == LCD_None) {
7579 // Try to avoid warnings for lambdas with an explicit capture list.
7580 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7581 // Warn only when the lambda captures the shadowed decl explicitly.
7582 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7583 if (CaptureLoc.isInvalid())
7584 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7585 } else {
7586 // Remember that this was shadowed so we can avoid the warning if the
7587 // shadowed decl isn't captured and the warning settings allow it.
7588 cast<LambdaScopeInfo>(getCurFunction())
7589 ->ShadowingDecls.push_back(
7590 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7591 return;
7592 }
7593 }
7594
7595 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7596 // A variable can't shadow a local variable in an enclosing scope, if
7597 // they are separated by a non-capturing declaration context.
7598 for (DeclContext *ParentDC = NewDC;
7599 ParentDC && !ParentDC->Equals(OldDC);
7600 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7601 // Only block literals, captured statements, and lambda expressions
7602 // can capture; other scopes don't.
7603 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7604 !isLambdaCallOperator(ParentDC)) {
7605 return;
7606 }
7607 }
7608 }
7609 }
7610 }
7611
7612 // Only warn about certain kinds of shadowing for class members.
7613 if (NewDC && NewDC->isRecord()) {
7614 // In particular, don't warn about shadowing non-class members.
7615 if (!OldDC->isRecord())
7616 return;
7617
7618 // TODO: should we warn about static data members shadowing
7619 // static data members from base classes?
7620
7621 // TODO: don't diagnose for inaccessible shadowed members.
7622 // This is hard to do perfectly because we might friend the
7623 // shadowing context, but that's just a false negative.
7624 }
7625
7626
7627 DeclarationName Name = R.getLookupName();
7628
7629 // Emit warning and note.
7630 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7631 return;
7632 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7633 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7634 if (!CaptureLoc.isInvalid())
7635 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7636 << Name << /*explicitly*/ 1;
7637 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7638}
7639
7640/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7641/// when these variables are captured by the lambda.
7642void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7643 for (const auto &Shadow : LSI->ShadowingDecls) {
7644 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7645 // Try to avoid the warning when the shadowed decl isn't captured.
7646 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7647 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7648 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7649 ? diag::warn_decl_shadow_uncaptured_local
7650 : diag::warn_decl_shadow)
7651 << Shadow.VD->getDeclName()
7652 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7653 if (!CaptureLoc.isInvalid())
7654 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7655 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7656 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7657 }
7658}
7659
7660/// Check -Wshadow without the advantage of a previous lookup.
7661void Sema::CheckShadow(Scope *S, VarDecl *D) {
7662 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7663 return;
7664
7665 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7666 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7667 LookupName(R, S);
7668 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7669 CheckShadow(D, ShadowedDecl, R);
7670}
7671
7672/// Check if 'E', which is an expression that is about to be modified, refers
7673/// to a constructor parameter that shadows a field.
7674void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7675 // Quickly ignore expressions that can't be shadowing ctor parameters.
7676 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7677 return;
7678 E = E->IgnoreParenImpCasts();
7679 auto *DRE = dyn_cast<DeclRefExpr>(E);
7680 if (!DRE)
7681 return;
7682 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7683 auto I = ShadowingDecls.find(D);
7684 if (I == ShadowingDecls.end())
7685 return;
7686 const NamedDecl *ShadowedDecl = I->second;
7687 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7688 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7689 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7690 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7691
7692 // Avoid issuing multiple warnings about the same decl.
7693 ShadowingDecls.erase(I);
7694}
7695
7696/// Check for conflict between this global or extern "C" declaration and
7697/// previous global or extern "C" declarations. This is only used in C++.
7698template<typename T>
7699static bool checkGlobalOrExternCConflict(
7700 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7701 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7701, __PRETTY_FUNCTION__))
;
7702 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7703
7704 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7705 // The common case: this global doesn't conflict with any extern "C"
7706 // declaration.
7707 return false;
7708 }
7709
7710 if (Prev) {
7711 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7712 // Both the old and new declarations have C language linkage. This is a
7713 // redeclaration.
7714 Previous.clear();
7715 Previous.addDecl(Prev);
7716 return true;
7717 }
7718
7719 // This is a global, non-extern "C" declaration, and there is a previous
7720 // non-global extern "C" declaration. Diagnose if this is a variable
7721 // declaration.
7722 if (!isa<VarDecl>(ND))
7723 return false;
7724 } else {
7725 // The declaration is extern "C". Check for any declaration in the
7726 // translation unit which might conflict.
7727 if (IsGlobal) {
7728 // We have already performed the lookup into the translation unit.
7729 IsGlobal = false;
7730 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7731 I != E; ++I) {
7732 if (isa<VarDecl>(*I)) {
7733 Prev = *I;
7734 break;
7735 }
7736 }
7737 } else {
7738 DeclContext::lookup_result R =
7739 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7740 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7741 I != E; ++I) {
7742 if (isa<VarDecl>(*I)) {
7743 Prev = *I;
7744 break;
7745 }
7746 // FIXME: If we have any other entity with this name in global scope,
7747 // the declaration is ill-formed, but that is a defect: it breaks the
7748 // 'stat' hack, for instance. Only variables can have mangled name
7749 // clashes with extern "C" declarations, so only they deserve a
7750 // diagnostic.
7751 }
7752 }
7753
7754 if (!Prev)
7755 return false;
7756 }
7757
7758 // Use the first declaration's location to ensure we point at something which
7759 // is lexically inside an extern "C" linkage-spec.
7760 assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose"
) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7760, __PRETTY_FUNCTION__))
;
7761 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7762 Prev = FD->getFirstDecl();
7763 else
7764 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7765
7766 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7767 << IsGlobal << ND;
7768 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7769 << IsGlobal;
7770 return false;
7771}
7772
7773/// Apply special rules for handling extern "C" declarations. Returns \c true
7774/// if we have found that this is a redeclaration of some prior entity.
7775///
7776/// Per C++ [dcl.link]p6:
7777/// Two declarations [for a function or variable] with C language linkage
7778/// with the same name that appear in different scopes refer to the same
7779/// [entity]. An entity with C language linkage shall not be declared with
7780/// the same name as an entity in global scope.
7781template<typename T>
7782static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7783 LookupResult &Previous) {
7784 if (!S.getLangOpts().CPlusPlus) {
7785 // In C, when declaring a global variable, look for a corresponding 'extern'
7786 // variable declared in function scope. We don't need this in C++, because
7787 // we find local extern decls in the surrounding file-scope DeclContext.
7788 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7789 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7790 Previous.clear();
7791 Previous.addDecl(Prev);
7792 return true;
7793 }
7794 }
7795 return false;
7796 }
7797
7798 // A declaration in the translation unit can conflict with an extern "C"
7799 // declaration.
7800 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7801 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7802
7803 // An extern "C" declaration can conflict with a declaration in the
7804 // translation unit or can be a redeclaration of an extern "C" declaration
7805 // in another scope.
7806 if (isIncompleteDeclExternC(S,ND))
7807 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7808
7809 // Neither global nor extern "C": nothing to do.
7810 return false;
7811}
7812
7813void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7814 // If the decl is already known invalid, don't check it.
7815 if (NewVD->isInvalidDecl())
7816 return;
7817
7818 QualType T = NewVD->getType();
7819
7820 // Defer checking an 'auto' type until its initializer is attached.
7821 if (T->isUndeducedType())
7822 return;
7823
7824 if (NewVD->hasAttrs())
7825 CheckAlignasUnderalignment(NewVD);
7826
7827 if (T->isObjCObjectType()) {
7828 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7829 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7830 T = Context.getObjCObjectPointerType(T);
7831 NewVD->setType(T);
7832 }
7833
7834 // Emit an error if an address space was applied to decl with local storage.
7835 // This includes arrays of objects with address space qualifiers, but not
7836 // automatic variables that point to other address spaces.
7837 // ISO/IEC TR 18037 S5.1.2
7838 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7839 T.getAddressSpace() != LangAS::Default) {
7840 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7841 NewVD->setInvalidDecl();
7842 return;
7843 }
7844
7845 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7846 // scope.
7847 if (getLangOpts().OpenCLVersion == 120 &&
7848 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7849 NewVD->isStaticLocal()) {
7850 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7851 NewVD->setInvalidDecl();
7852 return;
7853 }
7854
7855 if (getLangOpts().OpenCL) {
7856 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7857 if (NewVD->hasAttr<BlocksAttr>()) {
7858 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7859 return;
7860 }
7861
7862 if (T->isBlockPointerType()) {
7863 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7864 // can't use 'extern' storage class.
7865 if (!T.isConstQualified()) {
7866 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7867 << 0 /*const*/;
7868 NewVD->setInvalidDecl();
7869 return;
7870 }
7871 if (NewVD->hasExternalStorage()) {
7872 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7873 NewVD->setInvalidDecl();
7874 return;
7875 }
7876 }
7877 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7878 // __constant address space.
7879 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7880 // variables inside a function can also be declared in the global
7881 // address space.
7882 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7883 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7884 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7885 NewVD->hasExternalStorage()) {
7886 if (!T->isSamplerT() &&
7887 !T->isDependentType() &&
7888 !(T.getAddressSpace() == LangAS::opencl_constant ||
7889 (T.getAddressSpace() == LangAS::opencl_global &&
7890 (getLangOpts().OpenCLVersion == 200 ||
7891 getLangOpts().OpenCLCPlusPlus)))) {
7892 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7893 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7894 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7895 << Scope << "global or constant";
7896 else
7897 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7898 << Scope << "constant";
7899 NewVD->setInvalidDecl();
7900 return;
7901 }
7902 } else {
7903 if (T.getAddressSpace() == LangAS::opencl_global) {
7904 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7905 << 1 /*is any function*/ << "global";
7906 NewVD->setInvalidDecl();
7907 return;
7908 }
7909 if (T.getAddressSpace() == LangAS::opencl_constant ||
7910 T.getAddressSpace() == LangAS::opencl_local) {
7911 FunctionDecl *FD = getCurFunctionDecl();
7912 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7913 // in functions.
7914 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7915 if (T.getAddressSpace() == LangAS::opencl_constant)
7916 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7917 << 0 /*non-kernel only*/ << "constant";
7918 else
7919 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7920 << 0 /*non-kernel only*/ << "local";
7921 NewVD->setInvalidDecl();
7922 return;
7923 }
7924 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7925 // in the outermost scope of a kernel function.
7926 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7927 if (!getCurScope()->isFunctionScope()) {
7928 if (T.getAddressSpace() == LangAS::opencl_constant)
7929 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7930 << "constant";
7931 else
7932 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7933 << "local";
7934 NewVD->setInvalidDecl();
7935 return;
7936 }
7937 }
7938 } else if (T.getAddressSpace() != LangAS::opencl_private &&
7939 // If we are parsing a template we didn't deduce an addr
7940 // space yet.
7941 T.getAddressSpace() != LangAS::Default) {
7942 // Do not allow other address spaces on automatic variable.
7943 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7944 NewVD->setInvalidDecl();
7945 return;
7946 }
7947 }
7948 }
7949
7950 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7951 && !NewVD->hasAttr<BlocksAttr>()) {
7952 if (getLangOpts().getGC() != LangOptions::NonGC)
7953 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7954 else {
7955 assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 7955, __PRETTY_FUNCTION__))
;
7956 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7957 }
7958 }
7959
7960 bool isVM = T->isVariablyModifiedType();
7961 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7962 NewVD->hasAttr<BlocksAttr>())
7963 setFunctionHasBranchProtectedScope();
7964
7965 if ((isVM && NewVD->hasLinkage()) ||
7966 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7967 bool SizeIsNegative;
7968 llvm::APSInt Oversized;
7969 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7970 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7971 QualType FixedT;
7972 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7973 FixedT = FixedTInfo->getType();
7974 else if (FixedTInfo) {
7975 // Type and type-as-written are canonically different. We need to fix up
7976 // both types separately.
7977 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7978 Oversized);
7979 }
7980 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7981 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7982 // FIXME: This won't give the correct result for
7983 // int a[10][n];
7984 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7985
7986 if (NewVD->isFileVarDecl())
7987 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7988 << SizeRange;
7989 else if (NewVD->isStaticLocal())
7990 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7991 << SizeRange;
7992 else
7993 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7994 << SizeRange;
7995 NewVD->setInvalidDecl();
7996 return;
7997 }
7998
7999 if (!FixedTInfo) {
8000 if (NewVD->isFileVarDecl())
8001 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8002 else
8003 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8004 NewVD->setInvalidDecl();
8005 return;
8006 }
8007
8008 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
8009 NewVD->setType(FixedT);
8010 NewVD->setTypeSourceInfo(FixedTInfo);
8011 }
8012
8013 if (T->isVoidType()) {
8014 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8015 // of objects and functions.
8016 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8017 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8018 << T;
8019 NewVD->setInvalidDecl();
8020 return;
8021 }
8022 }
8023
8024 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8025 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8026 NewVD->setInvalidDecl();
8027 return;
8028 }
8029
8030 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8031 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8032 NewVD->setInvalidDecl();
8033 return;
8034 }
8035
8036 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8037 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8038 NewVD->setInvalidDecl();
8039 return;
8040 }
8041
8042 if (NewVD->isConstexpr() && !T->isDependentType() &&
8043 RequireLiteralType(NewVD->getLocation(), T,
8044 diag::err_constexpr_var_non_literal)) {
8045 NewVD->setInvalidDecl();
8046 return;
8047 }
8048}
8049
8050/// Perform semantic checking on a newly-created variable
8051/// declaration.
8052///
8053/// This routine performs all of the type-checking required for a
8054/// variable declaration once it has been built. It is used both to
8055/// check variables after they have been parsed and their declarators
8056/// have been translated into a declaration, and to check variables
8057/// that have been instantiated from a template.
8058///
8059/// Sets NewVD->isInvalidDecl() if an error was encountered.
8060///
8061/// Returns true if the variable declaration is a redeclaration.
8062bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8063 CheckVariableDeclarationType(NewVD);
8064
8065 // If the decl is already known invalid, don't check it.
8066 if (NewVD->isInvalidDecl())
8067 return false;
8068
8069 // If we did not find anything by this name, look for a non-visible
8070 // extern "C" declaration with the same name.
8071 if (Previous.empty() &&
8072 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8073 Previous.setShadowed();
8074
8075 if (!Previous.empty()) {
8076 MergeVarDecl(NewVD, Previous);
8077 return true;
8078 }
8079 return false;
8080}
8081
8082namespace {
8083struct FindOverriddenMethod {
8084 Sema *S;
8085 CXXMethodDecl *Method;
8086
8087 /// Member lookup function that determines whether a given C++
8088 /// method overrides a method in a base class, to be used with
8089 /// CXXRecordDecl::lookupInBases().
8090 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8091 RecordDecl *BaseRecord =
8092 Specifier->getType()->castAs<RecordType>()->getDecl();
8093
8094 DeclarationName Name = Method->getDeclName();
8095
8096 // FIXME: Do we care about other names here too?
8097 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8098 // We really want to find the base class destructor here.
8099 QualType T = S->Context.getTypeDeclType(BaseRecord);
8100 CanQualType CT = S->Context.getCanonicalType(T);
8101
8102 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8103 }
8104
8105 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8106 Path.Decls = Path.Decls.slice(1)) {
8107 NamedDecl *D = Path.Decls.front();
8108 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8109 if (MD->isVirtual() &&
8110 !S->IsOverload(
8111 Method, MD, /*UseMemberUsingDeclRules=*/false,
8112 /*ConsiderCudaAttrs=*/true,
8113 // C++2a [class.virtual]p2 does not consider requires clauses
8114 // when overriding.
8115 /*ConsiderRequiresClauses=*/false))
8116 return true;
8117 }
8118 }
8119
8120 return false;
8121 }
8122};
8123} // end anonymous namespace
8124
8125/// AddOverriddenMethods - See if a method overrides any in the base classes,
8126/// and if so, check that it's a valid override and remember it.
8127bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8128 // Look for methods in base classes that this method might override.
8129 CXXBasePaths Paths;
8130 FindOverriddenMethod FOM;
8131 FOM.Method = MD;
8132 FOM.S = this;
8133 bool AddedAny = false;
8134 if (DC->lookupInBases(FOM, Paths)) {
8135 for (auto *I : Paths.found_decls()) {
8136 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8137 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8138 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8139 !CheckOverridingFunctionAttributes(MD, OldMD) &&
8140 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8141 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8142 AddedAny = true;
8143 }
8144 }
8145 }
8146 }
8147
8148 return AddedAny;
8149}
8150
8151namespace {
8152 // Struct for holding all of the extra arguments needed by
8153 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8154 struct ActOnFDArgs {
8155 Scope *S;
8156 Declarator &D;
8157 MultiTemplateParamsArg TemplateParamLists;
8158 bool AddToScope;
8159 };
8160} // end anonymous namespace
8161
8162namespace {
8163
8164// Callback to only accept typo corrections that have a non-zero edit distance.
8165// Also only accept corrections that have the same parent decl.
8166class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8167 public:
8168 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8169 CXXRecordDecl *Parent)
8170 : Context(Context), OriginalFD(TypoFD),
8171 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8172
8173 bool ValidateCandidate(const TypoCorrection &candidate) override {
8174 if (candidate.getEditDistance() == 0)
8175 return false;
8176
8177 SmallVector<unsigned, 1> MismatchedParams;
8178 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8179 CDeclEnd = candidate.end();
8180 CDecl != CDeclEnd; ++CDecl) {
8181 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8182
8183 if (FD && !FD->hasBody() &&
8184 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8185 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8186 CXXRecordDecl *Parent = MD->getParent();
8187 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8188 return true;
8189 } else if (!ExpectedParent) {
8190 return true;
8191 }
8192 }
8193 }
8194
8195 return false;
8196 }
8197
8198 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8199 return std::make_unique<DifferentNameValidatorCCC>(*this);
8200 }
8201
8202 private:
8203 ASTContext &Context;
8204 FunctionDecl *OriginalFD;
8205 CXXRecordDecl *ExpectedParent;
8206};
8207
8208} // end anonymous namespace
8209
8210void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8211 TypoCorrectedFunctionDefinitions.insert(F);
8212}
8213
8214/// Generate diagnostics for an invalid function redeclaration.
8215///
8216/// This routine handles generating the diagnostic messages for an invalid
8217/// function redeclaration, including finding possible similar declarations
8218/// or performing typo correction if there are no previous declarations with
8219/// the same name.
8220///
8221/// Returns a NamedDecl iff typo correction was performed and substituting in
8222/// the new declaration name does not cause new errors.
8223static NamedDecl *DiagnoseInvalidRedeclaration(
8224 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8225 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8226 DeclarationName Name = NewFD->getDeclName();
8227 DeclContext *NewDC = NewFD->getDeclContext();
8228 SmallVector<unsigned, 1> MismatchedParams;
8229 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8230 TypoCorrection Correction;
8231 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8232 unsigned DiagMsg =
8233 IsLocalFriend ? diag::err_no_matching_local_friend :
8234 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8235 diag::err_member_decl_does_not_match;
8236 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8237 IsLocalFriend ? Sema::LookupLocalFriendName
8238 : Sema::LookupOrdinaryName,
8239 Sema::ForVisibleRedeclaration);
8240
8241 NewFD->setInvalidDecl();
8242 if (IsLocalFriend)
8243 SemaRef.LookupName(Prev, S);
8244 else
8245 SemaRef.LookupQualifiedName(Prev, NewDC);
8246 assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8247, __PRETTY_FUNCTION__))
8247 "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8247, __PRETTY_FUNCTION__))
;
8248 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8249 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8250 MD ? MD->getParent() : nullptr);
8251 if (!Prev.empty()) {
8252 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8253 Func != FuncEnd; ++Func) {
8254 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8255 if (FD &&
8256 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8257 // Add 1 to the index so that 0 can mean the mismatch didn't
8258 // involve a parameter
8259 unsigned ParamNum =
8260 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8261 NearMatches.push_back(std::make_pair(FD, ParamNum));
8262 }
8263 }
8264 // If the qualified name lookup yielded nothing, try typo correction
8265 } else if ((Correction = SemaRef.CorrectTypo(
8266 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8267 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8268 IsLocalFriend ? nullptr : NewDC))) {
8269 // Set up everything for the call to ActOnFunctionDeclarator
8270 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8271 ExtraArgs.D.getIdentifierLoc());
8272 Previous.clear();
8273 Previous.setLookupName(Correction.getCorrection());
8274 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8275 CDeclEnd = Correction.end();
8276 CDecl != CDeclEnd; ++CDecl) {
8277 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8278 if (FD && !FD->hasBody() &&
8279 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8280 Previous.addDecl(FD);
8281 }
8282 }
8283 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8284
8285 NamedDecl *Result;
8286 // Retry building the function declaration with the new previous
8287 // declarations, and with errors suppressed.
8288 {
8289 // Trap errors.
8290 Sema::SFINAETrap Trap(SemaRef);
8291
8292 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8293 // pieces need to verify the typo-corrected C++ declaration and hopefully
8294 // eliminate the need for the parameter pack ExtraArgs.
8295 Result = SemaRef.ActOnFunctionDeclarator(
8296 ExtraArgs.S, ExtraArgs.D,
8297 Correction.getCorrectionDecl()->getDeclContext(),
8298 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8299 ExtraArgs.AddToScope);
8300
8301 if (Trap.hasErrorOccurred())
8302 Result = nullptr;
8303 }
8304
8305 if (Result) {
8306 // Determine which correction we picked.
8307 Decl *Canonical = Result->getCanonicalDecl();
8308 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8309 I != E; ++I)
8310 if ((*I)->getCanonicalDecl() == Canonical)
8311 Correction.setCorrectionDecl(*I);
8312
8313 // Let Sema know about the correction.
8314 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8315 SemaRef.diagnoseTypo(
8316 Correction,
8317 SemaRef.PDiag(IsLocalFriend
8318 ? diag::err_no_matching_local_friend_suggest
8319 : diag::err_member_decl_does_not_match_suggest)
8320 << Name << NewDC << IsDefinition);
8321 return Result;
8322 }
8323
8324 // Pretend the typo correction never occurred
8325 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8326 ExtraArgs.D.getIdentifierLoc());
8327 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8328 Previous.clear();
8329 Previous.setLookupName(Name);
8330 }
8331
8332 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8333 << Name << NewDC << IsDefinition << NewFD->getLocation();
8334
8335 bool NewFDisConst = false;
8336 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8337 NewFDisConst = NewMD->isConst();
8338
8339 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8340 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8341 NearMatch != NearMatchEnd; ++NearMatch) {
8342 FunctionDecl *FD = NearMatch->first;
8343 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8344 bool FDisConst = MD && MD->isConst();
8345 bool IsMember = MD || !IsLocalFriend;
8346
8347 // FIXME: These notes are poorly worded for the local friend case.
8348 if (unsigned Idx = NearMatch->second) {
8349 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8350 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8351 if (Loc.isInvalid()) Loc = FD->getLocation();
8352 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8353 : diag::note_local_decl_close_param_match)
8354 << Idx << FDParam->getType()
8355 << NewFD->getParamDecl(Idx - 1)->getType();
8356 } else if (FDisConst != NewFDisConst) {
8357 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8358 << NewFDisConst << FD->getSourceRange().getEnd();
8359 } else
8360 SemaRef.Diag(FD->getLocation(),
8361 IsMember ? diag::note_member_def_close_match
8362 : diag::note_local_decl_close_match);
8363 }
8364 return nullptr;
8365}
8366
8367static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8368 switch (D.getDeclSpec().getStorageClassSpec()) {
8369 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8369)
;
8370 case DeclSpec::SCS_auto:
8371 case DeclSpec::SCS_register:
8372 case DeclSpec::SCS_mutable:
8373 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8374 diag::err_typecheck_sclass_func);
8375 D.getMutableDeclSpec().ClearStorageClassSpecs();
8376 D.setInvalidType();
8377 break;
8378 case DeclSpec::SCS_unspecified: break;
8379 case DeclSpec::SCS_extern:
8380 if (D.getDeclSpec().isExternInLinkageSpec())
8381 return SC_None;
8382 return SC_Extern;
8383 case DeclSpec::SCS_static: {
8384 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8385 // C99 6.7.1p5:
8386 // The declaration of an identifier for a function that has
8387 // block scope shall have no explicit storage-class specifier
8388 // other than extern
8389 // See also (C++ [dcl.stc]p4).
8390 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8391 diag::err_static_block_func);
8392 break;
8393 } else
8394 return SC_Static;
8395 }
8396 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8397 }
8398
8399 // No explicit storage class has already been returned
8400 return SC_None;
8401}
8402
8403static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8404 DeclContext *DC, QualType &R,
8405 TypeSourceInfo *TInfo,
8406 StorageClass SC,
8407 bool &IsVirtualOkay) {
8408 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8409 DeclarationName Name = NameInfo.getName();
8410
8411 FunctionDecl *NewFD = nullptr;
8412 bool isInline = D.getDeclSpec().isInlineSpecified();
8413
8414 if (!SemaRef.getLangOpts().CPlusPlus) {
8415 // Determine whether the function was written with a
8416 // prototype. This true when:
8417 // - there is a prototype in the declarator, or
8418 // - the type R of the function is some kind of typedef or other non-
8419 // attributed reference to a type name (which eventually refers to a
8420 // function type).
8421 bool HasPrototype =
8422 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8423 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8424
8425 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8426 R, TInfo, SC, isInline, HasPrototype,
8427 CSK_unspecified,
8428 /*TrailingRequiresClause=*/nullptr);
8429 if (D.isInvalidType())
8430 NewFD->setInvalidDecl();
8431
8432 return NewFD;
8433 }
8434
8435 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8436
8437 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8438 if (ConstexprKind == CSK_constinit) {
8439 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8440 diag::err_constexpr_wrong_decl_kind)
8441 << ConstexprKind;
8442 ConstexprKind = CSK_unspecified;
8443 D.getMutableDeclSpec().ClearConstexprSpec();
8444 }
8445 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8446
8447 // Check that the return type is not an abstract class type.
8448 // For record types, this is done by the AbstractClassUsageDiagnoser once
8449 // the class has been completely parsed.
8450 if (!DC->isRecord() &&
8451 SemaRef.RequireNonAbstractType(
8452 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8453 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8454 D.setInvalidType();
8455
8456 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8457 // This is a C++ constructor declaration.
8458 assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8459, __PRETTY_FUNCTION__))
8459 "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8459, __PRETTY_FUNCTION__))
;
8460
8461 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8462 return CXXConstructorDecl::Create(
8463 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8464 TInfo, ExplicitSpecifier, isInline,
8465 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8466 TrailingRequiresClause);
8467
8468 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8469 // This is a C++ destructor declaration.
8470 if (DC->isRecord()) {
8471 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8472 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8473 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8474 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8475 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8476 TrailingRequiresClause);
8477
8478 // If the destructor needs an implicit exception specification, set it
8479 // now. FIXME: It'd be nice to be able to create the right type to start
8480 // with, but the type needs to reference the destructor declaration.
8481 if (SemaRef.getLangOpts().CPlusPlus11)
8482 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8483
8484 IsVirtualOkay = true;
8485 return NewDD;
8486
8487 } else {
8488 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8489 D.setInvalidType();
8490
8491 // Create a FunctionDecl to satisfy the function definition parsing
8492 // code path.
8493 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8494 D.getIdentifierLoc(), Name, R, TInfo, SC,
8495 isInline,
8496 /*hasPrototype=*/true, ConstexprKind,
8497 TrailingRequiresClause);
8498 }
8499
8500 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8501 if (!DC->isRecord()) {
8502 SemaRef.Diag(D.getIdentifierLoc(),
8503 diag::err_conv_function_not_member);
8504 return nullptr;
8505 }
8506
8507 SemaRef.CheckConversionDeclarator(D, R, SC);
8508 if (D.isInvalidType())
8509 return nullptr;
8510
8511 IsVirtualOkay = true;
8512 return CXXConversionDecl::Create(
8513 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8514 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8515 TrailingRequiresClause);
8516
8517 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8518 if (TrailingRequiresClause)
8519 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8520 diag::err_trailing_requires_clause_on_deduction_guide)
8521 << TrailingRequiresClause->getSourceRange();
8522 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8523
8524 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8525 ExplicitSpecifier, NameInfo, R, TInfo,
8526 D.getEndLoc());
8527 } else if (DC->isRecord()) {
8528 // If the name of the function is the same as the name of the record,
8529 // then this must be an invalid constructor that has a return type.
8530 // (The parser checks for a return type and makes the declarator a
8531 // constructor if it has no return type).
8532 if (Name.getAsIdentifierInfo() &&
8533 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8534 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8535 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8536 << SourceRange(D.getIdentifierLoc());
8537 return nullptr;
8538 }
8539
8540 // This is a C++ method declaration.
8541 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8542 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8543 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8544 TrailingRequiresClause);
8545 IsVirtualOkay = !Ret->isStatic();
8546 return Ret;
8547 } else {
8548 bool isFriend =
8549 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8550 if (!isFriend && SemaRef.CurContext->isRecord())
8551 return nullptr;
8552
8553 // Determine whether the function was written with a
8554 // prototype. This true when:
8555 // - we're in C++ (where every function has a prototype),
8556 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8557 R, TInfo, SC, isInline, true /*HasPrototype*/,
8558 ConstexprKind, TrailingRequiresClause);
8559 }
8560}
8561
8562enum OpenCLParamType {
8563 ValidKernelParam,
8564 PtrPtrKernelParam,
8565 PtrKernelParam,
8566 InvalidAddrSpacePtrKernelParam,
8567 InvalidKernelParam,
8568 RecordKernelParam
8569};
8570
8571static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8572 // Size dependent types are just typedefs to normal integer types
8573 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8574 // integers other than by their names.
8575 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8576
8577 // Remove typedefs one by one until we reach a typedef
8578 // for a size dependent type.
8579 QualType DesugaredTy = Ty;
8580 do {
8581 ArrayRef<StringRef> Names(SizeTypeNames);
8582 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8583 if (Names.end() != Match)
8584 return true;
8585
8586 Ty = DesugaredTy;
8587 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8588 } while (DesugaredTy != Ty);
8589
8590 return false;
8591}
8592
8593static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8594 if (PT->isPointerType()) {
8595 QualType PointeeType = PT->getPointeeType();
8596 if (PointeeType->isPointerType())
8597 return PtrPtrKernelParam;
8598 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8599 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8600 PointeeType.getAddressSpace() == LangAS::Default)
8601 return InvalidAddrSpacePtrKernelParam;
8602 return PtrKernelParam;
8603 }
8604
8605 // OpenCL v1.2 s6.9.k:
8606 // Arguments to kernel functions in a program cannot be declared with the
8607 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8608 // uintptr_t or a struct and/or union that contain fields declared to be one
8609 // of these built-in scalar types.
8610 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8611 return InvalidKernelParam;
8612
8613 if (PT->isImageType())
8614 return PtrKernelParam;
8615
8616 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8617 return InvalidKernelParam;
8618
8619 // OpenCL extension spec v1.2 s9.5:
8620 // This extension adds support for half scalar and vector types as built-in
8621 // types that can be used for arithmetic operations, conversions etc.
8622 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8623 return InvalidKernelParam;
8624
8625 if (PT->isRecordType())
8626 return RecordKernelParam;
8627
8628 // Look into an array argument to check if it has a forbidden type.
8629 if (PT->isArrayType()) {
8630 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8631 // Call ourself to check an underlying type of an array. Since the
8632 // getPointeeOrArrayElementType returns an innermost type which is not an
8633 // array, this recursive call only happens once.
8634 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8635 }
8636
8637 return ValidKernelParam;
8638}
8639
8640static void checkIsValidOpenCLKernelParameter(
8641 Sema &S,
8642 Declarator &D,
8643 ParmVarDecl *Param,
8644 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8645 QualType PT = Param->getType();
8646
8647 // Cache the valid types we encounter to avoid rechecking structs that are
8648 // used again
8649 if (ValidTypes.count(PT.getTypePtr()))
8650 return;
8651
8652 switch (getOpenCLKernelParameterType(S, PT)) {
8653 case PtrPtrKernelParam:
8654 // OpenCL v1.2 s6.9.a:
8655 // A kernel function argument cannot be declared as a
8656 // pointer to a pointer type.
8657 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8658 D.setInvalidType();
8659 return;
8660
8661 case InvalidAddrSpacePtrKernelParam:
8662 // OpenCL v1.0 s6.5:
8663 // __kernel function arguments declared to be a pointer of a type can point
8664 // to one of the following address spaces only : __global, __local or
8665 // __constant.
8666 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8667 D.setInvalidType();
8668 return;
8669
8670 // OpenCL v1.2 s6.9.k:
8671 // Arguments to kernel functions in a program cannot be declared with the
8672 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8673 // uintptr_t or a struct and/or union that contain fields declared to be
8674 // one of these built-in scalar types.
8675
8676 case InvalidKernelParam:
8677 // OpenCL v1.2 s6.8 n:
8678 // A kernel function argument cannot be declared
8679 // of event_t type.
8680 // Do not diagnose half type since it is diagnosed as invalid argument
8681 // type for any function elsewhere.
8682 if (!PT->isHalfType()) {
8683 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8684
8685 // Explain what typedefs are involved.
8686 const TypedefType *Typedef = nullptr;
8687 while ((Typedef = PT->getAs<TypedefType>())) {
8688 SourceLocation Loc = Typedef->getDecl()->getLocation();
8689 // SourceLocation may be invalid for a built-in type.
8690 if (Loc.isValid())
8691 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8692 PT = Typedef->desugar();
8693 }
8694 }
8695
8696 D.setInvalidType();
8697 return;
8698
8699 case PtrKernelParam:
8700 case ValidKernelParam:
8701 ValidTypes.insert(PT.getTypePtr());
8702 return;
8703
8704 case RecordKernelParam:
8705 break;
8706 }
8707
8708 // Track nested structs we will inspect
8709 SmallVector<const Decl *, 4> VisitStack;
8710
8711 // Track where we are in the nested structs. Items will migrate from
8712 // VisitStack to HistoryStack as we do the DFS for bad field.
8713 SmallVector<const FieldDecl *, 4> HistoryStack;
8714 HistoryStack.push_back(nullptr);
8715
8716 // At this point we already handled everything except of a RecordType or
8717 // an ArrayType of a RecordType.
8718 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."
) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8718, __PRETTY_FUNCTION__))
;
8719 const RecordType *RecTy =
8720 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8721 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8722
8723 VisitStack.push_back(RecTy->getDecl());
8724 assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast
<void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8724, __PRETTY_FUNCTION__))
;
8725
8726 do {
8727 const Decl *Next = VisitStack.pop_back_val();
8728 if (!Next) {
8729 assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail
("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8729, __PRETTY_FUNCTION__))
;
8730 // Found a marker, we have gone up a level
8731 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8732 ValidTypes.insert(Hist->getType().getTypePtr());
8733
8734 continue;
8735 }
8736
8737 // Adds everything except the original parameter declaration (which is not a
8738 // field itself) to the history stack.
8739 const RecordDecl *RD;
8740 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8741 HistoryStack.push_back(Field);
8742
8743 QualType FieldTy = Field->getType();
8744 // Other field types (known to be valid or invalid) are handled while we
8745 // walk around RecordDecl::fields().
8746 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8747, __PRETTY_FUNCTION__))
8747 "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8747, __PRETTY_FUNCTION__))
;
8748 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8749
8750 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8751 } else {
8752 RD = cast<RecordDecl>(Next);
8753 }
8754
8755 // Add a null marker so we know when we've gone back up a level
8756 VisitStack.push_back(nullptr);
8757
8758 for (const auto *FD : RD->fields()) {
8759 QualType QT = FD->getType();
8760
8761 if (ValidTypes.count(QT.getTypePtr()))
8762 continue;
8763
8764 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8765 if (ParamType == ValidKernelParam)
8766 continue;
8767
8768 if (ParamType == RecordKernelParam) {
8769 VisitStack.push_back(FD);
8770 continue;
8771 }
8772
8773 // OpenCL v1.2 s6.9.p:
8774 // Arguments to kernel functions that are declared to be a struct or union
8775 // do not allow OpenCL objects to be passed as elements of the struct or
8776 // union.
8777 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8778 ParamType == InvalidAddrSpacePtrKernelParam) {
8779 S.Diag(Param->getLocation(),
8780 diag::err_record_with_pointers_kernel_param)
8781 << PT->isUnionType()
8782 << PT;
8783 } else {
8784 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8785 }
8786
8787 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8788 << OrigRecDecl->getDeclName();
8789
8790 // We have an error, now let's go back up through history and show where
8791 // the offending field came from
8792 for (ArrayRef<const FieldDecl *>::const_iterator
8793 I = HistoryStack.begin() + 1,
8794 E = HistoryStack.end();
8795 I != E; ++I) {
8796 const FieldDecl *OuterField = *I;
8797 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8798 << OuterField->getType();
8799 }
8800
8801 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8802 << QT->isPointerType()
8803 << QT;
8804 D.setInvalidType();
8805 return;
8806 }
8807 } while (!VisitStack.empty());
8808}
8809
8810/// Find the DeclContext in which a tag is implicitly declared if we see an
8811/// elaborated type specifier in the specified context, and lookup finds
8812/// nothing.
8813static DeclContext *getTagInjectionContext(DeclContext *DC) {
8814 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8815 DC = DC->getParent();
8816 return DC;
8817}
8818
8819/// Find the Scope in which a tag is implicitly declared if we see an
8820/// elaborated type specifier in the specified context, and lookup finds
8821/// nothing.
8822static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8823 while (S->isClassScope() ||
8824 (LangOpts.CPlusPlus &&
8825 S->isFunctionPrototypeScope()) ||
8826 ((S->getFlags() & Scope::DeclScope) == 0) ||
8827 (S->getEntity() && S->getEntity()->isTransparentContext()))
8828 S = S->getParent();
8829 return S;
8830}
8831
8832NamedDecl*
8833Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8834 TypeSourceInfo *TInfo, LookupResult &Previous,
8835 MultiTemplateParamsArg TemplateParamListsRef,
8836 bool &AddToScope) {
8837 QualType R = TInfo->getType();
8838
8839 assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail
("R->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 8839, __PRETTY_FUNCTION__))
;
8840 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8841 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8842
8843 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8844 for (TemplateParameterList *TPL : TemplateParamListsRef)
8845 TemplateParamLists.push_back(TPL);
8846 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8847 if (!TemplateParamLists.empty() &&
8848 Invented->getDepth() == TemplateParamLists.back()->getDepth())
8849 TemplateParamLists.back() = Invented;
8850 else
8851 TemplateParamLists.push_back(Invented);
8852 }
8853
8854 // TODO: consider using NameInfo for diagnostic.
8855 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8856 DeclarationName Name = NameInfo.getName();
8857 StorageClass SC = getFunctionStorageClass(*this, D);
8858
8859 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8860 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8861 diag::err_invalid_thread)
8862 << DeclSpec::getSpecifierName(TSCS);
8863
8864 if (D.isFirstDeclarationOfMember())
8865 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8866 D.getIdentifierLoc());
8867
8868 bool isFriend = false;
8869 FunctionTemplateDecl *FunctionTemplate = nullptr;
8870 bool isMemberSpecialization = false;
8871 bool isFunctionTemplateSpecialization = false;
8872
8873 bool isDependentClassScopeExplicitSpecialization = false;
8874 bool HasExplicitTemplateArgs = false;
8875 TemplateArgumentListInfo TemplateArgs;
8876
8877 bool isVirtualOkay = false;
8878
8879 DeclContext *OriginalDC = DC;
8880 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8881
8882 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8883 isVirtualOkay);
8884 if (!NewFD) return nullptr;
8885
8886 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8887 NewFD->setTopLevelDeclInObjCContainer();
8888
8889 // Set the lexical context. If this is a function-scope declaration, or has a
8890 // C++ scope specifier, or is the object of a friend declaration, the lexical
8891 // context will be different from the semantic context.
8892 NewFD->setLexicalDeclContext(CurContext);
8893
8894 if (IsLocalExternDecl)
8895 NewFD->setLocalExternDecl();
8896
8897 if (getLangOpts().CPlusPlus) {
8898 bool isInline = D.getDeclSpec().isInlineSpecified();
8899 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8900 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8901 isFriend = D.getDeclSpec().isFriendSpecified();
8902 if (isFriend && !isInline && D.isFunctionDefinition()) {
8903 // C++ [class.friend]p5
8904 // A function can be defined in a friend declaration of a
8905 // class . . . . Such a function is implicitly inline.
8906 NewFD->setImplicitlyInline();
8907 }
8908
8909 // If this is a method defined in an __interface, and is not a constructor
8910 // or an overloaded operator, then set the pure flag (isVirtual will already
8911 // return true).
8912 if (const CXXRecordDecl *Parent =
8913 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8914 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8915 NewFD->setPure(true);
8916
8917 // C++ [class.union]p2
8918 // A union can have member functions, but not virtual functions.
8919 if (isVirtual && Parent->isUnion())
8920 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8921 }
8922
8923 SetNestedNameSpecifier(*this, NewFD, D);
8924 isMemberSpecialization = false;
8925 isFunctionTemplateSpecialization = false;
8926 if (D.isInvalidType())
8927 NewFD->setInvalidDecl();
8928
8929 // Match up the template parameter lists with the scope specifier, then
8930 // determine whether we have a template or a template specialization.
8931 bool Invalid = false;
8932 TemplateParameterList *TemplateParams =
8933 MatchTemplateParametersToScopeSpecifier(
8934 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8935 D.getCXXScopeSpec(),
8936 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8937 ? D.getName().TemplateId
8938 : nullptr,
8939 TemplateParamLists, isFriend, isMemberSpecialization,
8940 Invalid);
8941 if (TemplateParams) {
8942 // Check that we can declare a template here.
8943 if (CheckTemplateDeclScope(S, TemplateParams))
8944 NewFD->setInvalidDecl();
8945
8946 if (TemplateParams->size() > 0) {
8947 // This is a function template
8948
8949 // A destructor cannot be a template.
8950 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8951 Diag(NewFD->getLocation(), diag::err_destructor_template);
8952 NewFD->setInvalidDecl();
8953 }
8954
8955 // If we're adding a template to a dependent context, we may need to
8956 // rebuilding some of the types used within the template parameter list,
8957 // now that we know what the current instantiation is.
8958 if (DC->isDependentContext()) {
8959 ContextRAII SavedContext(*this, DC);
8960 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8961 Invalid = true;
8962 }
8963
8964 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8965 NewFD->getLocation(),
8966 Name, TemplateParams,
8967 NewFD);
8968 FunctionTemplate->setLexicalDeclContext(CurContext);
8969 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8970
8971 // For source fidelity, store the other template param lists.
8972 if (TemplateParamLists.size() > 1) {
8973 NewFD->setTemplateParameterListsInfo(Context,
8974 ArrayRef<TemplateParameterList *>(TemplateParamLists)
8975 .drop_back(1));
8976 }
8977 } else {
8978 // This is a function template specialization.
8979 isFunctionTemplateSpecialization = true;
8980 // For source fidelity, store all the template param lists.
8981 if (TemplateParamLists.size() > 0)
8982 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8983
8984 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8985 if (isFriend) {
8986 // We want to remove the "template<>", found here.
8987 SourceRange RemoveRange = TemplateParams->getSourceRange();
8988
8989 // If we remove the template<> and the name is not a
8990 // template-id, we're actually silently creating a problem:
8991 // the friend declaration will refer to an untemplated decl,
8992 // and clearly the user wants a template specialization. So
8993 // we need to insert '<>' after the name.
8994 SourceLocation InsertLoc;
8995 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8996 InsertLoc = D.getName().getSourceRange().getEnd();
8997 InsertLoc = getLocForEndOfToken(InsertLoc);
8998 }
8999
9000 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9001 << Name << RemoveRange
9002 << FixItHint::CreateRemoval(RemoveRange)
9003 << FixItHint::CreateInsertion(InsertLoc, "<>");
9004 }
9005 }
9006 } else {
9007 // Check that we can declare a template here.
9008 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9009 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9010 NewFD->setInvalidDecl();
9011
9012 // All template param lists were matched against the scope specifier:
9013 // this is NOT (an explicit specialization of) a template.
9014 if (TemplateParamLists.size() > 0)
9015 // For source fidelity, store all the template param lists.
9016 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9017 }
9018
9019 if (Invalid) {
9020 NewFD->setInvalidDecl();
9021 if (FunctionTemplate)
9022 FunctionTemplate->setInvalidDecl();
9023 }
9024
9025 // C++ [dcl.fct.spec]p5:
9026 // The virtual specifier shall only be used in declarations of
9027 // nonstatic class member functions that appear within a
9028 // member-specification of a class declaration; see 10.3.
9029 //
9030 if (isVirtual && !NewFD->isInvalidDecl()) {
9031 if (!isVirtualOkay) {
9032 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9033 diag::err_virtual_non_function);
9034 } else if (!CurContext->isRecord()) {
9035 // 'virtual' was specified outside of the class.
9036 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9037 diag::err_virtual_out_of_class)
9038 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9039 } else if (NewFD->getDescribedFunctionTemplate()) {
9040 // C++ [temp.mem]p3:
9041 // A member function template shall not be virtual.
9042 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9043 diag::err_virtual_member_function_template)
9044 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9045 } else {
9046 // Okay: Add virtual to the method.
9047 NewFD->setVirtualAsWritten(true);
9048 }
9049
9050 if (getLangOpts().CPlusPlus14 &&
9051 NewFD->getReturnType()->isUndeducedType())
9052 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9053 }
9054
9055 if (getLangOpts().CPlusPlus14 &&
9056 (NewFD->isDependentContext() ||
9057 (isFriend && CurContext->isDependentContext())) &&
9058 NewFD->getReturnType()->isUndeducedType()) {
9059 // If the function template is referenced directly (for instance, as a
9060 // member of the current instantiation), pretend it has a dependent type.
9061 // This is not really justified by the standard, but is the only sane
9062 // thing to do.
9063 // FIXME: For a friend function, we have not marked the function as being
9064 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9065 const FunctionProtoType *FPT =
9066 NewFD->getType()->castAs<FunctionProtoType>();
9067 QualType Result =
9068 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9069 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9070 FPT->getExtProtoInfo()));
9071 }
9072
9073 // C++ [dcl.fct.spec]p3:
9074 // The inline specifier shall not appear on a block scope function
9075 // declaration.
9076 if (isInline && !NewFD->isInvalidDecl()) {
9077 if (CurContext->isFunctionOrMethod()) {
9078 // 'inline' is not allowed on block scope function declaration.
9079 Diag(D.getDeclSpec().getInlineSpecLoc(),
9080 diag::err_inline_declaration_block_scope) << Name
9081 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9082 }
9083 }
9084
9085 // C++ [dcl.fct.spec]p6:
9086 // The explicit specifier shall be used only in the declaration of a
9087 // constructor or conversion function within its class definition;
9088 // see 12.3.1 and 12.3.2.
9089 if (hasExplicit && !NewFD->isInvalidDecl() &&
9090 !isa<CXXDeductionGuideDecl>(NewFD)) {
9091 if (!CurContext->isRecord()) {
9092 // 'explicit' was specified outside of the class.
9093 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9094 diag::err_explicit_out_of_class)
9095 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9096 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9097 !isa<CXXConversionDecl>(NewFD)) {
9098 // 'explicit' was specified on a function that wasn't a constructor
9099 // or conversion function.
9100 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9101 diag::err_explicit_non_ctor_or_conv_function)
9102 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9103 }
9104 }
9105
9106 if (ConstexprSpecKind ConstexprKind =
9107 D.getDeclSpec().getConstexprSpecifier()) {
9108 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9109 // are implicitly inline.
9110 NewFD->setImplicitlyInline();
9111
9112 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9113 // be either constructors or to return a literal type. Therefore,
9114 // destructors cannot be declared constexpr.
9115 if (isa<CXXDestructorDecl>(NewFD) &&
9116 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9117 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9118 << ConstexprKind;
9119 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9120 }
9121 // C++20 [dcl.constexpr]p2: An allocation function, or a
9122 // deallocation function shall not be declared with the consteval
9123 // specifier.
9124 if (ConstexprKind == CSK_consteval &&
9125 (NewFD->getOverloadedOperator() == OO_New ||
9126 NewFD->getOverloadedOperator() == OO_Array_New ||
9127 NewFD->getOverloadedOperator() == OO_Delete ||
9128 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9129 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9130 diag::err_invalid_consteval_decl_kind)
9131 << NewFD;
9132 NewFD->setConstexprKind(CSK_constexpr);
9133 }
9134 }
9135
9136 // If __module_private__ was specified, mark the function accordingly.
9137 if (D.getDeclSpec().isModulePrivateSpecified()) {
9138 if (isFunctionTemplateSpecialization) {
9139 SourceLocation ModulePrivateLoc
9140 = D.getDeclSpec().getModulePrivateSpecLoc();
9141 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9142 << 0
9143 << FixItHint::CreateRemoval(ModulePrivateLoc);
9144 } else {
9145 NewFD->setModulePrivate();
9146 if (FunctionTemplate)
9147 FunctionTemplate->setModulePrivate();
9148 }
9149 }
9150
9151 if (isFriend) {
9152 if (FunctionTemplate) {
9153 FunctionTemplate->setObjectOfFriendDecl();
9154 FunctionTemplate->setAccess(AS_public);
9155 }
9156 NewFD->setObjectOfFriendDecl();
9157 NewFD->setAccess(AS_public);
9158 }
9159
9160 // If a function is defined as defaulted or deleted, mark it as such now.
9161 // We'll do the relevant checks on defaulted / deleted functions later.
9162 switch (D.getFunctionDefinitionKind()) {
9163 case FDK_Declaration:
9164 case FDK_Definition:
9165 break;
9166
9167 case FDK_Defaulted:
9168 NewFD->setDefaulted();
9169 break;
9170
9171 case FDK_Deleted:
9172 NewFD->setDeletedAsWritten();
9173 break;
9174 }
9175
9176 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9177 D.isFunctionDefinition()) {
9178 // C++ [class.mfct]p2:
9179 // A member function may be defined (8.4) in its class definition, in
9180 // which case it is an inline member function (7.1.2)
9181 NewFD->setImplicitlyInline();
9182 }
9183
9184 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9185 !CurContext->isRecord()) {
9186 // C++ [class.static]p1:
9187 // A data or function member of a class may be declared static
9188 // in a class definition, in which case it is a static member of
9189 // the class.
9190
9191 // Complain about the 'static' specifier if it's on an out-of-line
9192 // member function definition.
9193
9194 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9195 // member function template declaration and class member template
9196 // declaration (MSVC versions before 2015), warn about this.
9197 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9198 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9199 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9200 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9201 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9202 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9203 }
9204
9205 // C++11 [except.spec]p15:
9206 // A deallocation function with no exception-specification is treated
9207 // as if it were specified with noexcept(true).
9208 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9209 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9210 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9211 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9212 NewFD->setType(Context.getFunctionType(
9213 FPT->getReturnType(), FPT->getParamTypes(),
9214 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9215 }
9216
9217 // Filter out previous declarations that don't match the scope.
9218 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9219 D.getCXXScopeSpec().isNotEmpty() ||
9220 isMemberSpecialization ||
9221 isFunctionTemplateSpecialization);
9222
9223 // Handle GNU asm-label extension (encoded as an attribute).
9224 if (Expr *E = (Expr*) D.getAsmLabel()) {
9225 // The parser guarantees this is a string.
9226 StringLiteral *SE = cast<StringLiteral>(E);
9227 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9228 /*IsLiteralLabel=*/true,
9229 SE->getStrTokenLoc(0)));
9230 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9231 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9232 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9233 if (I != ExtnameUndeclaredIdentifiers.end()) {
9234 if (isDeclExternC(NewFD)) {
9235 NewFD->addAttr(I->second);
9236 ExtnameUndeclaredIdentifiers.erase(I);
9237 } else
9238 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9239 << /*Variable*/0 << NewFD;
9240 }
9241 }
9242
9243 // Copy the parameter declarations from the declarator D to the function
9244 // declaration NewFD, if they are available. First scavenge them into Params.
9245 SmallVector<ParmVarDecl*, 16> Params;
9246 unsigned FTIIdx;
9247 if (D.isFunctionDeclarator(FTIIdx)) {
9248 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9249
9250 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9251 // function that takes no arguments, not a function that takes a
9252 // single void argument.
9253 // We let through "const void" here because Sema::GetTypeForDeclarator
9254 // already checks for that case.
9255 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9256 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9257 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9258 assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?"
) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9258, __PRETTY_FUNCTION__))
;
9259 Param->setDeclContext(NewFD);
9260 Params.push_back(Param);
9261
9262 if (Param->isInvalidDecl())
9263 NewFD->setInvalidDecl();
9264 }
9265 }
9266
9267 if (!getLangOpts().CPlusPlus) {
9268 // In C, find all the tag declarations from the prototype and move them
9269 // into the function DeclContext. Remove them from the surrounding tag
9270 // injection context of the function, which is typically but not always
9271 // the TU.
9272 DeclContext *PrototypeTagContext =
9273 getTagInjectionContext(NewFD->getLexicalDeclContext());
9274 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9275 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9276
9277 // We don't want to reparent enumerators. Look at their parent enum
9278 // instead.
9279 if (!TD) {
9280 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9281 TD = cast<EnumDecl>(ECD->getDeclContext());
9282 }
9283 if (!TD)
9284 continue;
9285 DeclContext *TagDC = TD->getLexicalDeclContext();
9286 if (!TagDC->containsDecl(TD))
9287 continue;
9288 TagDC->removeDecl(TD);
9289 TD->setDeclContext(NewFD);
9290 NewFD->addDecl(TD);
9291
9292 // Preserve the lexical DeclContext if it is not the surrounding tag
9293 // injection context of the FD. In this example, the semantic context of
9294 // E will be f and the lexical context will be S, while both the
9295 // semantic and lexical contexts of S will be f:
9296 // void f(struct S { enum E { a } f; } s);
9297 if (TagDC != PrototypeTagContext)
9298 TD->setLexicalDeclContext(TagDC);
9299 }
9300 }
9301 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9302 // When we're declaring a function with a typedef, typeof, etc as in the
9303 // following example, we'll need to synthesize (unnamed)
9304 // parameters for use in the declaration.
9305 //
9306 // @code
9307 // typedef void fn(int);
9308 // fn f;
9309 // @endcode
9310
9311 // Synthesize a parameter for each argument type.
9312 for (const auto &AI : FT->param_types()) {
9313 ParmVarDecl *Param =
9314 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9315 Param->setScopeInfo(0, Params.size());
9316 Params.push_back(Param);
9317 }
9318 } else {
9319 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams
() == 0 && "Should not need args for typedef of non-prototype fn"
) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9320, __PRETTY_FUNCTION__))
9320 "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams
() == 0 && "Should not need args for typedef of non-prototype fn"
) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9320, __PRETTY_FUNCTION__))
;
9321 }
9322
9323 // Finally, we know we have the right number of parameters, install them.
9324 NewFD->setParams(Params);
9325
9326 if (D.getDeclSpec().isNoreturnSpecified())
9327 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9328 D.getDeclSpec().getNoreturnSpecLoc(),
9329 AttributeCommonInfo::AS_Keyword));
9330
9331 // Functions returning a variably modified type violate C99 6.7.5.2p2
9332 // because all functions have linkage.
9333 if (!NewFD->isInvalidDecl() &&
9334 NewFD->getReturnType()->isVariablyModifiedType()) {
9335 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9336 NewFD->setInvalidDecl();
9337 }
9338
9339 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9340 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9341 !NewFD->hasAttr<SectionAttr>())
9342 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9343 Context, PragmaClangTextSection.SectionName,
9344 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9345
9346 // Apply an implicit SectionAttr if #pragma code_seg is active.
9347 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9348 !NewFD->hasAttr<SectionAttr>()) {
9349 NewFD->addAttr(SectionAttr::CreateImplicit(
9350 Context, CodeSegStack.CurrentValue->getString(),
9351 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9352 SectionAttr::Declspec_allocate));
9353 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9354 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9355 ASTContext::PSF_Read,
9356 NewFD))
9357 NewFD->dropAttr<SectionAttr>();
9358 }
9359
9360 // Apply an implicit CodeSegAttr from class declspec or
9361 // apply an implicit SectionAttr from #pragma code_seg if active.
9362 if (!NewFD->hasAttr<CodeSegAttr>()) {
9363 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9364 D.isFunctionDefinition())) {
9365 NewFD->addAttr(SAttr);
9366 }
9367 }
9368
9369 // Handle attributes.
9370 ProcessDeclAttributes(S, NewFD, D);
9371
9372 if (getLangOpts().OpenCL) {
9373 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9374 // type declaration will generate a compilation error.
9375 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9376 if (AddressSpace != LangAS::Default) {
9377 Diag(NewFD->getLocation(),
9378 diag::err_opencl_return_value_with_address_space);
9379 NewFD->setInvalidDecl();
9380 }
9381 }
9382
9383 if (!getLangOpts().CPlusPlus) {
9384 // Perform semantic checking on the function declaration.
9385 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9386 CheckMain(NewFD, D.getDeclSpec());
9387
9388 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9389 CheckMSVCRTEntryPoint(NewFD);
9390
9391 if (!NewFD->isInvalidDecl())
9392 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9393 isMemberSpecialization));
9394 else if (!Previous.empty())
9395 // Recover gracefully from an invalid redeclaration.
9396 D.setRedeclaration(true);
9397 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9399, __PRETTY_FUNCTION__))
9398 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9399, __PRETTY_FUNCTION__))
9399 "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9399, __PRETTY_FUNCTION__))
;
9400
9401 // Diagnose no-prototype function declarations with calling conventions that
9402 // don't support variadic calls. Only do this in C and do it after merging
9403 // possibly prototyped redeclarations.
9404 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9405 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9406 CallingConv CC = FT->getExtInfo().getCC();
9407 if (!supportsVariadicCall(CC)) {
9408 // Windows system headers sometimes accidentally use stdcall without
9409 // (void) parameters, so we relax this to a warning.
9410 int DiagID =
9411 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9412 Diag(NewFD->getLocation(), DiagID)
9413 << FunctionType::getNameForCallConv(CC);
9414 }
9415 }
9416
9417 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9418 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9419 checkNonTrivialCUnion(NewFD->getReturnType(),
9420 NewFD->getReturnTypeSourceRange().getBegin(),
9421 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9422 } else {
9423 // C++11 [replacement.functions]p3:
9424 // The program's definitions shall not be specified as inline.
9425 //
9426 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9427 //
9428 // Suppress the diagnostic if the function is __attribute__((used)), since
9429 // that forces an external definition to be emitted.
9430 if (D.getDeclSpec().isInlineSpecified() &&
9431 NewFD->isReplaceableGlobalAllocationFunction() &&
9432 !NewFD->hasAttr<UsedAttr>())
9433 Diag(D.getDeclSpec().getInlineSpecLoc(),
9434 diag::ext_operator_new_delete_declared_inline)
9435 << NewFD->getDeclName();
9436
9437 // If the declarator is a template-id, translate the parser's template
9438 // argument list into our AST format.
9439 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9440 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9441 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9442 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9443 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9444 TemplateId->NumArgs);
9445 translateTemplateArguments(TemplateArgsPtr,
9446 TemplateArgs);
9447
9448 HasExplicitTemplateArgs = true;
9449
9450 if (NewFD->isInvalidDecl()) {
9451 HasExplicitTemplateArgs = false;
9452 } else if (FunctionTemplate) {
9453 // Function template with explicit template arguments.
9454 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9455 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9456
9457 HasExplicitTemplateArgs = false;
9458 } else {
9459 assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9461, __PRETTY_FUNCTION__))
9460 D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9461, __PRETTY_FUNCTION__))
9461 "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified
()) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9461, __PRETTY_FUNCTION__))
;
9462 // "friend void foo<>(int);" is an implicit specialization decl.
9463 isFunctionTemplateSpecialization = true;
9464 }
9465 } else if (isFriend && isFunctionTemplateSpecialization) {
9466 // This combination is only possible in a recovery case; the user
9467 // wrote something like:
9468 // template <> friend void foo(int);
9469 // which we're recovering from as if the user had written:
9470 // friend void foo<>(int);
9471 // Go ahead and fake up a template id.
9472 HasExplicitTemplateArgs = true;
9473 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9474 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9475 }
9476
9477 // We do not add HD attributes to specializations here because
9478 // they may have different constexpr-ness compared to their
9479 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9480 // may end up with different effective targets. Instead, a
9481 // specialization inherits its target attributes from its template
9482 // in the CheckFunctionTemplateSpecialization() call below.
9483 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9484 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9485
9486 // If it's a friend (and only if it's a friend), it's possible
9487 // that either the specialized function type or the specialized
9488 // template is dependent, and therefore matching will fail. In
9489 // this case, don't check the specialization yet.
9490 bool InstantiationDependent = false;
9491 if (isFunctionTemplateSpecialization && isFriend &&
9492 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9493 TemplateSpecializationType::anyDependentTemplateArguments(
9494 TemplateArgs,
9495 InstantiationDependent))) {
9496 assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args"
) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9497, __PRETTY_FUNCTION__))
9497 "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args"
) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9497, __PRETTY_FUNCTION__))
;
9498 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9499 Previous))
9500 NewFD->setInvalidDecl();
9501 } else if (isFunctionTemplateSpecialization) {
9502 if (CurContext->isDependentContext() && CurContext->isRecord()
9503 && !isFriend) {
9504 isDependentClassScopeExplicitSpecialization = true;
9505 } else if (!NewFD->isInvalidDecl() &&
9506 CheckFunctionTemplateSpecialization(
9507 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9508 Previous))
9509 NewFD->setInvalidDecl();
9510
9511 // C++ [dcl.stc]p1:
9512 // A storage-class-specifier shall not be specified in an explicit
9513 // specialization (14.7.3)
9514 FunctionTemplateSpecializationInfo *Info =
9515 NewFD->getTemplateSpecializationInfo();
9516 if (Info && SC != SC_None) {
9517 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9518 Diag(NewFD->getLocation(),
9519 diag::err_explicit_specialization_inconsistent_storage_class)
9520 << SC
9521 << FixItHint::CreateRemoval(
9522 D.getDeclSpec().getStorageClassSpecLoc());
9523
9524 else
9525 Diag(NewFD->getLocation(),
9526 diag::ext_explicit_specialization_storage_class)
9527 << FixItHint::CreateRemoval(
9528 D.getDeclSpec().getStorageClassSpecLoc());
9529 }
9530 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9531 if (CheckMemberSpecialization(NewFD, Previous))
9532 NewFD->setInvalidDecl();
9533 }
9534
9535 // Perform semantic checking on the function declaration.
9536 if (!isDependentClassScopeExplicitSpecialization) {
9537 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9538 CheckMain(NewFD, D.getDeclSpec());
9539
9540 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9541 CheckMSVCRTEntryPoint(NewFD);
9542
9543 if (!NewFD->isInvalidDecl())
9544 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9545 isMemberSpecialization));
9546 else if (!Previous.empty())
9547 // Recover gracefully from an invalid redeclaration.
9548 D.setRedeclaration(true);
9549 }
9550
9551 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9553, __PRETTY_FUNCTION__))
9552 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9553, __PRETTY_FUNCTION__))
9553 "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous
.getResultKind() != LookupResult::FoundOverloaded) &&
"previous declaration set still overloaded") ? static_cast<
void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9553, __PRETTY_FUNCTION__))
;
9554
9555 NamedDecl *PrincipalDecl = (FunctionTemplate
9556 ? cast<NamedDecl>(FunctionTemplate)
9557 : NewFD);
9558
9559 if (isFriend && NewFD->getPreviousDecl()) {
9560 AccessSpecifier Access = AS_public;
9561 if (!NewFD->isInvalidDecl())
9562 Access = NewFD->getPreviousDecl()->getAccess();
9563
9564 NewFD->setAccess(Access);
9565 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9566 }
9567
9568 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9569 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9570 PrincipalDecl->setNonMemberOperator();
9571
9572 // If we have a function template, check the template parameter
9573 // list. This will check and merge default template arguments.
9574 if (FunctionTemplate) {
9575 FunctionTemplateDecl *PrevTemplate =
9576 FunctionTemplate->getPreviousDecl();
9577 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9578 PrevTemplate ? PrevTemplate->getTemplateParameters()
9579 : nullptr,
9580 D.getDeclSpec().isFriendSpecified()
9581 ? (D.isFunctionDefinition()
9582 ? TPC_FriendFunctionTemplateDefinition
9583 : TPC_FriendFunctionTemplate)
9584 : (D.getCXXScopeSpec().isSet() &&
9585 DC && DC->isRecord() &&
9586 DC->isDependentContext())
9587 ? TPC_ClassTemplateMember
9588 : TPC_FunctionTemplate);
9589 }
9590
9591 if (NewFD->isInvalidDecl()) {
9592 // Ignore all the rest of this.
9593 } else if (!D.isRedeclaration()) {
9594 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9595 AddToScope };
9596 // Fake up an access specifier if it's supposed to be a class member.
9597 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9598 NewFD->setAccess(AS_public);
9599
9600 // Qualified decls generally require a previous declaration.
9601 if (D.getCXXScopeSpec().isSet()) {
9602 // ...with the major exception of templated-scope or
9603 // dependent-scope friend declarations.
9604
9605 // TODO: we currently also suppress this check in dependent
9606 // contexts because (1) the parameter depth will be off when
9607 // matching friend templates and (2) we might actually be
9608 // selecting a friend based on a dependent factor. But there
9609 // are situations where these conditions don't apply and we
9610 // can actually do this check immediately.
9611 //
9612 // Unless the scope is dependent, it's always an error if qualified
9613 // redeclaration lookup found nothing at all. Diagnose that now;
9614 // nothing will diagnose that error later.
9615 if (isFriend &&
9616 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9617 (!Previous.empty() && CurContext->isDependentContext()))) {
9618 // ignore these
9619 } else {
9620 // The user tried to provide an out-of-line definition for a
9621 // function that is a member of a class or namespace, but there
9622 // was no such member function declared (C++ [class.mfct]p2,
9623 // C++ [namespace.memdef]p2). For example:
9624 //
9625 // class X {
9626 // void f() const;
9627 // };
9628 //
9629 // void X::f() { } // ill-formed
9630 //
9631 // Complain about this problem, and attempt to suggest close
9632 // matches (e.g., those that differ only in cv-qualifiers and
9633 // whether the parameter types are references).
9634
9635 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9636 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9637 AddToScope = ExtraArgs.AddToScope;
9638 return Result;
9639 }
9640 }
9641
9642 // Unqualified local friend declarations are required to resolve
9643 // to something.
9644 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9645 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9646 *this, Previous, NewFD, ExtraArgs, true, S)) {
9647 AddToScope = ExtraArgs.AddToScope;
9648 return Result;
9649 }
9650 }
9651 } else if (!D.isFunctionDefinition() &&
9652 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9653 !isFriend && !isFunctionTemplateSpecialization &&
9654 !isMemberSpecialization) {
9655 // An out-of-line member function declaration must also be a
9656 // definition (C++ [class.mfct]p2).
9657 // Note that this is not the case for explicit specializations of
9658 // function templates or member functions of class templates, per
9659 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9660 // extension for compatibility with old SWIG code which likes to
9661 // generate them.
9662 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9663 << D.getCXXScopeSpec().getRange();
9664 }
9665 }
9666
9667 ProcessPragmaWeak(S, NewFD);
9668 checkAttributesAfterMerging(*this, *NewFD);
9669
9670 AddKnownFunctionAttributes(NewFD);
9671
9672 if (NewFD->hasAttr<OverloadableAttr>() &&
9673 !NewFD->getType()->getAs<FunctionProtoType>()) {
9674 Diag(NewFD->getLocation(),
9675 diag::err_attribute_overloadable_no_prototype)
9676 << NewFD;
9677
9678 // Turn this into a variadic function with no parameters.
9679 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9680 FunctionProtoType::ExtProtoInfo EPI(
9681 Context.getDefaultCallingConvention(true, false));
9682 EPI.Variadic = true;
9683 EPI.ExtInfo = FT->getExtInfo();
9684
9685 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9686 NewFD->setType(R);
9687 }
9688
9689 // If there's a #pragma GCC visibility in scope, and this isn't a class
9690 // member, set the visibility of this function.
9691 if (!DC->isRecord() && NewFD->isExternallyVisible())
9692 AddPushedVisibilityAttribute(NewFD);
9693
9694 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9695 // marking the function.
9696 AddCFAuditedAttribute(NewFD);
9697
9698 // If this is a function definition, check if we have to apply optnone due to
9699 // a pragma.
9700 if(D.isFunctionDefinition())
9701 AddRangeBasedOptnone(NewFD);
9702
9703 // If this is the first declaration of an extern C variable, update
9704 // the map of such variables.
9705 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9706 isIncompleteDeclExternC(*this, NewFD))
9707 RegisterLocallyScopedExternCDecl(NewFD, S);
9708
9709 // Set this FunctionDecl's range up to the right paren.
9710 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9711
9712 if (D.isRedeclaration() && !Previous.empty()) {
9713 NamedDecl *Prev = Previous.getRepresentativeDecl();
9714 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9715 isMemberSpecialization ||
9716 isFunctionTemplateSpecialization,
9717 D.isFunctionDefinition());
9718 }
9719
9720 if (getLangOpts().CUDA) {
9721 IdentifierInfo *II = NewFD->getIdentifier();
9722 if (II && II->isStr(getCudaConfigureFuncName()) &&
9723 !NewFD->isInvalidDecl() &&
9724 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9725 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9726 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9727 << getCudaConfigureFuncName();
9728 Context.setcudaConfigureCallDecl(NewFD);
9729 }
9730
9731 // Variadic functions, other than a *declaration* of printf, are not allowed
9732 // in device-side CUDA code, unless someone passed
9733 // -fcuda-allow-variadic-functions.
9734 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9735 (NewFD->hasAttr<CUDADeviceAttr>() ||
9736 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9737 !(II && II->isStr("printf") && NewFD->isExternC() &&
9738 !D.isFunctionDefinition())) {
9739 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9740 }
9741 }
9742
9743 MarkUnusedFileScopedDecl(NewFD);
9744
9745
9746
9747 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9748 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9749 if ((getLangOpts().OpenCLVersion >= 120)
9750 && (SC == SC_Static)) {
9751 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9752 D.setInvalidType();
9753 }
9754
9755 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9756 if (!NewFD->getReturnType()->isVoidType()) {
9757 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9758 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9759 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9760 : FixItHint());
9761 D.setInvalidType();
9762 }
9763
9764 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9765 for (auto Param : NewFD->parameters())
9766 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9767
9768 if (getLangOpts().OpenCLCPlusPlus) {
9769 if (DC->isRecord()) {
9770 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9771 D.setInvalidType();
9772 }
9773 if (FunctionTemplate) {
9774 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9775 D.setInvalidType();
9776 }
9777 }
9778 }
9779
9780 if (getLangOpts().CPlusPlus) {
9781 if (FunctionTemplate) {
9782 if (NewFD->isInvalidDecl())
9783 FunctionTemplate->setInvalidDecl();
9784 return FunctionTemplate;
9785 }
9786
9787 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9788 CompleteMemberSpecialization(NewFD, Previous);
9789 }
9790
9791 for (const ParmVarDecl *Param : NewFD->parameters()) {
9792 QualType PT = Param->getType();
9793
9794 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9795 // types.
9796 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9797 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9798 QualType ElemTy = PipeTy->getElementType();
9799 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9800 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9801 D.setInvalidType();
9802 }
9803 }
9804 }
9805 }
9806
9807 // Here we have an function template explicit specialization at class scope.
9808 // The actual specialization will be postponed to template instatiation
9809 // time via the ClassScopeFunctionSpecializationDecl node.
9810 if (isDependentClassScopeExplicitSpecialization) {
9811 ClassScopeFunctionSpecializationDecl *NewSpec =
9812 ClassScopeFunctionSpecializationDecl::Create(
9813 Context, CurContext, NewFD->getLocation(),
9814 cast<CXXMethodDecl>(NewFD),
9815 HasExplicitTemplateArgs, TemplateArgs);
9816 CurContext->addDecl(NewSpec);
9817 AddToScope = false;
9818 }
9819
9820 // Diagnose availability attributes. Availability cannot be used on functions
9821 // that are run during load/unload.
9822 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9823 if (NewFD->hasAttr<ConstructorAttr>()) {
9824 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9825 << 1;
9826 NewFD->dropAttr<AvailabilityAttr>();
9827 }
9828 if (NewFD->hasAttr<DestructorAttr>()) {
9829 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9830 << 2;
9831 NewFD->dropAttr<AvailabilityAttr>();
9832 }
9833 }
9834
9835 // Diagnose no_builtin attribute on function declaration that are not a
9836 // definition.
9837 // FIXME: We should really be doing this in
9838 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9839 // the FunctionDecl and at this point of the code
9840 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9841 // because Sema::ActOnStartOfFunctionDef has not been called yet.
9842 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9843 switch (D.getFunctionDefinitionKind()) {
9844 case FDK_Defaulted:
9845 case FDK_Deleted:
9846 Diag(NBA->getLocation(),
9847 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9848 << NBA->getSpelling();
9849 break;
9850 case FDK_Declaration:
9851 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9852 << NBA->getSpelling();
9853 break;
9854 case FDK_Definition:
9855 break;
9856 }
9857
9858 return NewFD;
9859}
9860
9861/// Return a CodeSegAttr from a containing class. The Microsoft docs say
9862/// when __declspec(code_seg) "is applied to a class, all member functions of
9863/// the class and nested classes -- this includes compiler-generated special
9864/// member functions -- are put in the specified segment."
9865/// The actual behavior is a little more complicated. The Microsoft compiler
9866/// won't check outer classes if there is an active value from #pragma code_seg.
9867/// The CodeSeg is always applied from the direct parent but only from outer
9868/// classes when the #pragma code_seg stack is empty. See:
9869/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9870/// available since MS has removed the page.
9871static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9872 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9873 if (!Method)
9874 return nullptr;
9875 const CXXRecordDecl *Parent = Method->getParent();
9876 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9877 Attr *NewAttr = SAttr->clone(S.getASTContext());
9878 NewAttr->setImplicit(true);
9879 return NewAttr;
9880 }
9881
9882 // The Microsoft compiler won't check outer classes for the CodeSeg
9883 // when the #pragma code_seg stack is active.
9884 if (S.CodeSegStack.CurrentValue)
9885 return nullptr;
9886
9887 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9888 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9889 Attr *NewAttr = SAttr->clone(S.getASTContext());
9890 NewAttr->setImplicit(true);
9891 return NewAttr;
9892 }
9893 }
9894 return nullptr;
9895}
9896
9897/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9898/// containing class. Otherwise it will return implicit SectionAttr if the
9899/// function is a definition and there is an active value on CodeSegStack
9900/// (from the current #pragma code-seg value).
9901///
9902/// \param FD Function being declared.
9903/// \param IsDefinition Whether it is a definition or just a declarartion.
9904/// \returns A CodeSegAttr or SectionAttr to apply to the function or
9905/// nullptr if no attribute should be added.
9906Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9907 bool IsDefinition) {
9908 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9909 return A;
9910 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9911 CodeSegStack.CurrentValue)
9912 return SectionAttr::CreateImplicit(
9913 getASTContext(), CodeSegStack.CurrentValue->getString(),
9914 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9915 SectionAttr::Declspec_allocate);
9916 return nullptr;
9917}
9918
9919/// Determines if we can perform a correct type check for \p D as a
9920/// redeclaration of \p PrevDecl. If not, we can generally still perform a
9921/// best-effort check.
9922///
9923/// \param NewD The new declaration.
9924/// \param OldD The old declaration.
9925/// \param NewT The portion of the type of the new declaration to check.
9926/// \param OldT The portion of the type of the old declaration to check.
9927bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9928 QualType NewT, QualType OldT) {
9929 if (!NewD->getLexicalDeclContext()->isDependentContext())
60
Assuming the condition is false
61
Taking false branch
9930 return true;
9931
9932 // For dependently-typed local extern declarations and friends, we can't
9933 // perform a correct type check in general until instantiation:
9934 //
9935 // int f();
9936 // template<typename T> void g() { T f(); }
9937 //
9938 // (valid if g() is only instantiated with T = int).
9939 if (NewT->isDependentType() &&
62
Assuming the condition is false
9940 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9941 return false;
9942
9943 // Similarly, if the previous declaration was a dependent local extern
9944 // declaration, we don't really know its type yet.
9945 if (OldT->isDependentType() && OldD->isLocalExternDecl())
63
Assuming the condition is false
9946 return false;
9947
9948 return true;
64
Returning the value 1, which participates in a condition later
9949}
9950
9951/// Checks if the new declaration declared in dependent context must be
9952/// put in the same redeclaration chain as the specified declaration.
9953///
9954/// \param D Declaration that is checked.
9955/// \param PrevDecl Previous declaration found with proper lookup method for the
9956/// same declaration name.
9957/// \returns True if D must be added to the redeclaration chain which PrevDecl
9958/// belongs to.
9959///
9960bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9961 if (!D->getLexicalDeclContext()->isDependentContext())
9962 return true;
9963
9964 // Don't chain dependent friend function definitions until instantiation, to
9965 // permit cases like
9966 //
9967 // void func();
9968 // template<typename T> class C1 { friend void func() {} };
9969 // template<typename T> class C2 { friend void func() {} };
9970 //
9971 // ... which is valid if only one of C1 and C2 is ever instantiated.
9972 //
9973 // FIXME: This need only apply to function definitions. For now, we proxy
9974 // this by checking for a file-scope function. We do not want this to apply
9975 // to friend declarations nominating member functions, because that gets in
9976 // the way of access checks.
9977 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9978 return false;
9979
9980 auto *VD = dyn_cast<ValueDecl>(D);
9981 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9982 return !VD || !PrevVD ||
9983 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9984 PrevVD->getType());
9985}
9986
9987/// Check the target attribute of the function for MultiVersion
9988/// validity.
9989///
9990/// Returns true if there was an error, false otherwise.
9991static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9992 const auto *TA = FD->getAttr<TargetAttr>();
9993 assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute"
) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 9993, __PRETTY_FUNCTION__))
;
9994 ParsedTargetAttr ParseInfo = TA->parse();
9995 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9996 enum ErrType { Feature = 0, Architecture = 1 };
9997
9998 if (!ParseInfo.Architecture.empty() &&
9999 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10000 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10001 << Architecture << ParseInfo.Architecture;
10002 return true;
10003 }
10004
10005 for (const auto &Feat : ParseInfo.Features) {
10006 auto BareFeat = StringRef{Feat}.substr(1);
10007 if (Feat[0] == '-') {
10008 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10009 << Feature << ("no-" + BareFeat).str();
10010 return true;
10011 }
10012
10013 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10014 !TargetInfo.isValidFeatureName(BareFeat)) {
10015 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10016 << Feature << BareFeat;
10017 return true;
10018 }
10019 }
10020 return false;
10021}
10022
10023// Provide a white-list of attributes that are allowed to be combined with
10024// multiversion functions.
10025static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10026 MultiVersionKind MVType) {
10027 // Note: this list/diagnosis must match the list in
10028 // checkMultiversionAttributesAllSame.
10029 switch (Kind) {
10030 default:
10031 return false;
10032 case attr::Used:
10033 return MVType == MultiVersionKind::Target;
10034 case attr::NonNull:
10035 case attr::NoThrow:
10036 return true;
10037 }
10038}
10039
10040static bool checkNonMultiVersionCompatAttributes(Sema &S,
10041 const FunctionDecl *FD,
10042 const FunctionDecl *CausedFD,
10043 MultiVersionKind MVType) {
10044 bool IsCPUSpecificCPUDispatchMVType =
10045 MVType == MultiVersionKind::CPUDispatch ||
10046 MVType == MultiVersionKind::CPUSpecific;
10047 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10048 Sema &S, const Attr *A) {
10049 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10050 << IsCPUSpecificCPUDispatchMVType << A;
10051 if (CausedFD)
10052 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10053 return true;
10054 };
10055
10056 for (const Attr *A : FD->attrs()) {
10057 switch (A->getKind()) {
10058 case attr::CPUDispatch:
10059 case attr::CPUSpecific:
10060 if (MVType != MultiVersionKind::CPUDispatch &&
10061 MVType != MultiVersionKind::CPUSpecific)
10062 return Diagnose(S, A);
10063 break;
10064 case attr::Target:
10065 if (MVType != MultiVersionKind::Target)
10066 return Diagnose(S, A);
10067 break;
10068 default:
10069 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10070 return Diagnose(S, A);
10071 break;
10072 }
10073 }
10074 return false;
10075}
10076
10077bool Sema::areMultiversionVariantFunctionsCompatible(
10078 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10079 const PartialDiagnostic &NoProtoDiagID,
10080 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10081 const PartialDiagnosticAt &NoSupportDiagIDAt,
10082 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10083 bool ConstexprSupported, bool CLinkageMayDiffer) {
10084 enum DoesntSupport {
10085 FuncTemplates = 0,
10086 VirtFuncs = 1,
10087 DeducedReturn = 2,
10088 Constructors = 3,
10089 Destructors = 4,
10090 DeletedFuncs = 5,
10091 DefaultedFuncs = 6,
10092 ConstexprFuncs = 7,
10093 ConstevalFuncs = 8,
10094 };
10095 enum Different {
10096 CallingConv = 0,
10097 ReturnType = 1,
10098 ConstexprSpec = 2,
10099 InlineSpec = 3,
10100 StorageClass = 4,
10101 Linkage = 5,
10102 };
10103
10104 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10105 !OldFD->getType()->getAs<FunctionProtoType>()) {
10106 Diag(OldFD->getLocation(), NoProtoDiagID);
10107 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10108 return true;
10109 }
10110
10111 if (NoProtoDiagID.getDiagID() != 0 &&
10112 !NewFD->getType()->getAs<FunctionProtoType>())
10113 return Diag(NewFD->getLocation(), NoProtoDiagID);
10114
10115 if (!TemplatesSupported &&
10116 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10117 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10118 << FuncTemplates;
10119
10120 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10121 if (NewCXXFD->isVirtual())
10122 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10123 << VirtFuncs;
10124
10125 if (isa<CXXConstructorDecl>(NewCXXFD))
10126 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10127 << Constructors;
10128
10129 if (isa<CXXDestructorDecl>(NewCXXFD))
10130 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10131 << Destructors;
10132 }
10133
10134 if (NewFD->isDeleted())
10135 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10136 << DeletedFuncs;
10137
10138 if (NewFD->isDefaulted())
10139 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10140 << DefaultedFuncs;
10141
10142 if (!ConstexprSupported && NewFD->isConstexpr())
10143 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10144 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10145
10146 QualType NewQType = Context.getCanonicalType(NewFD->getType());
10147 const auto *NewType = cast<FunctionType>(NewQType);
10148 QualType NewReturnType = NewType->getReturnType();
10149
10150 if (NewReturnType->isUndeducedType())
10151 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10152 << DeducedReturn;
10153
10154 // Ensure the return type is identical.
10155 if (OldFD) {
10156 QualType OldQType = Context.getCanonicalType(OldFD->getType());
10157 const auto *OldType = cast<FunctionType>(OldQType);
10158 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10159 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10160
10161 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10162 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10163
10164 QualType OldReturnType = OldType->getReturnType();
10165
10166 if (OldReturnType != NewReturnType)
10167 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10168
10169 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10170 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10171
10172 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10173 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10174
10175 if (OldFD->getStorageClass() != NewFD->getStorageClass())
10176 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10177
10178 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10179 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10180
10181 if (CheckEquivalentExceptionSpec(
10182 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10183 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10184 return true;
10185 }
10186 return false;
10187}
10188
10189static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10190 const FunctionDecl *NewFD,
10191 bool CausesMV,
10192 MultiVersionKind MVType) {
10193 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10194 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10195 if (OldFD)
10196 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10197 return true;
10198 }
10199
10200 bool IsCPUSpecificCPUDispatchMVType =
10201 MVType == MultiVersionKind::CPUDispatch ||
10202 MVType == MultiVersionKind::CPUSpecific;
10203
10204 if (CausesMV && OldFD &&
10205 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10206 return true;
10207
10208 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10209 return true;
10210
10211 // Only allow transition to MultiVersion if it hasn't been used.
10212 if (OldFD && CausesMV && OldFD->isUsed(false))
10213 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10214
10215 return S.areMultiversionVariantFunctionsCompatible(
10216 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10217 PartialDiagnosticAt(NewFD->getLocation(),
10218 S.PDiag(diag::note_multiversioning_caused_here)),
10219 PartialDiagnosticAt(NewFD->getLocation(),
10220 S.PDiag(diag::err_multiversion_doesnt_support)
10221 << IsCPUSpecificCPUDispatchMVType),
10222 PartialDiagnosticAt(NewFD->getLocation(),
10223 S.PDiag(diag::err_multiversion_diff)),
10224 /*TemplatesSupported=*/false,
10225 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10226 /*CLinkageMayDiffer=*/false);
10227}
10228
10229/// Check the validity of a multiversion function declaration that is the
10230/// first of its kind. Also sets the multiversion'ness' of the function itself.
10231///
10232/// This sets NewFD->isInvalidDecl() to true if there was an error.
10233///
10234/// Returns true if there was an error, false otherwise.
10235static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10236 MultiVersionKind MVType,
10237 const TargetAttr *TA) {
10238 assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute"
) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10239, __PRETTY_FUNCTION__))
10239 "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute"
) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10239, __PRETTY_FUNCTION__))
;
10240
10241 // Target only causes MV if it is default, otherwise this is a normal
10242 // function.
10243 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10244 return false;
10245
10246 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10247 FD->setInvalidDecl();
10248 return true;
10249 }
10250
10251 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10252 FD->setInvalidDecl();
10253 return true;
10254 }
10255
10256 FD->setIsMultiVersion();
10257 return false;
10258}
10259
10260static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10261 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10262 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10263 return true;
10264 }
10265
10266 return false;
10267}
10268
10269static bool CheckTargetCausesMultiVersioning(
10270 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10271 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10272 LookupResult &Previous) {
10273 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10274 ParsedTargetAttr NewParsed = NewTA->parse();
10275 // Sort order doesn't matter, it just needs to be consistent.
10276 llvm::sort(NewParsed.Features);
10277
10278 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10279 // to change, this is a simple redeclaration.
10280 if (!NewTA->isDefaultVersion() &&
10281 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10282 return false;
10283
10284 // Otherwise, this decl causes MultiVersioning.
10285 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10286 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10287 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10288 NewFD->setInvalidDecl();
10289 return true;
10290 }
10291
10292 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10293 MultiVersionKind::Target)) {
10294 NewFD->setInvalidDecl();
10295 return true;
10296 }
10297
10298 if (CheckMultiVersionValue(S, NewFD)) {
10299 NewFD->setInvalidDecl();
10300 return true;
10301 }
10302
10303 // If this is 'default', permit the forward declaration.
10304 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10305 Redeclaration = true;
10306 OldDecl = OldFD;
10307 OldFD->setIsMultiVersion();
10308 NewFD->setIsMultiVersion();
10309 return false;
10310 }
10311
10312 if (CheckMultiVersionValue(S, OldFD)) {
10313 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10314 NewFD->setInvalidDecl();
10315 return true;
10316 }
10317
10318 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10319
10320 if (OldParsed == NewParsed) {
10321 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10322 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10323 NewFD->setInvalidDecl();
10324 return true;
10325 }
10326
10327 for (const auto *FD : OldFD->redecls()) {
10328 const auto *CurTA = FD->getAttr<TargetAttr>();
10329 // We allow forward declarations before ANY multiversioning attributes, but
10330 // nothing after the fact.
10331 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10332 (!CurTA || CurTA->isInherited())) {
10333 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10334 << 0;
10335 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10336 NewFD->setInvalidDecl();
10337 return true;
10338 }
10339 }
10340
10341 OldFD->setIsMultiVersion();
10342 NewFD->setIsMultiVersion();
10343 Redeclaration = false;
10344 MergeTypeWithPrevious = false;
10345 OldDecl = nullptr;
10346 Previous.clear();
10347 return false;
10348}
10349
10350/// Check the validity of a new function declaration being added to an existing
10351/// multiversioned declaration collection.
10352static bool CheckMultiVersionAdditionalDecl(
10353 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10354 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10355 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10356 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10357 LookupResult &Previous) {
10358
10359 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10360 // Disallow mixing of multiversioning types.
10361 if ((OldMVType == MultiVersionKind::Target &&
10362 NewMVType != MultiVersionKind::Target) ||
10363 (NewMVType == MultiVersionKind::Target &&
10364 OldMVType != MultiVersionKind::Target)) {
10365 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10366 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10367 NewFD->setInvalidDecl();
10368 return true;
10369 }
10370
10371 ParsedTargetAttr NewParsed;
10372 if (NewTA) {
10373 NewParsed = NewTA->parse();
10374 llvm::sort(NewParsed.Features);
10375 }
10376
10377 bool UseMemberUsingDeclRules =
10378 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10379
10380 // Next, check ALL non-overloads to see if this is a redeclaration of a
10381 // previous member of the MultiVersion set.
10382 for (NamedDecl *ND : Previous) {
10383 FunctionDecl *CurFD = ND->getAsFunction();
10384 if (!CurFD)
10385 continue;
10386 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10387 continue;
10388
10389 if (NewMVType == MultiVersionKind::Target) {
10390 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10391 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10392 NewFD->setIsMultiVersion();
10393 Redeclaration = true;
10394 OldDecl = ND;
10395 return false;
10396 }
10397
10398 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10399 if (CurParsed == NewParsed) {
10400 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10401 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10402 NewFD->setInvalidDecl();
10403 return true;
10404 }
10405 } else {
10406 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10407 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10408 // Handle CPUDispatch/CPUSpecific versions.
10409 // Only 1 CPUDispatch function is allowed, this will make it go through
10410 // the redeclaration errors.
10411 if (NewMVType == MultiVersionKind::CPUDispatch &&
10412 CurFD->hasAttr<CPUDispatchAttr>()) {
10413 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10414 std::equal(
10415 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10416 NewCPUDisp->cpus_begin(),
10417 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10418 return Cur->getName() == New->getName();
10419 })) {
10420 NewFD->setIsMultiVersion();
10421 Redeclaration = true;
10422 OldDecl = ND;
10423 return false;
10424 }
10425
10426 // If the declarations don't match, this is an error condition.
10427 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10428 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10429 NewFD->setInvalidDecl();
10430 return true;
10431 }
10432 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10433
10434 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10435 std::equal(
10436 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10437 NewCPUSpec->cpus_begin(),
10438 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10439 return Cur->getName() == New->getName();
10440 })) {
10441 NewFD->setIsMultiVersion();
10442 Redeclaration = true;
10443 OldDecl = ND;
10444 return false;
10445 }
10446
10447 // Only 1 version of CPUSpecific is allowed for each CPU.
10448 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10449 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10450 if (CurII == NewII) {
10451 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10452 << NewII;
10453 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10454 NewFD->setInvalidDecl();
10455 return true;
10456 }
10457 }
10458 }
10459 }
10460 // If the two decls aren't the same MVType, there is no possible error
10461 // condition.
10462 }
10463 }
10464
10465 // Else, this is simply a non-redecl case. Checking the 'value' is only
10466 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10467 // handled in the attribute adding step.
10468 if (NewMVType == MultiVersionKind::Target &&
10469 CheckMultiVersionValue(S, NewFD)) {
10470 NewFD->setInvalidDecl();
10471 return true;
10472 }
10473
10474 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10475 !OldFD->isMultiVersion(), NewMVType)) {
10476 NewFD->setInvalidDecl();
10477 return true;
10478 }
10479
10480 // Permit forward declarations in the case where these two are compatible.
10481 if (!OldFD->isMultiVersion()) {
10482 OldFD->setIsMultiVersion();
10483 NewFD->setIsMultiVersion();
10484 Redeclaration = true;
10485 OldDecl = OldFD;
10486 return false;
10487 }
10488
10489 NewFD->setIsMultiVersion();
10490 Redeclaration = false;
10491 MergeTypeWithPrevious = false;
10492 OldDecl = nullptr;
10493 Previous.clear();
10494 return false;
10495}
10496
10497
10498/// Check the validity of a mulitversion function declaration.
10499/// Also sets the multiversion'ness' of the function itself.
10500///
10501/// This sets NewFD->isInvalidDecl() to true if there was an error.
10502///
10503/// Returns true if there was an error, false otherwise.
10504static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10505 bool &Redeclaration, NamedDecl *&OldDecl,
10506 bool &MergeTypeWithPrevious,
10507 LookupResult &Previous) {
10508 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10509 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10510 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10511
10512 // Mixing Multiversioning types is prohibited.
10513 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10514 (NewCPUDisp && NewCPUSpec)) {
10515 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10516 NewFD->setInvalidDecl();
10517 return true;
10518 }
10519
10520 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10521
10522 // Main isn't allowed to become a multiversion function, however it IS
10523 // permitted to have 'main' be marked with the 'target' optimization hint.
10524 if (NewFD->isMain()) {
10525 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10526 MVType == MultiVersionKind::CPUDispatch ||
10527 MVType == MultiVersionKind::CPUSpecific) {
10528 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10529 NewFD->setInvalidDecl();
10530 return true;
10531 }
10532 return false;
10533 }
10534
10535 if (!OldDecl || !OldDecl->getAsFunction() ||
10536 OldDecl->getDeclContext()->getRedeclContext() !=
10537 NewFD->getDeclContext()->getRedeclContext()) {
10538 // If there's no previous declaration, AND this isn't attempting to cause
10539 // multiversioning, this isn't an error condition.
10540 if (MVType == MultiVersionKind::None)
10541 return false;
10542 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10543 }
10544
10545 FunctionDecl *OldFD = OldDecl->getAsFunction();
10546
10547 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10548 return false;
10549
10550 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10551 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10552 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10553 NewFD->setInvalidDecl();
10554 return true;
10555 }
10556
10557 // Handle the target potentially causes multiversioning case.
10558 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10559 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10560 Redeclaration, OldDecl,
10561 MergeTypeWithPrevious, Previous);
10562
10563 // At this point, we have a multiversion function decl (in OldFD) AND an
10564 // appropriate attribute in the current function decl. Resolve that these are
10565 // still compatible with previous declarations.
10566 return CheckMultiVersionAdditionalDecl(
10567 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10568 OldDecl, MergeTypeWithPrevious, Previous);
10569}
10570
10571/// Perform semantic checking of a new function declaration.
10572///
10573/// Performs semantic analysis of the new function declaration
10574/// NewFD. This routine performs all semantic checking that does not
10575/// require the actual declarator involved in the declaration, and is
10576/// used both for the declaration of functions as they are parsed
10577/// (called via ActOnDeclarator) and for the declaration of functions
10578/// that have been instantiated via C++ template instantiation (called
10579/// via InstantiateDecl).
10580///
10581/// \param IsMemberSpecialization whether this new function declaration is
10582/// a member specialization (that replaces any definition provided by the
10583/// previous declaration).
10584///
10585/// This sets NewFD->isInvalidDecl() to true if there was an error.
10586///
10587/// \returns true if the function declaration is a redeclaration.
10588bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10589 LookupResult &Previous,
10590 bool IsMemberSpecialization) {
10591 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here") ? static_cast
<void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10592, __PRETTY_FUNCTION__))
10592 "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() &&
"Variably modified return types are not handled here") ? static_cast
<void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10592, __PRETTY_FUNCTION__))
;
10593
10594 // Determine whether the type of this function should be merged with
10595 // a previous visible declaration. This never happens for functions in C++,
10596 // and always happens in C if the previous declaration was visible.
10597 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10598 !Previous.isShadowed();
10599
10600 bool Redeclaration = false;
10601 NamedDecl *OldDecl = nullptr;
10602 bool MayNeedOverloadableChecks = false;
10603
10604 // Merge or overload the declaration with an existing declaration of
10605 // the same name, if appropriate.
10606 if (!Previous.empty()) {
10607 // Determine whether NewFD is an overload of PrevDecl or
10608 // a declaration that requires merging. If it's an overload,
10609 // there's no more work to do here; we'll just add the new
10610 // function to the scope.
10611 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10612 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10613 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10614 Redeclaration = true;
10615 OldDecl = Candidate;
10616 }
10617 } else {
10618 MayNeedOverloadableChecks = true;
10619 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10620 /*NewIsUsingDecl*/ false)) {
10621 case Ovl_Match:
10622 Redeclaration = true;
10623 break;
10624
10625 case Ovl_NonFunction:
10626 Redeclaration = true;
10627 break;
10628
10629 case Ovl_Overload:
10630 Redeclaration = false;
10631 break;
10632 }
10633 }
10634 }
10635
10636 // Check for a previous extern "C" declaration with this name.
10637 if (!Redeclaration &&
10638 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10639 if (!Previous.empty()) {
10640 // This is an extern "C" declaration with the same name as a previous
10641 // declaration, and thus redeclares that entity...
10642 Redeclaration = true;
10643 OldDecl = Previous.getFoundDecl();
10644 MergeTypeWithPrevious = false;
10645
10646 // ... except in the presence of __attribute__((overloadable)).
10647 if (OldDecl->hasAttr<OverloadableAttr>() ||
10648 NewFD->hasAttr<OverloadableAttr>()) {
10649 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10650 MayNeedOverloadableChecks = true;
10651 Redeclaration = false;
10652 OldDecl = nullptr;
10653 }
10654 }
10655 }
10656 }
10657
10658 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10659 MergeTypeWithPrevious, Previous))
10660 return Redeclaration;
10661
10662 // C++11 [dcl.constexpr]p8:
10663 // A constexpr specifier for a non-static member function that is not
10664 // a constructor declares that member function to be const.
10665 //
10666 // This needs to be delayed until we know whether this is an out-of-line
10667 // definition of a static member function.
10668 //
10669 // This rule is not present in C++1y, so we produce a backwards
10670 // compatibility warning whenever it happens in C++11.
10671 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10672 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10673 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10674 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10675 CXXMethodDecl *OldMD = nullptr;
10676 if (OldDecl)
10677 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10678 if (!OldMD || !OldMD->isStatic()) {
10679 const FunctionProtoType *FPT =
10680 MD->getType()->castAs<FunctionProtoType>();
10681 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10682 EPI.TypeQuals.addConst();
10683 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10684 FPT->getParamTypes(), EPI));
10685
10686 // Warn that we did this, if we're not performing template instantiation.
10687 // In that case, we'll have warned already when the template was defined.
10688 if (!inTemplateInstantiation()) {
10689 SourceLocation AddConstLoc;
10690 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10691 .IgnoreParens().getAs<FunctionTypeLoc>())
10692 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10693
10694 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10695 << FixItHint::CreateInsertion(AddConstLoc, " const");
10696 }
10697 }
10698 }
10699
10700 if (Redeclaration) {
10701 // NewFD and OldDecl represent declarations that need to be
10702 // merged.
10703 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10704 NewFD->setInvalidDecl();
10705 return Redeclaration;
10706 }
10707
10708 Previous.clear();
10709 Previous.addDecl(OldDecl);
10710
10711 if (FunctionTemplateDecl *OldTemplateDecl =
10712 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10713 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10714 FunctionTemplateDecl *NewTemplateDecl
10715 = NewFD->getDescribedFunctionTemplate();
10716 assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch"
) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10716, __PRETTY_FUNCTION__))
;
10717
10718 // The call to MergeFunctionDecl above may have created some state in
10719 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10720 // can add it as a redeclaration.
10721 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10722
10723 NewFD->setPreviousDeclaration(OldFD);
10724 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10725 if (NewFD->isCXXClassMember()) {
10726 NewFD->setAccess(OldTemplateDecl->getAccess());
10727 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10728 }
10729
10730 // If this is an explicit specialization of a member that is a function
10731 // template, mark it as a member specialization.
10732 if (IsMemberSpecialization &&
10733 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10734 NewTemplateDecl->setMemberSpecialization();
10735 assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast
<void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10735, __PRETTY_FUNCTION__))
;
10736 // Explicit specializations of a member template do not inherit deleted
10737 // status from the parent member template that they are specializing.
10738 if (OldFD->isDeleted()) {
10739 // FIXME: This assert will not hold in the presence of modules.
10740 assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void
> (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10740, __PRETTY_FUNCTION__))
;
10741 // FIXME: We need an update record for this AST mutation.
10742 OldFD->setDeletedAsWritten(false);
10743 }
10744 }
10745
10746 } else {
10747 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10748 auto *OldFD = cast<FunctionDecl>(OldDecl);
10749 // This needs to happen first so that 'inline' propagates.
10750 NewFD->setPreviousDeclaration(OldFD);
10751 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10752 if (NewFD->isCXXClassMember())
10753 NewFD->setAccess(OldFD->getAccess());
10754 }
10755 }
10756 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10757 !NewFD->getAttr<OverloadableAttr>()) {
10758 assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10763, __PRETTY_FUNCTION__))
10759 llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10763, __PRETTY_FUNCTION__))
10760 [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10763, __PRETTY_FUNCTION__))
10761 return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10763, __PRETTY_FUNCTION__))
10762 })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10763, __PRETTY_FUNCTION__))
10763 "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl
*ND) { return ND->hasAttr<OverloadableAttr>(); })) &&
"Non-redecls shouldn't happen without overloadable present")
? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10763, __PRETTY_FUNCTION__))
;
10764
10765 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10766 const auto *FD = dyn_cast<FunctionDecl>(ND);
10767 return FD && !FD->hasAttr<OverloadableAttr>();
10768 });
10769
10770 if (OtherUnmarkedIter != Previous.end()) {
10771 Diag(NewFD->getLocation(),
10772 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10773 Diag((*OtherUnmarkedIter)->getLocation(),
10774 diag::note_attribute_overloadable_prev_overload)
10775 << false;
10776
10777 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10778 }
10779 }
10780
10781 // Semantic checking for this function declaration (in isolation).
10782
10783 if (getLangOpts().CPlusPlus) {
10784 // C++-specific checks.
10785 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10786 CheckConstructor(Constructor);
10787 } else if (CXXDestructorDecl *Destructor =
10788 dyn_cast<CXXDestructorDecl>(NewFD)) {
10789 CXXRecordDecl *Record = Destructor->getParent();
10790 QualType ClassType = Context.getTypeDeclType(Record);
10791
10792 // FIXME: Shouldn't we be able to perform this check even when the class
10793 // type is dependent? Both gcc and edg can handle that.
10794 if (!ClassType->isDependentType()) {
10795 DeclarationName Name
10796 = Context.DeclarationNames.getCXXDestructorName(
10797 Context.getCanonicalType(ClassType));
10798 if (NewFD->getDeclName() != Name) {
10799 Diag(NewFD->getLocation(), diag::err_destructor_name);
10800 NewFD->setInvalidDecl();
10801 return Redeclaration;
10802 }
10803 }
10804 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10805 if (auto *TD = Guide->getDescribedFunctionTemplate())
10806 CheckDeductionGuideTemplate(TD);
10807
10808 // A deduction guide is not on the list of entities that can be
10809 // explicitly specialized.
10810 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10811 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10812 << /*explicit specialization*/ 1;
10813 }
10814
10815 // Find any virtual functions that this function overrides.
10816 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10817 if (!Method->isFunctionTemplateSpecialization() &&
10818 !Method->getDescribedFunctionTemplate() &&
10819 Method->isCanonicalDecl()) {
10820 AddOverriddenMethods(Method->getParent(), Method);
10821 }
10822 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10823 // C++2a [class.virtual]p6
10824 // A virtual method shall not have a requires-clause.
10825 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10826 diag::err_constrained_virtual_method);
10827
10828 if (Method->isStatic())
10829 checkThisInStaticMemberFunctionType(Method);
10830 }
10831
10832 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10833 ActOnConversionDeclarator(Conversion);
10834
10835 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10836 if (NewFD->isOverloadedOperator() &&
10837 CheckOverloadedOperatorDeclaration(NewFD)) {
10838 NewFD->setInvalidDecl();
10839 return Redeclaration;
10840 }
10841
10842 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10843 if (NewFD->getLiteralIdentifier() &&
10844 CheckLiteralOperatorDeclaration(NewFD)) {
10845 NewFD->setInvalidDecl();
10846 return Redeclaration;
10847 }
10848
10849 // In C++, check default arguments now that we have merged decls. Unless
10850 // the lexical context is the class, because in this case this is done
10851 // during delayed parsing anyway.
10852 if (!CurContext->isRecord())
10853 CheckCXXDefaultArguments(NewFD);
10854
10855 // If this function declares a builtin function, check the type of this
10856 // declaration against the expected type for the builtin.
10857 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10858 ASTContext::GetBuiltinTypeError Error;
10859 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
10860 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10861 // If the type of the builtin differs only in its exception
10862 // specification, that's OK.
10863 // FIXME: If the types do differ in this way, it would be better to
10864 // retain the 'noexcept' form of the type.
10865 if (!T.isNull() &&
10866 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10867 NewFD->getType()))
10868 // The type of this function differs from the type of the builtin,
10869 // so forget about the builtin entirely.
10870 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10871 }
10872
10873 // If this function is declared as being extern "C", then check to see if
10874 // the function returns a UDT (class, struct, or union type) that is not C
10875 // compatible, and if it does, warn the user.
10876 // But, issue any diagnostic on the first declaration only.
10877 if (Previous.empty() && NewFD->isExternC()) {
10878 QualType R = NewFD->getReturnType();
10879 if (R->isIncompleteType() && !R->isVoidType())
10880 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10881 << NewFD << R;
10882 else if (!R.isPODType(Context) && !R->isVoidType() &&
10883 !R->isObjCObjectPointerType())
10884 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10885 }
10886
10887 // C++1z [dcl.fct]p6:
10888 // [...] whether the function has a non-throwing exception-specification
10889 // [is] part of the function type
10890 //
10891 // This results in an ABI break between C++14 and C++17 for functions whose
10892 // declared type includes an exception-specification in a parameter or
10893 // return type. (Exception specifications on the function itself are OK in
10894 // most cases, and exception specifications are not permitted in most other
10895 // contexts where they could make it into a mangling.)
10896 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10897 auto HasNoexcept = [&](QualType T) -> bool {
10898 // Strip off declarator chunks that could be between us and a function
10899 // type. We don't need to look far, exception specifications are very
10900 // restricted prior to C++17.
10901 if (auto *RT = T->getAs<ReferenceType>())
10902 T = RT->getPointeeType();
10903 else if (T->isAnyPointerType())
10904 T = T->getPointeeType();
10905 else if (auto *MPT = T->getAs<MemberPointerType>())
10906 T = MPT->getPointeeType();
10907 if (auto *FPT = T->getAs<FunctionProtoType>())
10908 if (FPT->isNothrow())
10909 return true;
10910 return false;
10911 };
10912
10913 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10914 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10915 for (QualType T : FPT->param_types())
10916 AnyNoexcept |= HasNoexcept(T);
10917 if (AnyNoexcept)
10918 Diag(NewFD->getLocation(),
10919 diag::warn_cxx17_compat_exception_spec_in_signature)
10920 << NewFD;
10921 }
10922
10923 if (!Redeclaration && LangOpts.CUDA)
10924 checkCUDATargetOverload(NewFD, Previous);
10925 }
10926 return Redeclaration;
10927}
10928
10929void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10930 // C++11 [basic.start.main]p3:
10931 // A program that [...] declares main to be inline, static or
10932 // constexpr is ill-formed.
10933 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10934 // appear in a declaration of main.
10935 // static main is not an error under C99, but we should warn about it.
10936 // We accept _Noreturn main as an extension.
10937 if (FD->getStorageClass() == SC_Static)
10938 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10939 ? diag::err_static_main : diag::warn_static_main)
10940 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10941 if (FD->isInlineSpecified())
10942 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10943 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10944 if (DS.isNoreturnSpecified()) {
10945 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10946 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10947 Diag(NoreturnLoc, diag::ext_noreturn_main);
10948 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10949 << FixItHint::CreateRemoval(NoreturnRange);
10950 }
10951 if (FD->isConstexpr()) {
10952 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10953 << FD->isConsteval()
10954 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10955 FD->setConstexprKind(CSK_unspecified);
10956 }
10957
10958 if (getLangOpts().OpenCL) {
10959 Diag(FD->getLocation(), diag::err_opencl_no_main)
10960 << FD->hasAttr<OpenCLKernelAttr>();
10961 FD->setInvalidDecl();
10962 return;
10963 }
10964
10965 QualType T = FD->getType();
10966 assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 10966, __PRETTY_FUNCTION__))
;
10967 const FunctionType* FT = T->castAs<FunctionType>();
10968
10969 // Set default calling convention for main()
10970 if (FT->getCallConv() != CC_C) {
10971 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10972 FD->setType(QualType(FT, 0));
10973 T = Context.getCanonicalType(FD->getType());
10974 }
10975
10976 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10977 // In C with GNU extensions we allow main() to have non-integer return
10978 // type, but we should warn about the extension, and we disable the
10979 // implicit-return-zero rule.
10980
10981 // GCC in C mode accepts qualified 'int'.
10982 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10983 FD->setHasImplicitReturnZero(true);
10984 else {
10985 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10986 SourceRange RTRange = FD->getReturnTypeSourceRange();
10987 if (RTRange.isValid())
10988 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10989 << FixItHint::CreateReplacement(RTRange, "int");
10990 }
10991 } else {
10992 // In C and C++, main magically returns 0 if you fall off the end;
10993 // set the flag which tells us that.
10994 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10995
10996 // All the standards say that main() should return 'int'.
10997 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10998 FD->setHasImplicitReturnZero(true);
10999 else {
11000 // Otherwise, this is just a flat-out error.
11001 SourceRange RTRange = FD->getReturnTypeSourceRange();
11002 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11003 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11004 : FixItHint());
11005 FD->setInvalidDecl(true);
11006 }
11007 }
11008
11009 // Treat protoless main() as nullary.
11010 if (isa<FunctionNoProtoType>(FT)) return;
11011
11012 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11013 unsigned nparams = FTP->getNumParams();
11014 assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void>
(0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11014, __PRETTY_FUNCTION__))
;
11015
11016 bool HasExtraParameters = (nparams > 3);
11017
11018 if (FTP->isVariadic()) {
11019 Diag(FD->getLocation(), diag::ext_variadic_main);
11020 // FIXME: if we had information about the location of the ellipsis, we
11021 // could add a FixIt hint to remove it as a parameter.
11022 }
11023
11024 // Darwin passes an undocumented fourth argument of type char**. If
11025 // other platforms start sprouting these, the logic below will start
11026 // getting shifty.
11027 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11028 HasExtraParameters = false;
11029
11030 if (HasExtraParameters) {
11031 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11032 FD->setInvalidDecl(true);
11033 nparams = 3;
11034 }
11035
11036 // FIXME: a lot of the following diagnostics would be improved
11037 // if we had some location information about types.
11038
11039 QualType CharPP =
11040 Context.getPointerType(Context.getPointerType(Context.CharTy));
11041 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11042
11043 for (unsigned i = 0; i < nparams; ++i) {
11044 QualType AT = FTP->getParamType(i);
11045
11046 bool mismatch = true;
11047
11048 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11049 mismatch = false;
11050 else if (Expected[i] == CharPP) {
11051 // As an extension, the following forms are okay:
11052 // char const **
11053 // char const * const *
11054 // char * const *
11055
11056 QualifierCollector qs;
11057 const PointerType* PT;
11058 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11059 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11060 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11061 Context.CharTy)) {
11062 qs.removeConst();
11063 mismatch = !qs.empty();
11064 }
11065 }
11066
11067 if (mismatch) {
11068 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11069 // TODO: suggest replacing given type with expected type
11070 FD->setInvalidDecl(true);
11071 }
11072 }
11073
11074 if (nparams == 1 && !FD->isInvalidDecl()) {
11075 Diag(FD->getLocation(), diag::warn_main_one_arg);
11076 }
11077
11078 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11079 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11080 FD->setInvalidDecl();
11081 }
11082}
11083
11084void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11085 QualType T = FD->getType();
11086 assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type"
) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11086, __PRETTY_FUNCTION__))
;
11087 const FunctionType *FT = T->castAs<FunctionType>();
11088
11089 // Set an implicit return of 'zero' if the function can return some integral,
11090 // enumeration, pointer or nullptr type.
11091 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11092 FT->getReturnType()->isAnyPointerType() ||
11093 FT->getReturnType()->isNullPtrType())
11094 // DllMain is exempt because a return value of zero means it failed.
11095 if (FD->getName() != "DllMain")
11096 FD->setHasImplicitReturnZero(true);
11097
11098 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11099 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11100 FD->setInvalidDecl();
11101 }
11102}
11103
11104bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11105 // FIXME: Need strict checking. In C89, we need to check for
11106 // any assignment, increment, decrement, function-calls, or
11107 // commas outside of a sizeof. In C99, it's the same list,
11108 // except that the aforementioned are allowed in unevaluated
11109 // expressions. Everything else falls under the
11110 // "may accept other forms of constant expressions" exception.
11111 //
11112 // Regular C++ code will not end up here (exceptions: language extensions,
11113 // OpenCL C++ etc), so the constant expression rules there don't matter.
11114 if (Init->isValueDependent()) {
11115 assert(Init->containsErrors() &&((Init->containsErrors() && "Dependent code should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11116, __PRETTY_FUNCTION__))
11116 "Dependent code should only occur in error-recovery path.")((Init->containsErrors() && "Dependent code should only occur in error-recovery path."
) ? static_cast<void> (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11116, __PRETTY_FUNCTION__))
;
11117 return true;
11118 }
11119 const Expr *Culprit;
11120 if (Init->isConstantInitializer(Context, false, &Culprit))
11121 return false;
11122 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11123 << Culprit->getSourceRange();
11124 return true;
11125}
11126
11127namespace {
11128 // Visits an initialization expression to see if OrigDecl is evaluated in
11129 // its own initialization and throws a warning if it does.
11130 class SelfReferenceChecker
11131 : public EvaluatedExprVisitor<SelfReferenceChecker> {
11132 Sema &S;
11133 Decl *OrigDecl;
11134 bool isRecordType;
11135 bool isPODType;
11136 bool isReferenceType;
11137
11138 bool isInitList;
11139 llvm::SmallVector<unsigned, 4> InitFieldIndex;
11140
11141 public:
11142 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11143
11144 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11145 S(S), OrigDecl(OrigDecl) {
11146 isPODType = false;
11147 isRecordType = false;
11148 isReferenceType = false;
11149 isInitList = false;
11150 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11151 isPODType = VD->getType().isPODType(S.Context);
11152 isRecordType = VD->getType()->isRecordType();
11153 isReferenceType = VD->getType()->isReferenceType();
11154 }
11155 }
11156
11157 // For most expressions, just call the visitor. For initializer lists,
11158 // track the index of the field being initialized since fields are
11159 // initialized in order allowing use of previously initialized fields.
11160 void CheckExpr(Expr *E) {
11161 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11162 if (!InitList) {
11163 Visit(E);
11164 return;
11165 }
11166
11167 // Track and increment the index here.
11168 isInitList = true;
11169 InitFieldIndex.push_back(0);
11170 for (auto Child : InitList->children()) {
11171 CheckExpr(cast<Expr>(Child));
11172 ++InitFieldIndex.back();
11173 }
11174 InitFieldIndex.pop_back();
11175 }
11176
11177 // Returns true if MemberExpr is checked and no further checking is needed.
11178 // Returns false if additional checking is required.
11179 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11180 llvm::SmallVector<FieldDecl*, 4> Fields;
11181 Expr *Base = E;
11182 bool ReferenceField = false;
11183
11184 // Get the field members used.
11185 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11186 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11187 if (!FD)
11188 return false;
11189 Fields.push_back(FD);
11190 if (FD->getType()->isReferenceType())
11191 ReferenceField = true;
11192 Base = ME->getBase()->IgnoreParenImpCasts();
11193 }
11194
11195 // Keep checking only if the base Decl is the same.
11196 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11197 if (!DRE || DRE->getDecl() != OrigDecl)
11198 return false;
11199
11200 // A reference field can be bound to an unininitialized field.
11201 if (CheckReference && !ReferenceField)
11202 return true;
11203
11204 // Convert FieldDecls to their index number.
11205 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11206 for (const FieldDecl *I : llvm::reverse(Fields))
11207 UsedFieldIndex.push_back(I->getFieldIndex());
11208
11209 // See if a warning is needed by checking the first difference in index
11210 // numbers. If field being used has index less than the field being
11211 // initialized, then the use is safe.
11212 for (auto UsedIter = UsedFieldIndex.begin(),
11213 UsedEnd = UsedFieldIndex.end(),
11214 OrigIter = InitFieldIndex.begin(),
11215 OrigEnd = InitFieldIndex.end();
11216 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11217 if (*UsedIter < *OrigIter)
11218 return true;
11219 if (*UsedIter > *OrigIter)
11220 break;
11221 }
11222
11223 // TODO: Add a different warning which will print the field names.
11224 HandleDeclRefExpr(DRE);
11225 return true;
11226 }
11227
11228 // For most expressions, the cast is directly above the DeclRefExpr.
11229 // For conditional operators, the cast can be outside the conditional
11230 // operator if both expressions are DeclRefExpr's.
11231 void HandleValue(Expr *E) {
11232 E = E->IgnoreParens();
11233 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11234 HandleDeclRefExpr(DRE);
11235 return;
11236 }
11237
11238 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11239 Visit(CO->getCond());
11240 HandleValue(CO->getTrueExpr());
11241 HandleValue(CO->getFalseExpr());
11242 return;
11243 }
11244
11245 if (BinaryConditionalOperator *BCO =
11246 dyn_cast<BinaryConditionalOperator>(E)) {
11247 Visit(BCO->getCond());
11248 HandleValue(BCO->getFalseExpr());
11249 return;
11250 }
11251
11252 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11253 HandleValue(OVE->getSourceExpr());
11254 return;
11255 }
11256
11257 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11258 if (BO->getOpcode() == BO_Comma) {
11259 Visit(BO->getLHS());
11260 HandleValue(BO->getRHS());
11261 return;
11262 }
11263 }
11264
11265 if (isa<MemberExpr>(E)) {
11266 if (isInitList) {
11267 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11268 false /*CheckReference*/))
11269 return;
11270 }
11271
11272 Expr *Base = E->IgnoreParenImpCasts();
11273 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11274 // Check for static member variables and don't warn on them.
11275 if (!isa<FieldDecl>(ME->getMemberDecl()))
11276 return;
11277 Base = ME->getBase()->IgnoreParenImpCasts();
11278 }
11279 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11280 HandleDeclRefExpr(DRE);
11281 return;
11282 }
11283
11284 Visit(E);
11285 }
11286
11287 // Reference types not handled in HandleValue are handled here since all
11288 // uses of references are bad, not just r-value uses.
11289 void VisitDeclRefExpr(DeclRefExpr *E) {
11290 if (isReferenceType)
11291 HandleDeclRefExpr(E);
11292 }
11293
11294 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11295 if (E->getCastKind() == CK_LValueToRValue) {
11296 HandleValue(E->getSubExpr());
11297 return;
11298 }
11299
11300 Inherited::VisitImplicitCastExpr(E);
11301 }
11302
11303 void VisitMemberExpr(MemberExpr *E) {
11304 if (isInitList) {
11305 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11306 return;
11307 }
11308
11309 // Don't warn on arrays since they can be treated as pointers.
11310 if (E->getType()->canDecayToPointerType()) return;
11311
11312 // Warn when a non-static method call is followed by non-static member
11313 // field accesses, which is followed by a DeclRefExpr.
11314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11315 bool Warn = (MD && !MD->isStatic());
11316 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11317 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11318 if (!isa<FieldDecl>(ME->getMemberDecl()))
11319 Warn = false;
11320 Base = ME->getBase()->IgnoreParenImpCasts();
11321 }
11322
11323 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11324 if (Warn)
11325 HandleDeclRefExpr(DRE);
11326 return;
11327 }
11328
11329 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11330 // Visit that expression.
11331 Visit(Base);
11332 }
11333
11334 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11335 Expr *Callee = E->getCallee();
11336
11337 if (isa<UnresolvedLookupExpr>(Callee))
11338 return Inherited::VisitCXXOperatorCallExpr(E);
11339
11340 Visit(Callee);
11341 for (auto Arg: E->arguments())
11342 HandleValue(Arg->IgnoreParenImpCasts());
11343 }
11344
11345 void VisitUnaryOperator(UnaryOperator *E) {
11346 // For POD record types, addresses of its own members are well-defined.
11347 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11348 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11349 if (!isPODType)
11350 HandleValue(E->getSubExpr());
11351 return;
11352 }
11353
11354 if (E->isIncrementDecrementOp()) {
11355 HandleValue(E->getSubExpr());
11356 return;
11357 }
11358
11359 Inherited::VisitUnaryOperator(E);
11360 }
11361
11362 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11363
11364 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11365 if (E->getConstructor()->isCopyConstructor()) {
11366 Expr *ArgExpr = E->getArg(0);
11367 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11368 if (ILE->getNumInits() == 1)
11369 ArgExpr = ILE->getInit(0);
11370 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11371 if (ICE->getCastKind() == CK_NoOp)
11372 ArgExpr = ICE->getSubExpr();
11373 HandleValue(ArgExpr);
11374 return;
11375 }
11376 Inherited::VisitCXXConstructExpr(E);
11377 }
11378
11379 void VisitCallExpr(CallExpr *E) {
11380 // Treat std::move as a use.
11381 if (E->isCallToStdMove()) {
11382 HandleValue(E->getArg(0));
11383 return;
11384 }
11385
11386 Inherited::VisitCallExpr(E);
11387 }
11388
11389 void VisitBinaryOperator(BinaryOperator *E) {
11390 if (E->isCompoundAssignmentOp()) {
11391 HandleValue(E->getLHS());
11392 Visit(E->getRHS());
11393 return;
11394 }
11395
11396 Inherited::VisitBinaryOperator(E);
11397 }
11398
11399 // A custom visitor for BinaryConditionalOperator is needed because the
11400 // regular visitor would check the condition and true expression separately
11401 // but both point to the same place giving duplicate diagnostics.
11402 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11403 Visit(E->getCond());
11404 Visit(E->getFalseExpr());
11405 }
11406
11407 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11408 Decl* ReferenceDecl = DRE->getDecl();
11409 if (OrigDecl != ReferenceDecl) return;
11410 unsigned diag;
11411 if (isReferenceType) {
11412 diag = diag::warn_uninit_self_reference_in_reference_init;
11413 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11414 diag = diag::warn_static_self_reference_in_init;
11415 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11416 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11417 DRE->getDecl()->getType()->isRecordType()) {
11418 diag = diag::warn_uninit_self_reference_in_init;
11419 } else {
11420 // Local variables will be handled by the CFG analysis.
11421 return;
11422 }
11423
11424 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11425 S.PDiag(diag)
11426 << DRE->getDecl() << OrigDecl->getLocation()
11427 << DRE->getSourceRange());
11428 }
11429 };
11430
11431 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11432 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11433 bool DirectInit) {
11434 // Parameters arguments are occassionially constructed with itself,
11435 // for instance, in recursive functions. Skip them.
11436 if (isa<ParmVarDecl>(OrigDecl))
11437 return;
11438
11439 E = E->IgnoreParens();
11440
11441 // Skip checking T a = a where T is not a record or reference type.
11442 // Doing so is a way to silence uninitialized warnings.
11443 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11444 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11445 if (ICE->getCastKind() == CK_LValueToRValue)
11446 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11447 if (DRE->getDecl() == OrigDecl)
11448 return;
11449
11450 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11451 }
11452} // end anonymous namespace
11453
11454namespace {
11455 // Simple wrapper to add the name of a variable or (if no variable is
11456 // available) a DeclarationName into a diagnostic.
11457 struct VarDeclOrName {
11458 VarDecl *VDecl;
11459 DeclarationName Name;
11460
11461 friend const Sema::SemaDiagnosticBuilder &
11462 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11463 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11464 }
11465 };
11466} // end anonymous namespace
11467
11468QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11469 DeclarationName Name, QualType Type,
11470 TypeSourceInfo *TSI,
11471 SourceRange Range, bool DirectInit,
11472 Expr *Init) {
11473 bool IsInitCapture = !VDecl;
11474 assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization"
) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11475, __PRETTY_FUNCTION__))
11475 "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization"
) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11475, __PRETTY_FUNCTION__))
;
11476
11477 VarDeclOrName VN{VDecl, Name};
11478
11479 DeducedType *Deduced = Type->getContainedDeducedType();
11480 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type"
) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11480, __PRETTY_FUNCTION__))
;
11481
11482 // C++11 [dcl.spec.auto]p3
11483 if (!Init) {
11484 assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast
<void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11484, __PRETTY_FUNCTION__))
;
11485
11486 // Except for class argument deduction, and then for an initializing
11487 // declaration only, i.e. no static at class scope or extern.
11488 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11489 VDecl->hasExternalStorage() ||
11490 VDecl->isStaticDataMember()) {
11491 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11492 << VDecl->getDeclName() << Type;
11493 return QualType();
11494 }
11495 }
11496
11497 ArrayRef<Expr*> DeduceInits;
11498 if (Init)
11499 DeduceInits = Init;
11500
11501 if (DirectInit) {
11502 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11503 DeduceInits = PL->exprs();
11504 }
11505
11506 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11507 assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?"
) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11507, __PRETTY_FUNCTION__))
;
11508 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11509 InitializationKind Kind = InitializationKind::CreateForInit(
11510 VDecl->getLocation(), DirectInit, Init);
11511 // FIXME: Initialization should not be taking a mutable list of inits.
11512 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11513 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11514 InitsCopy);
11515 }
11516
11517 if (DirectInit) {
11518 if (auto *IL = dyn_cast<InitListExpr>(Init))
11519 DeduceInits = IL->inits();
11520 }
11521
11522 // Deduction only works if we have exactly one source expression.
11523 if (DeduceInits.empty()) {
11524 // It isn't possible to write this directly, but it is possible to
11525 // end up in this situation with "auto x(some_pack...);"
11526 Diag(Init->getBeginLoc(), IsInitCapture
11527 ? diag::err_init_capture_no_expression
11528 : diag::err_auto_var_init_no_expression)
11529 << VN << Type << Range;
11530 return QualType();
11531 }
11532
11533 if (DeduceInits.size() > 1) {
11534 Diag(DeduceInits[1]->getBeginLoc(),
11535 IsInitCapture ? diag::err_init_capture_multiple_expressions
11536 : diag::err_auto_var_init_multiple_expressions)
11537 << VN << Type << Range;
11538 return QualType();
11539 }
11540
11541 Expr *DeduceInit = DeduceInits[0];
11542 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11543 Diag(Init->getBeginLoc(), IsInitCapture
11544 ? diag::err_init_capture_paren_braces
11545 : diag::err_auto_var_init_paren_braces)
11546 << isa<InitListExpr>(Init) << VN << Type << Range;
11547 return QualType();
11548 }
11549
11550 // Expressions default to 'id' when we're in a debugger.
11551 bool DefaultedAnyToId = false;
11552 if (getLangOpts().DebuggerCastResultToId &&
11553 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11554 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11555 if (Result.isInvalid()) {
11556 return QualType();
11557 }
11558 Init = Result.get();
11559 DefaultedAnyToId = true;
11560 }
11561
11562 // C++ [dcl.decomp]p1:
11563 // If the assignment-expression [...] has array type A and no ref-qualifier
11564 // is present, e has type cv A
11565 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11566 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11567 DeduceInit->getType()->isConstantArrayType())
11568 return Context.getQualifiedType(DeduceInit->getType(),
11569 Type.getQualifiers());
11570
11571 QualType DeducedType;
11572 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11573 if (!IsInitCapture)
11574 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11575 else if (isa<InitListExpr>(Init))
11576 Diag(Range.getBegin(),
11577 diag::err_init_capture_deduction_failure_from_init_list)
11578 << VN
11579 << (DeduceInit->getType().isNull() ? TSI->getType()
11580 : DeduceInit->getType())
11581 << DeduceInit->getSourceRange();
11582 else
11583 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11584 << VN << TSI->getType()
11585 << (DeduceInit->getType().isNull() ? TSI->getType()
11586 : DeduceInit->getType())
11587 << DeduceInit->getSourceRange();
11588 }
11589
11590 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11591 // 'id' instead of a specific object type prevents most of our usual
11592 // checks.
11593 // We only want to warn outside of template instantiations, though:
11594 // inside a template, the 'id' could have come from a parameter.
11595 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11596 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11597 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11598 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11599 }
11600
11601 return DeducedType;
11602}
11603
11604bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11605 Expr *Init) {
11606 assert(!Init || !Init->containsErrors())((!Init || !Init->containsErrors()) ? static_cast<void>
(0) : __assert_fail ("!Init || !Init->containsErrors()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11606, __PRETTY_FUNCTION__))
;
11607 QualType DeducedType = deduceVarTypeFromInitializer(
11608 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11609 VDecl->getSourceRange(), DirectInit, Init);
11610 if (DeducedType.isNull()) {
11611 VDecl->setInvalidDecl();
11612 return true;
11613 }
11614
11615 VDecl->setType(DeducedType);
11616 assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) :
__assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11616, __PRETTY_FUNCTION__))
;
11617
11618 // In ARC, infer lifetime.
11619 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11620 VDecl->setInvalidDecl();
11621
11622 if (getLangOpts().OpenCL)
11623 deduceOpenCLAddressSpace(VDecl);
11624
11625 // If this is a redeclaration, check that the type we just deduced matches
11626 // the previously declared type.
11627 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11628 // We never need to merge the type, because we cannot form an incomplete
11629 // array of auto, nor deduce such a type.
11630 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11631 }
11632
11633 // Check the deduced type is valid for a variable declaration.
11634 CheckVariableDeclarationType(VDecl);
11635 return VDecl->isInvalidDecl();
11636}
11637
11638void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11639 SourceLocation Loc) {
11640 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11641 Init = EWC->getSubExpr();
11642
11643 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11644 Init = CE->getSubExpr();
11645
11646 QualType InitType = Init->getType();
11647 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11649, __PRETTY_FUNCTION__))
11648 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11649, __PRETTY_FUNCTION__))
11649 "shouldn't be called if type doesn't have a non-trivial C struct")(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()
|| InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
"shouldn't be called if type doesn't have a non-trivial C struct"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11649, __PRETTY_FUNCTION__))
;
11650 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11651 for (auto I : ILE->inits()) {
11652 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11653 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11654 continue;
11655 SourceLocation SL = I->getExprLoc();
11656 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11657 }
11658 return;
11659 }
11660
11661 if (isa<ImplicitValueInitExpr>(Init)) {
11662 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11663 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11664 NTCUK_Init);
11665 } else {
11666 // Assume all other explicit initializers involving copying some existing
11667 // object.
11668 // TODO: ignore any explicit initializers where we can guarantee
11669 // copy-elision.
11670 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11671 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11672 }
11673}
11674
11675namespace {
11676
11677bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11678 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11679 // in the source code or implicitly by the compiler if it is in a union
11680 // defined in a system header and has non-trivial ObjC ownership
11681 // qualifications. We don't want those fields to participate in determining
11682 // whether the containing union is non-trivial.
11683 return FD->hasAttr<UnavailableAttr>();
11684}
11685
11686struct DiagNonTrivalCUnionDefaultInitializeVisitor
11687 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11688 void> {
11689 using Super =
11690 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11691 void>;
11692
11693 DiagNonTrivalCUnionDefaultInitializeVisitor(
11694 QualType OrigTy, SourceLocation OrigLoc,
11695 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11696 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11697
11698 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11699 const FieldDecl *FD, bool InNonTrivialUnion) {
11700 if (const auto *AT = S.Context.getAsArrayType(QT))
11701 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11702 InNonTrivialUnion);
11703 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11704 }
11705
11706 void visitARCStrong(QualType QT, const FieldDecl *FD,
11707 bool InNonTrivialUnion) {
11708 if (InNonTrivialUnion)
11709 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11710 << 1 << 0 << QT << FD->getName();
11711 }
11712
11713 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11714 if (InNonTrivialUnion)
11715 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11716 << 1 << 0 << QT << FD->getName();
11717 }
11718
11719 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11720 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11721 if (RD->isUnion()) {
11722 if (OrigLoc.isValid()) {
11723 bool IsUnion = false;
11724 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11725 IsUnion = OrigRD->isUnion();
11726 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11727 << 0 << OrigTy << IsUnion << UseContext;
11728 // Reset OrigLoc so that this diagnostic is emitted only once.
11729 OrigLoc = SourceLocation();
11730 }
11731 InNonTrivialUnion = true;
11732 }
11733
11734 if (InNonTrivialUnion)
11735 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11736 << 0 << 0 << QT.getUnqualifiedType() << "";
11737
11738 for (const FieldDecl *FD : RD->fields())
11739 if (!shouldIgnoreForRecordTriviality(FD))
11740 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11741 }
11742
11743 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11744
11745 // The non-trivial C union type or the struct/union type that contains a
11746 // non-trivial C union.
11747 QualType OrigTy;
11748 SourceLocation OrigLoc;
11749 Sema::NonTrivialCUnionContext UseContext;
11750 Sema &S;
11751};
11752
11753struct DiagNonTrivalCUnionDestructedTypeVisitor
11754 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11755 using Super =
11756 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11757
11758 DiagNonTrivalCUnionDestructedTypeVisitor(
11759 QualType OrigTy, SourceLocation OrigLoc,
11760 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11761 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11762
11763 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11764 const FieldDecl *FD, bool InNonTrivialUnion) {
11765 if (const auto *AT = S.Context.getAsArrayType(QT))
11766 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11767 InNonTrivialUnion);
11768 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11769 }
11770
11771 void visitARCStrong(QualType QT, const FieldDecl *FD,
11772 bool InNonTrivialUnion) {
11773 if (InNonTrivialUnion)
11774 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11775 << 1 << 1 << QT << FD->getName();
11776 }
11777
11778 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11779 if (InNonTrivialUnion)
11780 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11781 << 1 << 1 << QT << FD->getName();
11782 }
11783
11784 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11785 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11786 if (RD->isUnion()) {
11787 if (OrigLoc.isValid()) {
11788 bool IsUnion = false;
11789 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11790 IsUnion = OrigRD->isUnion();
11791 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11792 << 1 << OrigTy << IsUnion << UseContext;
11793 // Reset OrigLoc so that this diagnostic is emitted only once.
11794 OrigLoc = SourceLocation();
11795 }
11796 InNonTrivialUnion = true;
11797 }
11798
11799 if (InNonTrivialUnion)
11800 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11801 << 0 << 1 << QT.getUnqualifiedType() << "";
11802
11803 for (const FieldDecl *FD : RD->fields())
11804 if (!shouldIgnoreForRecordTriviality(FD))
11805 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11806 }
11807
11808 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11809 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11810 bool InNonTrivialUnion) {}
11811
11812 // The non-trivial C union type or the struct/union type that contains a
11813 // non-trivial C union.
11814 QualType OrigTy;
11815 SourceLocation OrigLoc;
11816 Sema::NonTrivialCUnionContext UseContext;
11817 Sema &S;
11818};
11819
11820struct DiagNonTrivalCUnionCopyVisitor
11821 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11822 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11823
11824 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11825 Sema::NonTrivialCUnionContext UseContext,
11826 Sema &S)
11827 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11828
11829 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11830 const FieldDecl *FD, bool InNonTrivialUnion) {
11831 if (const auto *AT = S.Context.getAsArrayType(QT))
11832 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11833 InNonTrivialUnion);
11834 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11835 }
11836
11837 void visitARCStrong(QualType QT, const FieldDecl *FD,
11838 bool InNonTrivialUnion) {
11839 if (InNonTrivialUnion)
11840 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11841 << 1 << 2 << QT << FD->getName();
11842 }
11843
11844 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11845 if (InNonTrivialUnion)
11846 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11847 << 1 << 2 << QT << FD->getName();
11848 }
11849
11850 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11851 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11852 if (RD->isUnion()) {
11853 if (OrigLoc.isValid()) {
11854 bool IsUnion = false;
11855 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11856 IsUnion = OrigRD->isUnion();
11857 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11858 << 2 << OrigTy << IsUnion << UseContext;
11859 // Reset OrigLoc so that this diagnostic is emitted only once.
11860 OrigLoc = SourceLocation();
11861 }
11862 InNonTrivialUnion = true;
11863 }
11864
11865 if (InNonTrivialUnion)
11866 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11867 << 0 << 2 << QT.getUnqualifiedType() << "";
11868
11869 for (const FieldDecl *FD : RD->fields())
11870 if (!shouldIgnoreForRecordTriviality(FD))
11871 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11872 }
11873
11874 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11875 const FieldDecl *FD, bool InNonTrivialUnion) {}
11876 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11877 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11878 bool InNonTrivialUnion) {}
11879
11880 // The non-trivial C union type or the struct/union type that contains a
11881 // non-trivial C union.
11882 QualType OrigTy;
11883 SourceLocation OrigLoc;
11884 Sema::NonTrivialCUnionContext UseContext;
11885 Sema &S;
11886};
11887
11888} // namespace
11889
11890void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11891 NonTrivialCUnionContext UseContext,
11892 unsigned NonTrivialKind) {
11893 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11896, __PRETTY_FUNCTION__))
11894 QT.hasNonTrivialToPrimitiveDestructCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11896, __PRETTY_FUNCTION__))
11895 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11896, __PRETTY_FUNCTION__))
11896 "shouldn't be called if type doesn't have a non-trivial C union")(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT
.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion
()) && "shouldn't be called if type doesn't have a non-trivial C union"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11896, __PRETTY_FUNCTION__))
;
11897
11898 if ((NonTrivialKind & NTCUK_Init) &&
11899 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11900 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11901 .visit(QT, nullptr, false);
11902 if ((NonTrivialKind & NTCUK_Destruct) &&
11903 QT.hasNonTrivialToPrimitiveDestructCUnion())
11904 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11905 .visit(QT, nullptr, false);
11906 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11907 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11908 .visit(QT, nullptr, false);
11909}
11910
11911/// AddInitializerToDecl - Adds the initializer Init to the
11912/// declaration dcl. If DirectInit is true, this is C++ direct
11913/// initialization rather than copy initialization.
11914void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11915 // If there is no declaration, there was an error parsing it. Just ignore
11916 // the initializer.
11917 if (!RealDecl || RealDecl->isInvalidDecl()) {
11918 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11919 return;
11920 }
11921
11922 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11923 // Pure-specifiers are handled in ActOnPureSpecifier.
11924 Diag(Method->getLocation(), diag::err_member_function_initialization)
11925 << Method->getDeclName() << Init->getSourceRange();
11926 Method->setInvalidDecl();
11927 return;
11928 }
11929
11930 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11931 if (!VDecl) {
11932 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"
) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 11932, __PRETTY_FUNCTION__))
;
11933 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11934 RealDecl->setInvalidDecl();
11935 return;
11936 }
11937
11938 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11939 if (VDecl->getType()->isUndeducedType()) {
11940 // Attempt typo correction early so that the type of the init expression can
11941 // be deduced based on the chosen correction if the original init contains a
11942 // TypoExpr.
11943 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11944 if (!Res.isUsable()) {
11945 // There are unresolved typos in Init, just drop them.
11946 // FIXME: improve the recovery strategy to preserve the Init.
11947 RealDecl->setInvalidDecl();
11948 return;
11949 }
11950 if (Res.get()->containsErrors()) {
11951 // Invalidate the decl as we don't know the type for recovery-expr yet.
11952 RealDecl->setInvalidDecl();
11953 VDecl->setInit(Res.get());
11954 return;
11955 }
11956 Init = Res.get();
11957
11958 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11959 return;
11960 }
11961
11962 // dllimport cannot be used on variable definitions.
11963 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11964 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11965 VDecl->setInvalidDecl();
11966 return;
11967 }
11968
11969 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11970 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11971 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11972 VDecl->setInvalidDecl();
11973 return;
11974 }
11975
11976 if (!VDecl->getType()->isDependentType()) {
11977 // A definition must end up with a complete type, which means it must be
11978 // complete with the restriction that an array type might be completed by
11979 // the initializer; note that later code assumes this restriction.
11980 QualType BaseDeclType = VDecl->getType();
11981 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11982 BaseDeclType = Array->getElementType();
11983 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11984 diag::err_typecheck_decl_incomplete_type)) {
11985 RealDecl->setInvalidDecl();
11986 return;
11987 }
11988
11989 // The variable can not have an abstract class type.
11990 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11991 diag::err_abstract_type_in_decl,
11992 AbstractVariableType))
11993 VDecl->setInvalidDecl();
11994 }
11995
11996 // If adding the initializer will turn this declaration into a definition,
11997 // and we already have a definition for this variable, diagnose or otherwise
11998 // handle the situation.
11999 VarDecl *Def;
12000 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12001 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12002 !VDecl->isThisDeclarationADemotedDefinition() &&
12003 checkVarDeclRedefinition(Def, VDecl))
12004 return;
12005
12006 if (getLangOpts().CPlusPlus) {
12007 // C++ [class.static.data]p4
12008 // If a static data member is of const integral or const
12009 // enumeration type, its declaration in the class definition can
12010 // specify a constant-initializer which shall be an integral
12011 // constant expression (5.19). In that case, the member can appear
12012 // in integral constant expressions. The member shall still be
12013 // defined in a namespace scope if it is used in the program and the
12014 // namespace scope definition shall not contain an initializer.
12015 //
12016 // We already performed a redefinition check above, but for static
12017 // data members we also need to check whether there was an in-class
12018 // declaration with an initializer.
12019 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12020 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12021 << VDecl->getDeclName();
12022 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12023 diag::note_previous_initializer)
12024 << 0;
12025 return;
12026 }
12027
12028 if (VDecl->hasLocalStorage())
12029 setFunctionHasBranchProtectedScope();
12030
12031 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12032 VDecl->setInvalidDecl();
12033 return;
12034 }
12035 }
12036
12037 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12038 // a kernel function cannot be initialized."
12039 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12040 Diag(VDecl->getLocation(), diag::err_local_cant_init);
12041 VDecl->setInvalidDecl();
12042 return;
12043 }
12044
12045 // The LoaderUninitialized attribute acts as a definition (of undef).
12046 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12047 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12048 VDecl->setInvalidDecl();
12049 return;
12050 }
12051
12052 // Get the decls type and save a reference for later, since
12053 // CheckInitializerTypes may change it.
12054 QualType DclT = VDecl->getType(), SavT = DclT;
12055
12056 // Expressions default to 'id' when we're in a debugger
12057 // and we are assigning it to a variable of Objective-C pointer type.
12058 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12059 Init->getType() == Context.UnknownAnyTy) {
12060 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12061 if (Result.isInvalid()) {
12062 VDecl->setInvalidDecl();
12063 return;
12064 }
12065 Init = Result.get();
12066 }
12067
12068 // Perform the initialization.
12069 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12070 if (!VDecl->isInvalidDecl()) {
12071 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12072 InitializationKind Kind = InitializationKind::CreateForInit(
12073 VDecl->getLocation(), DirectInit, Init);
12074
12075 MultiExprArg Args = Init;
12076 if (CXXDirectInit)
12077 Args = MultiExprArg(CXXDirectInit->getExprs(),
12078 CXXDirectInit->getNumExprs());
12079
12080 // Try to correct any TypoExprs in the initialization arguments.
12081 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12082 ExprResult Res = CorrectDelayedTyposInExpr(
12083 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12084 [this, Entity, Kind](Expr *E) {
12085 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12086 return Init.Failed() ? ExprError() : E;
12087 });
12088 if (Res.isInvalid()) {
12089 VDecl->setInvalidDecl();
12090 } else if (Res.get() != Args[Idx]) {
12091 Args[Idx] = Res.get();
12092 }
12093 }
12094 if (VDecl->isInvalidDecl())
12095 return;
12096
12097 InitializationSequence InitSeq(*this, Entity, Kind, Args,
12098 /*TopLevelOfInitList=*/false,
12099 /*TreatUnavailableAsInvalid=*/false);
12100 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12101 if (Result.isInvalid()) {
12102 // If the provied initializer fails to initialize the var decl,
12103 // we attach a recovery expr for better recovery.
12104 auto RecoveryExpr =
12105 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12106 if (RecoveryExpr.get())
12107 VDecl->setInit(RecoveryExpr.get());
12108 return;
12109 }
12110
12111 Init = Result.getAs<Expr>();
12112 }
12113
12114 // Check for self-references within variable initializers.
12115 // Variables declared within a function/method body (except for references)
12116 // are handled by a dataflow analysis.
12117 // This is undefined behavior in C++, but valid in C.
12118 if (getLangOpts().CPlusPlus) {
12119 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12120 VDecl->getType()->isReferenceType()) {
12121 CheckSelfReference(*this, RealDecl, Init, DirectInit);
12122 }
12123 }
12124
12125 // If the type changed, it means we had an incomplete type that was
12126 // completed by the initializer. For example:
12127 // int ary[] = { 1, 3, 5 };
12128 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12129 if (!VDecl->isInvalidDecl() && (DclT != SavT))
12130 VDecl->setType(DclT);
12131
12132 if (!VDecl->isInvalidDecl()) {
12133 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12134
12135 if (VDecl->hasAttr<BlocksAttr>())
12136 checkRetainCycles(VDecl, Init);
12137
12138 // It is safe to assign a weak reference into a strong variable.
12139 // Although this code can still have problems:
12140 // id x = self.weakProp;
12141 // id y = self.weakProp;
12142 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12143 // paths through the function. This should be revisited if
12144 // -Wrepeated-use-of-weak is made flow-sensitive.
12145 if (FunctionScopeInfo *FSI = getCurFunction())
12146 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12147 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12148 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12149 Init->getBeginLoc()))
12150 FSI->markSafeWeakUse(Init);
12151 }
12152
12153 // The initialization is usually a full-expression.
12154 //
12155 // FIXME: If this is a braced initialization of an aggregate, it is not
12156 // an expression, and each individual field initializer is a separate
12157 // full-expression. For instance, in:
12158 //
12159 // struct Temp { ~Temp(); };
12160 // struct S { S(Temp); };
12161 // struct T { S a, b; } t = { Temp(), Temp() }
12162 //
12163 // we should destroy the first Temp before constructing the second.
12164 ExprResult Result =
12165 ActOnFinishFullExpr(Init, VDecl->getLocation(),
12166 /*DiscardedValue*/ false, VDecl->isConstexpr());
12167 if (Result.isInvalid()) {
12168 VDecl->setInvalidDecl();
12169 return;
12170 }
12171 Init = Result.get();
12172
12173 // Attach the initializer to the decl.
12174 VDecl->setInit(Init);
12175
12176 if (VDecl->isLocalVarDecl()) {
12177 // Don't check the initializer if the declaration is malformed.
12178 if (VDecl->isInvalidDecl()) {
12179 // do nothing
12180
12181 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12182 // This is true even in C++ for OpenCL.
12183 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12184 CheckForConstantInitializer(Init, DclT);
12185
12186 // Otherwise, C++ does not restrict the initializer.
12187 } else if (getLangOpts().CPlusPlus) {
12188 // do nothing
12189
12190 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12191 // static storage duration shall be constant expressions or string literals.
12192 } else if (VDecl->getStorageClass() == SC_Static) {
12193 CheckForConstantInitializer(Init, DclT);
12194
12195 // C89 is stricter than C99 for aggregate initializers.
12196 // C89 6.5.7p3: All the expressions [...] in an initializer list
12197 // for an object that has aggregate or union type shall be
12198 // constant expressions.
12199 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12200 isa<InitListExpr>(Init)) {
12201 const Expr *Culprit;
12202 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12203 Diag(Culprit->getExprLoc(),
12204 diag::ext_aggregate_init_not_constant)
12205 << Culprit->getSourceRange();
12206 }
12207 }
12208
12209 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12210 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12211 if (VDecl->hasLocalStorage())
12212 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12213 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12214 VDecl->getLexicalDeclContext()->isRecord()) {
12215 // This is an in-class initialization for a static data member, e.g.,
12216 //
12217 // struct S {
12218 // static const int value = 17;
12219 // };
12220
12221 // C++ [class.mem]p4:
12222 // A member-declarator can contain a constant-initializer only
12223 // if it declares a static member (9.4) of const integral or
12224 // const enumeration type, see 9.4.2.
12225 //
12226 // C++11 [class.static.data]p3:
12227 // If a non-volatile non-inline const static data member is of integral
12228 // or enumeration type, its declaration in the class definition can
12229 // specify a brace-or-equal-initializer in which every initializer-clause
12230 // that is an assignment-expression is a constant expression. A static
12231 // data member of literal type can be declared in the class definition
12232 // with the constexpr specifier; if so, its declaration shall specify a
12233 // brace-or-equal-initializer in which every initializer-clause that is
12234 // an assignment-expression is a constant expression.
12235
12236 // Do nothing on dependent types.
12237 if (DclT->isDependentType()) {
12238
12239 // Allow any 'static constexpr' members, whether or not they are of literal
12240 // type. We separately check that every constexpr variable is of literal
12241 // type.
12242 } else if (VDecl->isConstexpr()) {
12243
12244 // Require constness.
12245 } else if (!DclT.isConstQualified()) {
12246 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12247 << Init->getSourceRange();
12248 VDecl->setInvalidDecl();
12249
12250 // We allow integer constant expressions in all cases.
12251 } else if (DclT->isIntegralOrEnumerationType()) {
12252 // Check whether the expression is a constant expression.
12253 SourceLocation Loc;
12254 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12255 // In C++11, a non-constexpr const static data member with an
12256 // in-class initializer cannot be volatile.
12257 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12258 else if (Init->isValueDependent())
12259 ; // Nothing to check.
12260 else if (Init->isIntegerConstantExpr(Context, &Loc))
12261 ; // Ok, it's an ICE!
12262 else if (Init->getType()->isScopedEnumeralType() &&
12263 Init->isCXX11ConstantExpr(Context))
12264 ; // Ok, it is a scoped-enum constant expression.
12265 else if (Init->isEvaluatable(Context)) {
12266 // If we can constant fold the initializer through heroics, accept it,
12267 // but report this as a use of an extension for -pedantic.
12268 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12269 << Init->getSourceRange();
12270 } else {
12271 // Otherwise, this is some crazy unknown case. Report the issue at the
12272 // location provided by the isIntegerConstantExpr failed check.
12273 Diag(Loc, diag::err_in_class_initializer_non_constant)
12274 << Init->getSourceRange();
12275 VDecl->setInvalidDecl();
12276 }
12277
12278 // We allow foldable floating-point constants as an extension.
12279 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12280 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12281 // it anyway and provide a fixit to add the 'constexpr'.
12282 if (getLangOpts().CPlusPlus11) {
12283 Diag(VDecl->getLocation(),
12284 diag::ext_in_class_initializer_float_type_cxx11)
12285 << DclT << Init->getSourceRange();
12286 Diag(VDecl->getBeginLoc(),
12287 diag::note_in_class_initializer_float_type_cxx11)
12288 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12289 } else {
12290 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12291 << DclT << Init->getSourceRange();
12292
12293 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12294 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12295 << Init->getSourceRange();
12296 VDecl->setInvalidDecl();
12297 }
12298 }
12299
12300 // Suggest adding 'constexpr' in C++11 for literal types.
12301 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12302 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12303 << DclT << Init->getSourceRange()
12304 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12305 VDecl->setConstexpr(true);
12306
12307 } else {
12308 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12309 << DclT << Init->getSourceRange();
12310 VDecl->setInvalidDecl();
12311 }
12312 } else if (VDecl->isFileVarDecl()) {
12313 // In C, extern is typically used to avoid tentative definitions when
12314 // declaring variables in headers, but adding an intializer makes it a
12315 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12316 // In C++, extern is often used to give implictly static const variables
12317 // external linkage, so don't warn in that case. If selectany is present,
12318 // this might be header code intended for C and C++ inclusion, so apply the
12319 // C++ rules.
12320 if (VDecl->getStorageClass() == SC_Extern &&
12321 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12322 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12323 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12324 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12325 Diag(VDecl->getLocation(), diag::warn_extern_init);
12326
12327 // In Microsoft C++ mode, a const variable defined in namespace scope has
12328 // external linkage by default if the variable is declared with
12329 // __declspec(dllexport).
12330 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12331 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12332 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12333 VDecl->setStorageClass(SC_Extern);
12334
12335 // C99 6.7.8p4. All file scoped initializers need to be constant.
12336 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12337 CheckForConstantInitializer(Init, DclT);
12338 }
12339
12340 QualType InitType = Init->getType();
12341 if (!InitType.isNull() &&
12342 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12343 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12344 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12345
12346 // We will represent direct-initialization similarly to copy-initialization:
12347 // int x(1); -as-> int x = 1;
12348 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12349 //
12350 // Clients that want to distinguish between the two forms, can check for
12351 // direct initializer using VarDecl::getInitStyle().
12352 // A major benefit is that clients that don't particularly care about which
12353 // exactly form was it (like the CodeGen) can handle both cases without
12354 // special case code.
12355
12356 // C++ 8.5p11:
12357 // The form of initialization (using parentheses or '=') is generally
12358 // insignificant, but does matter when the entity being initialized has a
12359 // class type.
12360 if (CXXDirectInit) {
12361 assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init."
) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 12361, __PRETTY_FUNCTION__))
;
12362 VDecl->setInitStyle(VarDecl::CallInit);
12363 } else if (DirectInit) {
12364 // This must be list-initialization. No other way is direct-initialization.
12365 VDecl->setInitStyle(VarDecl::ListInit);
12366 }
12367
12368 if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12369 DeclsToCheckForDeferredDiags.push_back(VDecl);
12370 CheckCompleteVariableDeclaration(VDecl);
12371}
12372
12373/// ActOnInitializerError - Given that there was an error parsing an
12374/// initializer for the given declaration, try to return to some form
12375/// of sanity.
12376void Sema::ActOnInitializerError(Decl *D) {
12377 // Our main concern here is re-establishing invariants like "a
12378 // variable's type is either dependent or complete".
12379 if (!D || D->isInvalidDecl()) return;
12380
12381 VarDecl *VD = dyn_cast<VarDecl>(D);
12382 if (!VD) return;
12383
12384 // Bindings are not usable if we can't make sense of the initializer.
12385 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12386 for (auto *BD : DD->bindings())
12387 BD->setInvalidDecl();
12388
12389 // Auto types are meaningless if we can't make sense of the initializer.
12390 if (VD->getType()->isUndeducedType()) {
12391 D->setInvalidDecl();
12392 return;
12393 }
12394
12395 QualType Ty = VD->getType();
12396 if (Ty->isDependentType()) return;
12397
12398 // Require a complete type.
12399 if (RequireCompleteType(VD->getLocation(),
12400 Context.getBaseElementType(Ty),
12401 diag::err_typecheck_decl_incomplete_type)) {
12402 VD->setInvalidDecl();
12403 return;
12404 }
12405
12406 // Require a non-abstract type.
12407 if (RequireNonAbstractType(VD->getLocation(), Ty,
12408 diag::err_abstract_type_in_decl,
12409 AbstractVariableType)) {
12410 VD->setInvalidDecl();
12411 return;
12412 }
12413
12414 // Don't bother complaining about constructors or destructors,
12415 // though.
12416}
12417
12418void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12419 // If there is no declaration, there was an error parsing it. Just ignore it.
12420 if (!RealDecl)
12421 return;
12422
12423 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12424 QualType Type = Var->getType();
12425
12426 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12427 if (isa<DecompositionDecl>(RealDecl)) {
12428 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12429 Var->setInvalidDecl();
12430 return;
12431 }
12432
12433 if (Type->isUndeducedType() &&
12434 DeduceVariableDeclarationType(Var, false, nullptr))
12435 return;
12436
12437 // C++11 [class.static.data]p3: A static data member can be declared with
12438 // the constexpr specifier; if so, its declaration shall specify
12439 // a brace-or-equal-initializer.
12440 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12441 // the definition of a variable [...] or the declaration of a static data
12442 // member.
12443 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12444 !Var->isThisDeclarationADemotedDefinition()) {
12445 if (Var->isStaticDataMember()) {
12446 // C++1z removes the relevant rule; the in-class declaration is always
12447 // a definition there.
12448 if (!getLangOpts().CPlusPlus17 &&
12449 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12450 Diag(Var->getLocation(),
12451 diag::err_constexpr_static_mem_var_requires_init)
12452 << Var;
12453 Var->setInvalidDecl();
12454 return;
12455 }
12456 } else {
12457 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12458 Var->setInvalidDecl();
12459 return;
12460 }
12461 }
12462
12463 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12464 // be initialized.
12465 if (!Var->isInvalidDecl() &&
12466 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12467 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12468 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12469 Var->setInvalidDecl();
12470 return;
12471 }
12472
12473 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12474 if (Var->getStorageClass() == SC_Extern) {
12475 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12476 << Var;
12477 Var->setInvalidDecl();
12478 return;
12479 }
12480 if (RequireCompleteType(Var->getLocation(), Var->getType(),
12481 diag::err_typecheck_decl_incomplete_type)) {
12482 Var->setInvalidDecl();
12483 return;
12484 }
12485 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12486 if (!RD->hasTrivialDefaultConstructor()) {
12487 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12488 Var->setInvalidDecl();
12489 return;
12490 }
12491 }
12492 }
12493
12494 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12495 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12496 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12497 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12498 NTCUC_DefaultInitializedObject, NTCUK_Init);
12499
12500
12501 switch (DefKind) {
12502 case VarDecl::Definition:
12503 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12504 break;
12505
12506 // We have an out-of-line definition of a static data member
12507 // that has an in-class initializer, so we type-check this like
12508 // a declaration.
12509 //
12510 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12511
12512 case VarDecl::DeclarationOnly:
12513 // It's only a declaration.
12514
12515 // Block scope. C99 6.7p7: If an identifier for an object is
12516 // declared with no linkage (C99 6.2.2p6), the type for the
12517 // object shall be complete.
12518 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12519 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12520 RequireCompleteType(Var->getLocation(), Type,
12521 diag::err_typecheck_decl_incomplete_type))
12522 Var->setInvalidDecl();
12523
12524 // Make sure that the type is not abstract.
12525 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12526 RequireNonAbstractType(Var->getLocation(), Type,
12527 diag::err_abstract_type_in_decl,
12528 AbstractVariableType))
12529 Var->setInvalidDecl();
12530 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12531 Var->getStorageClass() == SC_PrivateExtern) {
12532 Diag(Var->getLocation(), diag::warn_private_extern);
12533 Diag(Var->getLocation(), diag::note_private_extern);
12534 }
12535
12536 if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12537 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12538 ExternalDeclarations.push_back(Var);
12539
12540 return;
12541
12542 case VarDecl::TentativeDefinition:
12543 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12544 // object that has file scope without an initializer, and without a
12545 // storage-class specifier or with the storage-class specifier "static",
12546 // constitutes a tentative definition. Note: A tentative definition with
12547 // external linkage is valid (C99 6.2.2p5).
12548 if (!Var->isInvalidDecl()) {
12549 if (const IncompleteArrayType *ArrayT
12550 = Context.getAsIncompleteArrayType(Type)) {
12551 if (RequireCompleteSizedType(
12552 Var->getLocation(), ArrayT->getElementType(),
12553 diag::err_array_incomplete_or_sizeless_type))
12554 Var->setInvalidDecl();
12555 } else if (Var->getStorageClass() == SC_Static) {
12556 // C99 6.9.2p3: If the declaration of an identifier for an object is
12557 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12558 // declared type shall not be an incomplete type.
12559 // NOTE: code such as the following
12560 // static struct s;
12561 // struct s { int a; };
12562 // is accepted by gcc. Hence here we issue a warning instead of
12563 // an error and we do not invalidate the static declaration.
12564 // NOTE: to avoid multiple warnings, only check the first declaration.
12565 if (Var->isFirstDecl())
12566 RequireCompleteType(Var->getLocation(), Type,
12567 diag::ext_typecheck_decl_incomplete_type);
12568 }
12569 }
12570
12571 // Record the tentative definition; we're done.
12572 if (!Var->isInvalidDecl())
12573 TentativeDefinitions.push_back(Var);
12574 return;
12575 }
12576
12577 // Provide a specific diagnostic for uninitialized variable
12578 // definitions with incomplete array type.
12579 if (Type->isIncompleteArrayType()) {
12580 Diag(Var->getLocation(),
12581 diag::err_typecheck_incomplete_array_needs_initializer);
12582 Var->setInvalidDecl();
12583 return;
12584 }
12585
12586 // Provide a specific diagnostic for uninitialized variable
12587 // definitions with reference type.
12588 if (Type->isReferenceType()) {
12589 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12590 << Var << SourceRange(Var->getLocation(), Var->getLocation());
12591 Var->setInvalidDecl();
12592 return;
12593 }
12594
12595 // Do not attempt to type-check the default initializer for a
12596 // variable with dependent type.
12597 if (Type->isDependentType())
12598 return;
12599
12600 if (Var->isInvalidDecl())
12601 return;
12602
12603 if (!Var->hasAttr<AliasAttr>()) {
12604 if (RequireCompleteType(Var->getLocation(),
12605 Context.getBaseElementType(Type),
12606 diag::err_typecheck_decl_incomplete_type)) {
12607 Var->setInvalidDecl();
12608 return;
12609 }
12610 } else {
12611 return;
12612 }
12613
12614 // The variable can not have an abstract class type.
12615 if (RequireNonAbstractType(Var->getLocation(), Type,
12616 diag::err_abstract_type_in_decl,
12617 AbstractVariableType)) {
12618 Var->setInvalidDecl();
12619 return;
12620 }
12621
12622 // Check for jumps past the implicit initializer. C++0x
12623 // clarifies that this applies to a "variable with automatic
12624 // storage duration", not a "local variable".
12625 // C++11 [stmt.dcl]p3
12626 // A program that jumps from a point where a variable with automatic
12627 // storage duration is not in scope to a point where it is in scope is
12628 // ill-formed unless the variable has scalar type, class type with a
12629 // trivial default constructor and a trivial destructor, a cv-qualified
12630 // version of one of these types, or an array of one of the preceding
12631 // types and is declared without an initializer.
12632 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12633 if (const RecordType *Record
12634 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12635 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12636 // Mark the function (if we're in one) for further checking even if the
12637 // looser rules of C++11 do not require such checks, so that we can
12638 // diagnose incompatibilities with C++98.
12639 if (!CXXRecord->isPOD())
12640 setFunctionHasBranchProtectedScope();
12641 }
12642 }
12643 // In OpenCL, we can't initialize objects in the __local address space,
12644 // even implicitly, so don't synthesize an implicit initializer.
12645 if (getLangOpts().OpenCL &&
12646 Var->getType().getAddressSpace() == LangAS::opencl_local)
12647 return;
12648 // C++03 [dcl.init]p9:
12649 // If no initializer is specified for an object, and the
12650 // object is of (possibly cv-qualified) non-POD class type (or
12651 // array thereof), the object shall be default-initialized; if
12652 // the object is of const-qualified type, the underlying class
12653 // type shall have a user-declared default
12654 // constructor. Otherwise, if no initializer is specified for
12655 // a non- static object, the object and its subobjects, if
12656 // any, have an indeterminate initial value); if the object
12657 // or any of its subobjects are of const-qualified type, the
12658 // program is ill-formed.
12659 // C++0x [dcl.init]p11:
12660 // If no initializer is specified for an object, the object is
12661 // default-initialized; [...].
12662 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12663 InitializationKind Kind
12664 = InitializationKind::CreateDefault(Var->getLocation());
12665
12666 InitializationSequence InitSeq(*this, Entity, Kind, None);
12667 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12668
12669 if (Init.get()) {
12670 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12671 // This is important for template substitution.
12672 Var->setInitStyle(VarDecl::CallInit);
12673 } else if (Init.isInvalid()) {
12674 // If default-init fails, attach a recovery-expr initializer to track
12675 // that initialization was attempted and failed.
12676 auto RecoveryExpr =
12677 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12678 if (RecoveryExpr.get())
12679 Var->setInit(RecoveryExpr.get());
12680 }
12681
12682 CheckCompleteVariableDeclaration(Var);
12683 }
12684}
12685
12686void Sema::ActOnCXXForRangeDecl(Decl *D) {
12687 // If there is no declaration, there was an error parsing it. Ignore it.
12688 if (!D)
12689 return;
12690
12691 VarDecl *VD = dyn_cast<VarDecl>(D);
12692 if (!VD) {
12693 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12694 D->setInvalidDecl();
12695 return;
12696 }
12697
12698 VD->setCXXForRangeDecl(true);
12699
12700 // for-range-declaration cannot be given a storage class specifier.
12701 int Error = -1;
12702 switch (VD->getStorageClass()) {
12703 case SC_None:
12704 break;
12705 case SC_Extern:
12706 Error = 0;
12707 break;
12708 case SC_Static:
12709 Error = 1;
12710 break;
12711 case SC_PrivateExtern:
12712 Error = 2;
12713 break;
12714 case SC_Auto:
12715 Error = 3;
12716 break;
12717 case SC_Register:
12718 Error = 4;
12719 break;
12720 }
12721 if (Error != -1) {
12722 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12723 << VD << Error;
12724 D->setInvalidDecl();
12725 }
12726}
12727
12728StmtResult
12729Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12730 IdentifierInfo *Ident,
12731 ParsedAttributes &Attrs,
12732 SourceLocation AttrEnd) {
12733 // C++1y [stmt.iter]p1:
12734 // A range-based for statement of the form
12735 // for ( for-range-identifier : for-range-initializer ) statement
12736 // is equivalent to
12737 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12738 DeclSpec DS(Attrs.getPool().getFactory());
12739
12740 const char *PrevSpec;
12741 unsigned DiagID;
12742 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12743 getPrintingPolicy());
12744
12745 Declarator D(DS, DeclaratorContext::ForContext);
12746 D.SetIdentifier(Ident, IdentLoc);
12747 D.takeAttributes(Attrs, AttrEnd);
12748
12749 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12750 IdentLoc);
12751 Decl *Var = ActOnDeclarator(S, D);
12752 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12753 FinalizeDeclaration(Var);
12754 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12755 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12756}
12757
12758void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12759 if (var->isInvalidDecl()) return;
12760
12761 if (getLangOpts().OpenCL) {
12762 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12763 // initialiser
12764 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12765 !var->hasInit()) {
12766 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12767 << 1 /*Init*/;
12768 var->setInvalidDecl();
12769 return;
12770 }
12771 }
12772
12773 // In Objective-C, don't allow jumps past the implicit initialization of a
12774 // local retaining variable.
12775 if (getLangOpts().ObjC &&
12776 var->hasLocalStorage()) {
12777 switch (var->getType().getObjCLifetime()) {
12778 case Qualifiers::OCL_None:
12779 case Qualifiers::OCL_ExplicitNone:
12780 case Qualifiers::OCL_Autoreleasing:
12781 break;
12782
12783 case Qualifiers::OCL_Weak:
12784 case Qualifiers::OCL_Strong:
12785 setFunctionHasBranchProtectedScope();
12786 break;
12787 }
12788 }
12789
12790 if (var->hasLocalStorage() &&
12791 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12792 setFunctionHasBranchProtectedScope();
12793
12794 // Warn about externally-visible variables being defined without a
12795 // prior declaration. We only want to do this for global
12796 // declarations, but we also specifically need to avoid doing it for
12797 // class members because the linkage of an anonymous class can
12798 // change if it's later given a typedef name.
12799 if (var->isThisDeclarationADefinition() &&
12800 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12801 var->isExternallyVisible() && var->hasLinkage() &&
12802 !var->isInline() && !var->getDescribedVarTemplate() &&
12803 !isa<VarTemplatePartialSpecializationDecl>(var) &&
12804 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12805 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12806 var->getLocation())) {
12807 // Find a previous declaration that's not a definition.
12808 VarDecl *prev = var->getPreviousDecl();
12809 while (prev && prev->isThisDeclarationADefinition())
12810 prev = prev->getPreviousDecl();
12811
12812 if (!prev) {
12813 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12814 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12815 << /* variable */ 0;
12816 }
12817 }
12818
12819 // Cache the result of checking for constant initialization.
12820 Optional<bool> CacheHasConstInit;
12821 const Expr *CacheCulprit = nullptr;
12822 auto checkConstInit = [&]() mutable {
12823 if (!CacheHasConstInit)
12824 CacheHasConstInit = var->getInit()->isConstantInitializer(
12825 Context, var->getType()->isReferenceType(), &CacheCulprit);
12826 return *CacheHasConstInit;
12827 };
12828
12829 if (var->getTLSKind() == VarDecl::TLS_Static) {
12830 if (var->getType().isDestructedType()) {
12831 // GNU C++98 edits for __thread, [basic.start.term]p3:
12832 // The type of an object with thread storage duration shall not
12833 // have a non-trivial destructor.
12834 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12835 if (getLangOpts().CPlusPlus11)
12836 Diag(var->getLocation(), diag::note_use_thread_local);
12837 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12838 if (!checkConstInit()) {
12839 // GNU C++98 edits for __thread, [basic.start.init]p4:
12840 // An object of thread storage duration shall not require dynamic
12841 // initialization.
12842 // FIXME: Need strict checking here.
12843 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12844 << CacheCulprit->getSourceRange();
12845 if (getLangOpts().CPlusPlus11)
12846 Diag(var->getLocation(), diag::note_use_thread_local);
12847 }
12848 }
12849 }
12850
12851 // Apply section attributes and pragmas to global variables.
12852 bool GlobalStorage = var->hasGlobalStorage();
12853 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12854 !inTemplateInstantiation()) {
12855 PragmaStack<StringLiteral *> *Stack = nullptr;
12856 int SectionFlags = ASTContext::PSF_Read;
12857 if (var->getType().isConstQualified())
12858 Stack = &ConstSegStack;
12859 else if (!var->getInit()) {
12860 Stack = &BSSSegStack;
12861 SectionFlags |= ASTContext::PSF_Write;
12862 } else {
12863 Stack = &DataSegStack;
12864 SectionFlags |= ASTContext::PSF_Write;
12865 }
12866 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12867 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12868 SectionFlags |= ASTContext::PSF_Implicit;
12869 UnifySection(SA->getName(), SectionFlags, var);
12870 } else if (Stack->CurrentValue) {
12871 SectionFlags |= ASTContext::PSF_Implicit;
12872 auto SectionName = Stack->CurrentValue->getString();
12873 var->addAttr(SectionAttr::CreateImplicit(
12874 Context, SectionName, Stack->CurrentPragmaLocation,
12875 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12876 if (UnifySection(SectionName, SectionFlags, var))
12877 var->dropAttr<SectionAttr>();
12878 }
12879
12880 // Apply the init_seg attribute if this has an initializer. If the
12881 // initializer turns out to not be dynamic, we'll end up ignoring this
12882 // attribute.
12883 if (CurInitSeg && var->getInit())
12884 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12885 CurInitSegLoc,
12886 AttributeCommonInfo::AS_Pragma));
12887 }
12888
12889 if (!var->getType()->isStructureType() && var->hasInit() &&
12890 isa<InitListExpr>(var->getInit())) {
12891 const auto *ILE = cast<InitListExpr>(var->getInit());
12892 unsigned NumInits = ILE->getNumInits();
12893 if (NumInits > 2)
12894 for (unsigned I = 0; I < NumInits; ++I) {
12895 const auto *Init = ILE->getInit(I);
12896 if (!Init)
12897 break;
12898 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12899 if (!SL)
12900 break;
12901
12902 unsigned NumConcat = SL->getNumConcatenated();
12903 // Diagnose missing comma in string array initialization.
12904 // Do not warn when all the elements in the initializer are concatenated
12905 // together. Do not warn for macros too.
12906 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
12907 bool OnlyOneMissingComma = true;
12908 for (unsigned J = I + 1; J < NumInits; ++J) {
12909 const auto *Init = ILE->getInit(J);
12910 if (!Init)
12911 break;
12912 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12913 if (!SLJ || SLJ->getNumConcatenated() > 1) {
12914 OnlyOneMissingComma = false;
12915 break;
12916 }
12917 }
12918
12919 if (OnlyOneMissingComma) {
12920 SmallVector<FixItHint, 1> Hints;
12921 for (unsigned i = 0; i < NumConcat - 1; ++i)
12922 Hints.push_back(FixItHint::CreateInsertion(
12923 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
12924
12925 Diag(SL->getStrTokenLoc(1),
12926 diag::warn_concatenated_literal_array_init)
12927 << Hints;
12928 Diag(SL->getBeginLoc(),
12929 diag::note_concatenated_string_literal_silence);
12930 }
12931 // In any case, stop now.
12932 break;
12933 }
12934 }
12935 }
12936
12937 // All the following checks are C++ only.
12938 if (!getLangOpts().CPlusPlus) {
12939 // If this variable must be emitted, add it as an initializer for the
12940 // current module.
12941 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12942 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12943 return;
12944 }
12945
12946 if (auto *DD = dyn_cast<DecompositionDecl>(var))
12947 CheckCompleteDecompositionDeclaration(DD);
12948
12949 QualType type = var->getType();
12950 if (type->isDependentType()) return;
12951
12952 if (var->hasAttr<BlocksAttr>())
12953 getCurFunction()->addByrefBlockVar(var);
12954
12955 Expr *Init = var->getInit();
12956 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12957 QualType baseType = Context.getBaseElementType(type);
12958
12959 if (Init && !Init->isValueDependent()) {
12960 if (var->isConstexpr()) {
12961 SmallVector<PartialDiagnosticAt, 8> Notes;
12962 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12963 SourceLocation DiagLoc = var->getLocation();
12964 // If the note doesn't add any useful information other than a source
12965 // location, fold it into the primary diagnostic.
12966 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12967 diag::note_invalid_subexpr_in_const_expr) {
12968 DiagLoc = Notes[0].first;
12969 Notes.clear();
12970 }
12971 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12972 << var << Init->getSourceRange();
12973 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12974 Diag(Notes[I].first, Notes[I].second);
12975 }
12976 } else if (var->mightBeUsableInConstantExpressions(Context)) {
12977 // Check whether the initializer of a const variable of integral or
12978 // enumeration type is an ICE now, since we can't tell whether it was
12979 // initialized by a constant expression if we check later.
12980 var->checkInitIsICE();
12981 }
12982
12983 // Don't emit further diagnostics about constexpr globals since they
12984 // were just diagnosed.
12985 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12986 // FIXME: Need strict checking in C++03 here.
12987 bool DiagErr = getLangOpts().CPlusPlus11
12988 ? !var->checkInitIsICE() : !checkConstInit();
12989 if (DiagErr) {
12990 auto *Attr = var->getAttr<ConstInitAttr>();
12991 Diag(var->getLocation(), diag::err_require_constant_init_failed)
12992 << Init->getSourceRange();
12993 Diag(Attr->getLocation(),
12994 diag::note_declared_required_constant_init_here)
12995 << Attr->getRange() << Attr->isConstinit();
12996 if (getLangOpts().CPlusPlus11) {
12997 APValue Value;
12998 SmallVector<PartialDiagnosticAt, 8> Notes;
12999 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
13000 for (auto &it : Notes)
13001 Diag(it.first, it.second);
13002 } else {
13003 Diag(CacheCulprit->getExprLoc(),
13004 diag::note_invalid_subexpr_in_const_expr)
13005 << CacheCulprit->getSourceRange();
13006 }
13007 }
13008 }
13009 else if (!var->isConstexpr() && IsGlobal &&
13010 !getDiagnostics().isIgnored(diag::warn_global_constructor,
13011 var->getLocation())) {
13012 // Warn about globals which don't have a constant initializer. Don't
13013 // warn about globals with a non-trivial destructor because we already
13014 // warned about them.
13015 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13016 if (!(RD && !RD->hasTrivialDestructor())) {
13017 if (!checkConstInit())
13018 Diag(var->getLocation(), diag::warn_global_constructor)
13019 << Init->getSourceRange();
13020 }
13021 }
13022 }
13023
13024 // Require the destructor.
13025 if (const RecordType *recordType = baseType->getAs<RecordType>())
13026 FinalizeVarWithDestructor(var, recordType);
13027
13028 // If this variable must be emitted, add it as an initializer for the current
13029 // module.
13030 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13031 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13032}
13033
13034/// Determines if a variable's alignment is dependent.
13035static bool hasDependentAlignment(VarDecl *VD) {
13036 if (VD->getType()->isDependentType())
13037 return true;
13038 for (auto *I : VD->specific_attrs<AlignedAttr>())
13039 if (I->isAlignmentDependent())
13040 return true;
13041 return false;
13042}
13043
13044/// Check if VD needs to be dllexport/dllimport due to being in a
13045/// dllexport/import function.
13046void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13047 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 13047, __PRETTY_FUNCTION__))
;
13048
13049 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13050
13051 // Find outermost function when VD is in lambda function.
13052 while (FD && !getDLLAttr(FD) &&
13053 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13054 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13055 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13056 }
13057
13058 if (!FD)
13059 return;
13060
13061 // Static locals inherit dll attributes from their function.
13062 if (Attr *A = getDLLAttr(FD)) {
13063 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13064 NewAttr->setInherited(true);
13065 VD->addAttr(NewAttr);
13066 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13067 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13068 NewAttr->setInherited(true);
13069 VD->addAttr(NewAttr);
13070
13071 // Export this function to enforce exporting this static variable even
13072 // if it is not used in this compilation unit.
13073 if (!FD->hasAttr<DLLExportAttr>())
13074 FD->addAttr(NewAttr);
13075
13076 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13077 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13078 NewAttr->setInherited(true);
13079 VD->addAttr(NewAttr);
13080 }
13081}
13082
13083/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13084/// any semantic actions necessary after any initializer has been attached.
13085void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13086 // Note that we are no longer parsing the initializer for this declaration.
13087 ParsingInitForAutoVars.erase(ThisDecl);
13088
13089 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13090 if (!VD)
13091 return;
13092
13093 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13094 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13095 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13096 if (PragmaClangBSSSection.Valid)
13097 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13098 Context, PragmaClangBSSSection.SectionName,
13099 PragmaClangBSSSection.PragmaLocation,
13100 AttributeCommonInfo::AS_Pragma));
13101 if (PragmaClangDataSection.Valid)
13102 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13103 Context, PragmaClangDataSection.SectionName,
13104 PragmaClangDataSection.PragmaLocation,
13105 AttributeCommonInfo::AS_Pragma));
13106 if (PragmaClangRodataSection.Valid)
13107 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13108 Context, PragmaClangRodataSection.SectionName,
13109 PragmaClangRodataSection.PragmaLocation,
13110 AttributeCommonInfo::AS_Pragma));
13111 if (PragmaClangRelroSection.Valid)
13112 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13113 Context, PragmaClangRelroSection.SectionName,
13114 PragmaClangRelroSection.PragmaLocation,
13115 AttributeCommonInfo::AS_Pragma));
13116 }
13117
13118 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13119 for (auto *BD : DD->bindings()) {
13120 FinalizeDeclaration(BD);
13121 }
13122 }
13123
13124 checkAttributesAfterMerging(*this, *VD);
13125
13126 // Perform TLS alignment check here after attributes attached to the variable
13127 // which may affect the alignment have been processed. Only perform the check
13128 // if the target has a maximum TLS alignment (zero means no constraints).
13129 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13130 // Protect the check so that it's not performed on dependent types and
13131 // dependent alignments (we can't determine the alignment in that case).
13132 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13133 !VD->isInvalidDecl()) {
13134 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13135 if (Context.getDeclAlign(VD) > MaxAlignChars) {
13136 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13137 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13138 << (unsigned)MaxAlignChars.getQuantity();
13139 }
13140 }
13141 }
13142
13143 if (VD->isStaticLocal()) {
13144 CheckStaticLocalForDllExport(VD);
13145
13146 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13147 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13148 // function, only __shared__ variables or variables without any device
13149 // memory qualifiers may be declared with static storage class.
13150 // Note: It is unclear how a function-scope non-const static variable
13151 // without device memory qualifier is implemented, therefore only static
13152 // const variable without device memory qualifier is allowed.
13153 [&]() {
13154 if (!getLangOpts().CUDA)
13155 return;
13156 if (VD->hasAttr<CUDASharedAttr>())
13157 return;
13158 if (VD->getType().isConstQualified() &&
13159 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13160 return;
13161 if (CUDADiagIfDeviceCode(VD->getLocation(),
13162 diag::err_device_static_local_var)
13163 << CurrentCUDATarget())
13164 VD->setInvalidDecl();
13165 }();
13166 }
13167 }
13168
13169 // Perform check for initializers of device-side global variables.
13170 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13171 // 7.5). We must also apply the same checks to all __shared__
13172 // variables whether they are local or not. CUDA also allows
13173 // constant initializers for __constant__ and __device__ variables.
13174 if (getLangOpts().CUDA)
13175 checkAllowedCUDAInitializer(VD);
13176
13177 // Grab the dllimport or dllexport attribute off of the VarDecl.
13178 const InheritableAttr *DLLAttr = getDLLAttr(VD);
13179
13180 // Imported static data members cannot be defined out-of-line.
13181 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13182 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13183 VD->isThisDeclarationADefinition()) {
13184 // We allow definitions of dllimport class template static data members
13185 // with a warning.
13186 CXXRecordDecl *Context =
13187 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13188 bool IsClassTemplateMember =
13189 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13190 Context->getDescribedClassTemplate();
13191
13192 Diag(VD->getLocation(),
13193 IsClassTemplateMember
13194 ? diag::warn_attribute_dllimport_static_field_definition
13195 : diag::err_attribute_dllimport_static_field_definition);
13196 Diag(IA->getLocation(), diag::note_attribute);
13197 if (!IsClassTemplateMember)
13198 VD->setInvalidDecl();
13199 }
13200 }
13201
13202 // dllimport/dllexport variables cannot be thread local, their TLS index
13203 // isn't exported with the variable.
13204 if (DLLAttr && VD->getTLSKind()) {
13205 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13206 if (F && getDLLAttr(F)) {
13207 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 13207, __PRETTY_FUNCTION__))
;
13208 // But if this is a static local in a dlimport/dllexport function, the
13209 // function will never be inlined, which means the var would never be
13210 // imported, so having it marked import/export is safe.
13211 } else {
13212 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13213 << DLLAttr;
13214 VD->setInvalidDecl();
13215 }
13216 }
13217
13218 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13219 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13220 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13221 VD->dropAttr<UsedAttr>();
13222 }
13223 }
13224
13225 const DeclContext *DC = VD->getDeclContext();
13226 // If there's a #pragma GCC visibility in scope, and this isn't a class
13227 // member, set the visibility of this variable.
13228 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13229 AddPushedVisibilityAttribute(VD);
13230
13231 // FIXME: Warn on unused var template partial specializations.
13232 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13233 MarkUnusedFileScopedDecl(VD);
13234
13235 // Now we have parsed the initializer and can update the table of magic
13236 // tag values.
13237 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13238 !VD->getType()->isIntegralOrEnumerationType())
13239 return;
13240
13241 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13242 const Expr *MagicValueExpr = VD->getInit();
13243 if (!MagicValueExpr) {
13244 continue;
13245 }
13246 Optional<llvm::APSInt> MagicValueInt;
13247 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13248 Diag(I->getRange().getBegin(),
13249 diag::err_type_tag_for_datatype_not_ice)
13250 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13251 continue;
13252 }
13253 if (MagicValueInt->getActiveBits() > 64) {
13254 Diag(I->getRange().getBegin(),
13255 diag::err_type_tag_for_datatype_too_large)
13256 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13257 continue;
13258 }
13259 uint64_t MagicValue = MagicValueInt->getZExtValue();
13260 RegisterTypeTagForDatatype(I->getArgumentKind(),
13261 MagicValue,
13262 I->getMatchingCType(),
13263 I->getLayoutCompatible(),
13264 I->getMustBeNull());
13265 }
13266}
13267
13268static bool hasDeducedAuto(DeclaratorDecl *DD) {
13269 auto *VD = dyn_cast<VarDecl>(DD);
13270 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13271}
13272
13273Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13274 ArrayRef<Decl *> Group) {
13275 SmallVector<Decl*, 8> Decls;
13276
13277 if (DS.isTypeSpecOwned())
13278 Decls.push_back(DS.getRepAsDecl());
13279
13280 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13281 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13282 bool DiagnosedMultipleDecomps = false;
13283 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13284 bool DiagnosedNonDeducedAuto = false;
13285
13286 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13287 if (Decl *D = Group[i]) {
13288 // For declarators, there are some additional syntactic-ish checks we need
13289 // to perform.
13290 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13291 if (!FirstDeclaratorInGroup)
13292 FirstDeclaratorInGroup = DD;
13293 if (!FirstDecompDeclaratorInGroup)
13294 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13295 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13296 !hasDeducedAuto(DD))
13297 FirstNonDeducedAutoInGroup = DD;
13298
13299 if (FirstDeclaratorInGroup != DD) {
13300 // A decomposition declaration cannot be combined with any other
13301 // declaration in the same group.
13302 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13303 Diag(FirstDecompDeclaratorInGroup->getLocation(),
13304 diag::err_decomp_decl_not_alone)
13305 << FirstDeclaratorInGroup->getSourceRange()
13306 << DD->getSourceRange();
13307 DiagnosedMultipleDecomps = true;
13308 }
13309
13310 // A declarator that uses 'auto' in any way other than to declare a
13311 // variable with a deduced type cannot be combined with any other
13312 // declarator in the same group.
13313 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13314 Diag(FirstNonDeducedAutoInGroup->getLocation(),
13315 diag::err_auto_non_deduced_not_alone)
13316 << FirstNonDeducedAutoInGroup->getType()
13317 ->hasAutoForTrailingReturnType()
13318 << FirstDeclaratorInGroup->getSourceRange()
13319 << DD->getSourceRange();
13320 DiagnosedNonDeducedAuto = true;
13321 }
13322 }
13323 }
13324
13325 Decls.push_back(D);
13326 }
13327 }
13328
13329 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13330 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13331 handleTagNumbering(Tag, S);
13332 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13333 getLangOpts().CPlusPlus)
13334 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13335 }
13336 }
13337
13338 return BuildDeclaratorGroup(Decls);
13339}
13340
13341/// BuildDeclaratorGroup - convert a list of declarations into a declaration
13342/// group, performing any necessary semantic checking.
13343Sema::DeclGroupPtrTy
13344Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13345 // C++14 [dcl.spec.auto]p7: (DR1347)
13346 // If the type that replaces the placeholder type is not the same in each
13347 // deduction, the program is ill-formed.
13348 if (Group.size() > 1) {
13349 QualType Deduced;
13350 VarDecl *DeducedDecl = nullptr;
13351 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13352 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13353 if (!D || D->isInvalidDecl())
13354 break;
13355 DeducedType *DT = D->getType()->getContainedDeducedType();
13356 if (!DT || DT->getDeducedType().isNull())
13357 continue;
13358 if (Deduced.isNull()) {
13359 Deduced = DT->getDeducedType();
13360 DeducedDecl = D;
13361 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13362 auto *AT = dyn_cast<AutoType>(DT);
13363 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13364 diag::err_auto_different_deductions)
13365 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13366 << DeducedDecl->getDeclName() << DT->getDeducedType()
13367 << D->getDeclName();
13368 if (DeducedDecl->hasInit())
13369 Dia << DeducedDecl->getInit()->getSourceRange();
13370 if (D->getInit())
13371 Dia << D->getInit()->getSourceRange();
13372 D->setInvalidDecl();
13373 break;
13374 }
13375 }
13376 }
13377
13378 ActOnDocumentableDecls(Group);
13379
13380 return DeclGroupPtrTy::make(
13381 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13382}
13383
13384void Sema::ActOnDocumentableDecl(Decl *D) {
13385 ActOnDocumentableDecls(D);
13386}
13387
13388void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13389 // Don't parse the comment if Doxygen diagnostics are ignored.
13390 if (Group.empty() || !Group[0])
13391 return;
13392
13393 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13394 Group[0]->getLocation()) &&
13395 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13396 Group[0]->getLocation()))
13397 return;
13398
13399 if (Group.size() >= 2) {
13400 // This is a decl group. Normally it will contain only declarations
13401 // produced from declarator list. But in case we have any definitions or
13402 // additional declaration references:
13403 // 'typedef struct S {} S;'
13404 // 'typedef struct S *S;'
13405 // 'struct S *pS;'
13406 // FinalizeDeclaratorGroup adds these as separate declarations.
13407 Decl *MaybeTagDecl = Group[0];
13408 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13409 Group = Group.slice(1);
13410 }
13411 }
13412
13413 // FIMXE: We assume every Decl in the group is in the same file.
13414 // This is false when preprocessor constructs the group from decls in
13415 // different files (e. g. macros or #include).
13416 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13417}
13418
13419/// Common checks for a parameter-declaration that should apply to both function
13420/// parameters and non-type template parameters.
13421void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13422 // Check that there are no default arguments inside the type of this
13423 // parameter.
13424 if (getLangOpts().CPlusPlus)
13425 CheckExtraCXXDefaultArguments(D);
13426
13427 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13428 if (D.getCXXScopeSpec().isSet()) {
13429 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13430 << D.getCXXScopeSpec().getRange();
13431 }
13432
13433 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13434 // simple identifier except [...irrelevant cases...].
13435 switch (D.getName().getKind()) {
13436 case UnqualifiedIdKind::IK_Identifier:
13437 break;
13438
13439 case UnqualifiedIdKind::IK_OperatorFunctionId:
13440 case UnqualifiedIdKind::IK_ConversionFunctionId:
13441 case UnqualifiedIdKind::IK_LiteralOperatorId:
13442 case UnqualifiedIdKind::IK_ConstructorName:
13443 case UnqualifiedIdKind::IK_DestructorName:
13444 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13445 case UnqualifiedIdKind::IK_DeductionGuideName:
13446 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13447 << GetNameForDeclarator(D).getName();
13448 break;
13449
13450 case UnqualifiedIdKind::IK_TemplateId:
13451 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13452 // GetNameForDeclarator would not produce a useful name in this case.
13453 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13454 break;
13455 }
13456}
13457
13458/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13459/// to introduce parameters into function prototype scope.
13460Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13461 const DeclSpec &DS = D.getDeclSpec();
13462
13463 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13464
13465 // C++03 [dcl.stc]p2 also permits 'auto'.
13466 StorageClass SC = SC_None;
13467 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13468 SC = SC_Register;
13469 // In C++11, the 'register' storage class specifier is deprecated.
13470 // In C++17, it is not allowed, but we tolerate it as an extension.
13471 if (getLangOpts().CPlusPlus11) {
13472 Diag(DS.getStorageClassSpecLoc(),
13473 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13474 : diag::warn_deprecated_register)
13475 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13476 }
13477 } else if (getLangOpts().CPlusPlus &&
13478 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13479 SC = SC_Auto;
13480 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13481 Diag(DS.getStorageClassSpecLoc(),
13482 diag::err_invalid_storage_class_in_func_decl);
13483 D.getMutableDeclSpec().ClearStorageClassSpecs();
13484 }
13485
13486 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13487 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13488 << DeclSpec::getSpecifierName(TSCS);
13489 if (DS.isInlineSpecified())
13490 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13491 << getLangOpts().CPlusPlus17;
13492 if (DS.hasConstexprSpecifier())
13493 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13494 << 0 << D.getDeclSpec().getConstexprSpecifier();
13495
13496 DiagnoseFunctionSpecifiers(DS);
13497
13498 CheckFunctionOrTemplateParamDeclarator(S, D);
13499
13500 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13501 QualType parmDeclType = TInfo->getType();
13502
13503 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13504 IdentifierInfo *II = D.getIdentifier();
13505 if (II) {
13506 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13507 ForVisibleRedeclaration);
13508 LookupName(R, S);
13509 if (R.isSingleResult()) {
13510 NamedDecl *PrevDecl = R.getFoundDecl();
13511 if (PrevDecl->isTemplateParameter()) {
13512 // Maybe we will complain about the shadowed template parameter.
13513 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13514 // Just pretend that we didn't see the previous declaration.
13515 PrevDecl = nullptr;
13516 } else if (S->isDeclScope(PrevDecl)) {
13517 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13518 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13519
13520 // Recover by removing the name
13521 II = nullptr;
13522 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13523 D.setInvalidType(true);
13524 }
13525 }
13526 }
13527
13528 // Temporarily put parameter variables in the translation unit, not
13529 // the enclosing context. This prevents them from accidentally
13530 // looking like class members in C++.
13531 ParmVarDecl *New =
13532 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13533 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13534
13535 if (D.isInvalidType())
13536 New->setInvalidDecl();
13537
13538 assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void>
(0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 13538, __PRETTY_FUNCTION__))
;
13539 assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast<
void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 13539, __PRETTY_FUNCTION__))
;
13540 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13541 S->getNextFunctionPrototypeIndex());
13542
13543 // Add the parameter declaration into this scope.
13544 S->AddDecl(New);
13545 if (II)
13546 IdResolver.AddDecl(New);
13547
13548 ProcessDeclAttributes(S, New, D);
13549
13550 if (D.getDeclSpec().isModulePrivateSpecified())
13551 Diag(New->getLocation(), diag::err_module_private_local)
13552 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13553 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13554
13555 if (New->hasAttr<BlocksAttr>()) {
13556 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13557 }
13558
13559 if (getLangOpts().OpenCL)
13560 deduceOpenCLAddressSpace(New);
13561
13562 return New;
13563}
13564
13565/// Synthesizes a variable for a parameter arising from a
13566/// typedef.
13567ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13568 SourceLocation Loc,
13569 QualType T) {
13570 /* FIXME: setting StartLoc == Loc.
13571 Would it be worth to modify callers so as to provide proper source
13572 location for the unnamed parameters, embedding the parameter's type? */
13573 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13574 T, Context.getTrivialTypeSourceInfo(T, Loc),
13575 SC_None, nullptr);
13576 Param->setImplicit();
13577 return Param;
13578}
13579
13580void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13581 // Don't diagnose unused-parameter errors in template instantiations; we
13582 // will already have done so in the template itself.
13583 if (inTemplateInstantiation())
13584 return;
13585
13586 for (const ParmVarDecl *Parameter : Parameters) {
13587 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13588 !Parameter->hasAttr<UnusedAttr>()) {
13589 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13590 << Parameter->getDeclName();
13591 }
13592 }
13593}
13594
13595void Sema::DiagnoseSizeOfParametersAndReturnValue(
13596 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13597 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13598 return;
13599
13600 // Warn if the return value is pass-by-value and larger than the specified
13601 // threshold.
13602 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13603 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13604 if (Size > LangOpts.NumLargeByValueCopy)
13605 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13606 }
13607
13608 // Warn if any parameter is pass-by-value and larger than the specified
13609 // threshold.
13610 for (const ParmVarDecl *Parameter : Parameters) {
13611 QualType T = Parameter->getType();
13612 if (T->isDependentType() || !T.isPODType(Context))
13613 continue;
13614 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13615 if (Size > LangOpts.NumLargeByValueCopy)
13616 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13617 << Parameter << Size;
13618 }
13619}
13620
13621ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13622 SourceLocation NameLoc, IdentifierInfo *Name,
13623 QualType T, TypeSourceInfo *TSInfo,
13624 StorageClass SC) {
13625 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13626 if (getLangOpts().ObjCAutoRefCount &&
13627 T.getObjCLifetime() == Qualifiers::OCL_None &&
13628 T->isObjCLifetimeType()) {
13629
13630 Qualifiers::ObjCLifetime lifetime;
13631
13632 // Special cases for arrays:
13633 // - if it's const, use __unsafe_unretained
13634 // - otherwise, it's an error
13635 if (T->isArrayType()) {
13636 if (!T.isConstQualified()) {
13637 if (DelayedDiagnostics.shouldDelayDiagnostics())
13638 DelayedDiagnostics.add(
13639 sema::DelayedDiagnostic::makeForbiddenType(
13640 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13641 else
13642 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13643 << TSInfo->getTypeLoc().getSourceRange();
13644 }
13645 lifetime = Qualifiers::OCL_ExplicitNone;
13646 } else {
13647 lifetime = T->getObjCARCImplicitLifetime();
13648 }
13649 T = Context.getLifetimeQualifiedType(T, lifetime);
13650 }
13651
13652 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13653 Context.getAdjustedParameterType(T),
13654 TSInfo, SC, nullptr);
13655
13656 // Make a note if we created a new pack in the scope of a lambda, so that
13657 // we know that references to that pack must also be expanded within the
13658 // lambda scope.
13659 if (New->isParameterPack())
13660 if (auto *LSI = getEnclosingLambda())
13661 LSI->LocalPacks.push_back(New);
13662
13663 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13664 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13665 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13666 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13667
13668 // Parameters can not be abstract class types.
13669 // For record types, this is done by the AbstractClassUsageDiagnoser once
13670 // the class has been completely parsed.
13671 if (!CurContext->isRecord() &&
13672 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13673 AbstractParamType))
13674 New->setInvalidDecl();
13675
13676 // Parameter declarators cannot be interface types. All ObjC objects are
13677 // passed by reference.
13678 if (T->isObjCObjectType()) {
13679 SourceLocation TypeEndLoc =
13680 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13681 Diag(NameLoc,
13682 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13683 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13684 T = Context.getObjCObjectPointerType(T);
13685 New->setType(T);
13686 }
13687
13688 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13689 // duration shall not be qualified by an address-space qualifier."
13690 // Since all parameters have automatic store duration, they can not have
13691 // an address space.
13692 if (T.getAddressSpace() != LangAS::Default &&
13693 // OpenCL allows function arguments declared to be an array of a type
13694 // to be qualified with an address space.
13695 !(getLangOpts().OpenCL &&
13696 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13697 Diag(NameLoc, diag::err_arg_with_address_space);
13698 New->setInvalidDecl();
13699 }
13700
13701 return New;
13702}
13703
13704void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13705 SourceLocation LocAfterDecls) {
13706 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13707
13708 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13709 // for a K&R function.
13710 if (!FTI.hasPrototype) {
13711 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13712 --i;
13713 if (FTI.Params[i].Param == nullptr) {
13714 SmallString<256> Code;
13715 llvm::raw_svector_ostream(Code)
13716 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13717 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13718 << FTI.Params[i].Ident
13719 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13720
13721 // Implicitly declare the argument as type 'int' for lack of a better
13722 // type.
13723 AttributeFactory attrs;
13724 DeclSpec DS(attrs);
13725 const char* PrevSpec; // unused
13726 unsigned DiagID; // unused
13727 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13728 DiagID, Context.getPrintingPolicy());
13729 // Use the identifier location for the type source range.
13730 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13731 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13732 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13733 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13734 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13735 }
13736 }
13737 }
13738}
13739
13740Decl *
13741Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13742 MultiTemplateParamsArg TemplateParameterLists,
13743 SkipBodyInfo *SkipBody) {
13744 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused"
) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 13744, __PRETTY_FUNCTION__))
;
13745 assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!"
) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 13745, __PRETTY_FUNCTION__))
;
13746 Scope *ParentScope = FnBodyScope->getParent();
13747
13748 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13749 // we define a non-templated function definition, we will create a declaration
13750 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13751 // The base function declaration will have the equivalent of an `omp declare
13752 // variant` annotation which specifies the mangled definition as a
13753 // specialization function under the OpenMP context defined as part of the
13754 // `omp begin declare variant`.
13755 SmallVector<FunctionDecl *, 4> Bases;
13756 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13757 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13758 ParentScope, D, TemplateParameterLists, Bases);
13759
13760 D.setFunctionDefinitionKind(FDK_Definition);
13761 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13762 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13763
13764 if (!Bases.empty())
13765 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13766
13767 return Dcl;
13768}
13769
13770void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13771 Consumer.HandleInlineFunctionDefinition(D);
13772}
13773
13774static bool
13775ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13776 const FunctionDecl *&PossiblePrototype) {
13777 // Don't warn about invalid declarations.
13778 if (FD->isInvalidDecl())
13779 return false;
13780
13781 // Or declarations that aren't global.
13782 if (!FD->isGlobal())
13783 return false;
13784
13785 // Don't warn about C++ member functions.
13786 if (isa<CXXMethodDecl>(FD))
13787 return false;
13788
13789 // Don't warn about 'main'.
13790 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13791 if (IdentifierInfo *II = FD->getIdentifier())
13792 if (II->isStr("main"))
13793 return false;
13794
13795 // Don't warn about inline functions.
13796 if (FD->isInlined())
13797 return false;
13798
13799 // Don't warn about function templates.
13800 if (FD->getDescribedFunctionTemplate())
13801 return false;
13802
13803 // Don't warn about function template specializations.
13804 if (FD->isFunctionTemplateSpecialization())
13805 return false;
13806
13807 // Don't warn for OpenCL kernels.
13808 if (FD->hasAttr<OpenCLKernelAttr>())
13809 return false;
13810
13811 // Don't warn on explicitly deleted functions.
13812 if (FD->isDeleted())
13813 return false;
13814
13815 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13816 Prev; Prev = Prev->getPreviousDecl()) {
13817 // Ignore any declarations that occur in function or method
13818 // scope, because they aren't visible from the header.
13819 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13820 continue;
13821
13822 PossiblePrototype = Prev;
13823 return Prev->getType()->isFunctionNoProtoType();
13824 }
13825
13826 return true;
13827}
13828
13829void
13830Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13831 const FunctionDecl *EffectiveDefinition,
13832 SkipBodyInfo *SkipBody) {
13833 const FunctionDecl *Definition = EffectiveDefinition;
13834 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13835 // If this is a friend function defined in a class template, it does not
13836 // have a body until it is used, nevertheless it is a definition, see
13837 // [temp.inst]p2:
13838 //
13839 // ... for the purpose of determining whether an instantiated redeclaration
13840 // is valid according to [basic.def.odr] and [class.mem], a declaration that
13841 // corresponds to a definition in the template is considered to be a
13842 // definition.
13843 //
13844 // The following code must produce redefinition error:
13845 //
13846 // template<typename T> struct C20 { friend void func_20() {} };
13847 // C20<int> c20i;
13848 // void func_20() {}
13849 //
13850 for (auto I : FD->redecls()) {
13851 if (I != FD && !I->isInvalidDecl() &&
13852 I->getFriendObjectKind() != Decl::FOK_None) {
13853 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13854 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13855 // A merged copy of the same function, instantiated as a member of
13856 // the same class, is OK.
13857 if (declaresSameEntity(OrigFD, Original) &&
13858 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13859 cast<Decl>(FD->getLexicalDeclContext())))
13860 continue;
13861 }
13862
13863 if (Original->isThisDeclarationADefinition()) {
13864 Definition = I;
13865 break;
13866 }
13867 }
13868 }
13869 }
13870 }
13871
13872 if (!Definition)
13873 // Similar to friend functions a friend function template may be a
13874 // definition and do not have a body if it is instantiated in a class
13875 // template.
13876 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13877 for (auto I : FTD->redecls()) {
13878 auto D = cast<FunctionTemplateDecl>(I);
13879 if (D != FTD) {
13880 assert(!D->isThisDeclarationADefinition() &&((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 13881, __PRETTY_FUNCTION__))
13881 "More than one definition in redeclaration chain")((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 13881, __PRETTY_FUNCTION__))
;
13882 if (D->getFriendObjectKind() != Decl::FOK_None)
13883 if (FunctionTemplateDecl *FT =
13884 D->getInstantiatedFromMemberTemplate()) {
13885 if (FT->isThisDeclarationADefinition()) {
13886 Definition = D->getTemplatedDecl();
13887 break;
13888 }
13889 }
13890 }
13891 }
13892 }
13893
13894 if (!Definition)
13895 return;
13896
13897 if (canRedefineFunction(Definition, getLangOpts()))
13898 return;
13899
13900 // Don't emit an error when this is redefinition of a typo-corrected
13901 // definition.
13902 if (TypoCorrectedFunctionDefinitions.count(Definition))
13903 return;
13904
13905 // If we don't have a visible definition of the function, and it's inline or
13906 // a template, skip the new definition.
13907 if (SkipBody && !hasVisibleDefinition(Definition) &&
13908 (Definition->getFormalLinkage() == InternalLinkage ||
13909 Definition->isInlined() ||
13910 Definition->getDescribedFunctionTemplate() ||
13911 Definition->getNumTemplateParameterLists())) {
13912 SkipBody->ShouldSkip = true;
13913 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13914 if (auto *TD = Definition->getDescribedFunctionTemplate())
13915 makeMergedDefinitionVisible(TD);
13916 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13917 return;
13918 }
13919
13920 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13921 Definition->getStorageClass() == SC_Extern)
13922 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13923 << FD << getLangOpts().CPlusPlus;
13924 else
13925 Diag(FD->getLocation(), diag::err_redefinition) << FD;
13926
13927 Diag(Definition->getLocation(), diag::note_previous_definition);
13928 FD->setInvalidDecl();
13929}
13930
13931static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13932 Sema &S) {
13933 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13934
13935 LambdaScopeInfo *LSI = S.PushLambdaScope();
13936 LSI->CallOperator = CallOperator;
13937 LSI->Lambda = LambdaClass;
13938 LSI->ReturnType = CallOperator->getReturnType();
13939 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13940
13941 if (LCD == LCD_None)
13942 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13943 else if (LCD == LCD_ByCopy)
13944 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13945 else if (LCD == LCD_ByRef)
13946 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13947 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13948
13949 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13950 LSI->Mutable = !CallOperator->isConst();
13951
13952 // Add the captures to the LSI so they can be noted as already
13953 // captured within tryCaptureVar.
13954 auto I = LambdaClass->field_begin();
13955 for (const auto &C : LambdaClass->captures()) {
13956 if (C.capturesVariable()) {
13957 VarDecl *VD = C.getCapturedVar();
13958 if (VD->isInitCapture())
13959 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13960 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13961 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13962 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13963 /*EllipsisLoc*/C.isPackExpansion()
13964 ? C.getEllipsisLoc() : SourceLocation(),
13965 I->getType(), /*Invalid*/false);
13966
13967 } else if (C.capturesThis()) {
13968 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13969 C.getCaptureKind() == LCK_StarThis);
13970 } else {
13971 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13972 I->getType());
13973 }
13974 ++I;
13975 }
13976}
13977
13978Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13979 SkipBodyInfo *SkipBody) {
13980 if (!D) {
13981 // Parsing the function declaration failed in some way. Push on a fake scope
13982 // anyway so we can try to parse the function body.
13983 PushFunctionScope();
13984 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13985 return D;
13986 }
13987
13988 FunctionDecl *FD = nullptr;
13989
13990 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13991 FD = FunTmpl->getTemplatedDecl();
13992 else
13993 FD = cast<FunctionDecl>(D);
13994
13995 // Do not push if it is a lambda because one is already pushed when building
13996 // the lambda in ActOnStartOfLambdaDefinition().
13997 if (!isLambdaCallOperator(FD))
13998 PushExpressionEvaluationContext(
13999 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14000 : ExprEvalContexts.back().Context);
14001
14002 // Check for defining attributes before the check for redefinition.
14003 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14004 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14005 FD->dropAttr<AliasAttr>();
14006 FD->setInvalidDecl();
14007 }
14008 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14009 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14010 FD->dropAttr<IFuncAttr>();
14011 FD->setInvalidDecl();
14012 }
14013
14014 // See if this is a redefinition. If 'will have body' is already set, then
14015 // these checks were already performed when it was set.
14016 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
14017 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14018
14019 // If we're skipping the body, we're done. Don't enter the scope.
14020 if (SkipBody && SkipBody->ShouldSkip)
14021 return D;
14022 }
14023
14024 // Mark this function as "will have a body eventually". This lets users to
14025 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14026 // this function.
14027 FD->setWillHaveBody();
14028
14029 // If we are instantiating a generic lambda call operator, push
14030 // a LambdaScopeInfo onto the function stack. But use the information
14031 // that's already been calculated (ActOnLambdaExpr) to prime the current
14032 // LambdaScopeInfo.
14033 // When the template operator is being specialized, the LambdaScopeInfo,
14034 // has to be properly restored so that tryCaptureVariable doesn't try
14035 // and capture any new variables. In addition when calculating potential
14036 // captures during transformation of nested lambdas, it is necessary to
14037 // have the LSI properly restored.
14038 if (isGenericLambdaCallOperatorSpecialization(FD)) {
14039 assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14041, __PRETTY_FUNCTION__))
14040 "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14041, __PRETTY_FUNCTION__))
14041 "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? static_cast<void
> (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14041, __PRETTY_FUNCTION__))
;
14042 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14043 } else {
14044 // Enter a new function scope
14045 PushFunctionScope();
14046 }
14047
14048 // Builtin functions cannot be defined.
14049 if (unsigned BuiltinID = FD->getBuiltinID()) {
14050 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14051 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14052 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14053 FD->setInvalidDecl();
14054 }
14055 }
14056
14057 // The return type of a function definition must be complete
14058 // (C99 6.9.1p3, C++ [dcl.fct]p6).
14059 QualType ResultType = FD->getReturnType();
14060 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14061 !FD->isInvalidDecl() &&
14062 RequireCompleteType(FD->getLocation(), ResultType,
14063 diag::err_func_def_incomplete_result))
14064 FD->setInvalidDecl();
14065
14066 if (FnBodyScope)
14067 PushDeclContext(FnBodyScope, FD);
14068
14069 // Check the validity of our function parameters
14070 CheckParmsForFunctionDef(FD->parameters(),
14071 /*CheckParameterNames=*/true);
14072
14073 // Add non-parameter declarations already in the function to the current
14074 // scope.
14075 if (FnBodyScope) {
14076 for (Decl *NPD : FD->decls()) {
14077 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14078 if (!NonParmDecl)
14079 continue;
14080 assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14081, __PRETTY_FUNCTION__))
14081 "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet"
) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14081, __PRETTY_FUNCTION__))
;
14082
14083 // If the decl has a name, make it accessible in the current scope.
14084 if (NonParmDecl->getDeclName())
14085 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14086
14087 // Similarly, dive into enums and fish their constants out, making them
14088 // accessible in this scope.
14089 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14090 for (auto *EI : ED->enumerators())
14091 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14092 }
14093 }
14094 }
14095
14096 // Introduce our parameters into the function scope
14097 for (auto Param : FD->parameters()) {
14098 Param->setOwningFunction(FD);
14099
14100 // If this has an identifier, add it to the scope stack.
14101 if (Param->getIdentifier() && FnBodyScope) {
14102 CheckShadow(FnBodyScope, Param);
14103
14104 PushOnScopeChains(Param, FnBodyScope);
14105 }
14106 }
14107
14108 // Ensure that the function's exception specification is instantiated.
14109 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14110 ResolveExceptionSpec(D->getLocation(), FPT);
14111
14112 // dllimport cannot be applied to non-inline function definitions.
14113 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14114 !FD->isTemplateInstantiation()) {
14115 assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void
> (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14115, __PRETTY_FUNCTION__))
;
14116 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14117 FD->setInvalidDecl();
14118 return D;
14119 }
14120 // We want to attach documentation to original Decl (which might be
14121 // a function template).
14122 ActOnDocumentableDecl(D);
14123 if (getCurLexicalContext()->isObjCContainer() &&
14124 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14125 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14126 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14127
14128 return D;
14129}
14130
14131/// Given the set of return statements within a function body,
14132/// compute the variables that are subject to the named return value
14133/// optimization.
14134///
14135/// Each of the variables that is subject to the named return value
14136/// optimization will be marked as NRVO variables in the AST, and any
14137/// return statement that has a marked NRVO variable as its NRVO candidate can
14138/// use the named return value optimization.
14139///
14140/// This function applies a very simplistic algorithm for NRVO: if every return
14141/// statement in the scope of a variable has the same NRVO candidate, that
14142/// candidate is an NRVO variable.
14143void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14144 ReturnStmt **Returns = Scope->Returns.data();
14145
14146 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14147 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14148 if (!NRVOCandidate->isNRVOVariable())
14149 Returns[I]->setNRVOCandidate(nullptr);
14150 }
14151 }
14152}
14153
14154bool Sema::canDelayFunctionBody(const Declarator &D) {
14155 // We can't delay parsing the body of a constexpr function template (yet).
14156 if (D.getDeclSpec().hasConstexprSpecifier())
14157 return false;
14158
14159 // We can't delay parsing the body of a function template with a deduced
14160 // return type (yet).
14161 if (D.getDeclSpec().hasAutoTypeSpec()) {
14162 // If the placeholder introduces a non-deduced trailing return type,
14163 // we can still delay parsing it.
14164 if (D.getNumTypeObjects()) {
14165 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14166 if (Outer.Kind == DeclaratorChunk::Function &&
14167 Outer.Fun.hasTrailingReturnType()) {
14168 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14169 return Ty.isNull() || !Ty->isUndeducedType();
14170 }
14171 }
14172 return false;
14173 }
14174
14175 return true;
14176}
14177
14178bool Sema::canSkipFunctionBody(Decl *D) {
14179 // We cannot skip the body of a function (or function template) which is
14180 // constexpr, since we may need to evaluate its body in order to parse the
14181 // rest of the file.
14182 // We cannot skip the body of a function with an undeduced return type,
14183 // because any callers of that function need to know the type.
14184 if (const FunctionDecl *FD = D->getAsFunction()) {
14185 if (FD->isConstexpr())
14186 return false;
14187 // We can't simply call Type::isUndeducedType here, because inside template
14188 // auto can be deduced to a dependent type, which is not considered
14189 // "undeduced".
14190 if (FD->getReturnType()->getContainedDeducedType())
14191 return false;
14192 }
14193 return Consumer.shouldSkipFunctionBody(D);
14194}
14195
14196Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14197 if (!Decl)
14198 return nullptr;
14199 if (FunctionDecl *FD = Decl->getAsFunction())
14200 FD->setHasSkippedBody();
14201 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14202 MD->setHasSkippedBody();
14203 return Decl;
14204}
14205
14206Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14207 return ActOnFinishFunctionBody(D, BodyArg, false);
14208}
14209
14210/// RAII object that pops an ExpressionEvaluationContext when exiting a function
14211/// body.
14212class ExitFunctionBodyRAII {
14213public:
14214 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14215 ~ExitFunctionBodyRAII() {
14216 if (!IsLambda)
14217 S.PopExpressionEvaluationContext();
14218 }
14219
14220private:
14221 Sema &S;
14222 bool IsLambda = false;
14223};
14224
14225static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14226 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14227
14228 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14229 if (EscapeInfo.count(BD))
14230 return EscapeInfo[BD];
14231
14232 bool R = false;
14233 const BlockDecl *CurBD = BD;
14234
14235 do {
14236 R = !CurBD->doesNotEscape();
14237 if (R)
14238 break;
14239 CurBD = CurBD->getParent()->getInnermostBlockDecl();
14240 } while (CurBD);
14241
14242 return EscapeInfo[BD] = R;
14243 };
14244
14245 // If the location where 'self' is implicitly retained is inside a escaping
14246 // block, emit a diagnostic.
14247 for (const std::pair<SourceLocation, const BlockDecl *> &P :
14248 S.ImplicitlyRetainedSelfLocs)
14249 if (IsOrNestedInEscapingBlock(P.second))
14250 S.Diag(P.first, diag::warn_implicitly_retains_self)
14251 << FixItHint::CreateInsertion(P.first, "self->");
14252}
14253
14254Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14255 bool IsInstantiation) {
14256 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14257
14258 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14259 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14260
14261 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14262 CheckCompletedCoroutineBody(FD, Body);
14263
14264 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14265 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14266 // meant to pop the context added in ActOnStartOfFunctionDef().
14267 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14268
14269 if (FD) {
14270 FD->setBody(Body);
14271 FD->setWillHaveBody(false);
14272
14273 if (getLangOpts().CPlusPlus14) {
14274 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14275 FD->getReturnType()->isUndeducedType()) {
14276 // If the function has a deduced result type but contains no 'return'
14277 // statements, the result type as written must be exactly 'auto', and
14278 // the deduced result type is 'void'.
14279 if (!FD->getReturnType()->getAs<AutoType>()) {
14280 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14281 << FD->getReturnType();
14282 FD->setInvalidDecl();
14283 } else {
14284 // Substitute 'void' for the 'auto' in the type.
14285 TypeLoc ResultType = getReturnTypeLoc(FD);
14286 Context.adjustDeducedFunctionResultType(
14287 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14288 }
14289 }
14290 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14291 // In C++11, we don't use 'auto' deduction rules for lambda call
14292 // operators because we don't support return type deduction.
14293 auto *LSI = getCurLambda();
14294 if (LSI->HasImplicitReturnType) {
14295 deduceClosureReturnType(*LSI);
14296
14297 // C++11 [expr.prim.lambda]p4:
14298 // [...] if there are no return statements in the compound-statement
14299 // [the deduced type is] the type void
14300 QualType RetType =
14301 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14302
14303 // Update the return type to the deduced type.
14304 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14305 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14306 Proto->getExtProtoInfo()));
14307 }
14308 }
14309
14310 // If the function implicitly returns zero (like 'main') or is naked,
14311 // don't complain about missing return statements.
14312 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14313 WP.disableCheckFallThrough();
14314
14315 // MSVC permits the use of pure specifier (=0) on function definition,
14316 // defined at class scope, warn about this non-standard construct.
14317 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14318 Diag(FD->getLocation(), diag::ext_pure_function_definition);
14319
14320 if (!FD->isInvalidDecl()) {
14321 // Don't diagnose unused parameters of defaulted or deleted functions.
14322 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14323 DiagnoseUnusedParameters(FD->parameters());
14324 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14325 FD->getReturnType(), FD);
14326
14327 // If this is a structor, we need a vtable.
14328 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14329 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14330 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14331 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14332
14333 // Try to apply the named return value optimization. We have to check
14334 // if we can do this here because lambdas keep return statements around
14335 // to deduce an implicit return type.
14336 if (FD->getReturnType()->isRecordType() &&
14337 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14338 computeNRVO(Body, getCurFunction());
14339 }
14340
14341 // GNU warning -Wmissing-prototypes:
14342 // Warn if a global function is defined without a previous
14343 // prototype declaration. This warning is issued even if the
14344 // definition itself provides a prototype. The aim is to detect
14345 // global functions that fail to be declared in header files.
14346 const FunctionDecl *PossiblePrototype = nullptr;
14347 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14348 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14349
14350 if (PossiblePrototype) {
14351 // We found a declaration that is not a prototype,
14352 // but that could be a zero-parameter prototype
14353 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14354 TypeLoc TL = TI->getTypeLoc();
14355 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14356 Diag(PossiblePrototype->getLocation(),
14357 diag::note_declaration_not_a_prototype)
14358 << (FD->getNumParams() != 0)
14359 << (FD->getNumParams() == 0
14360 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14361 : FixItHint{});
14362 }
14363 } else {
14364 // Returns true if the token beginning at this Loc is `const`.
14365 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14366 const LangOptions &LangOpts) {
14367 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14368 if (LocInfo.first.isInvalid())
14369 return false;
14370
14371 bool Invalid = false;
14372 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14373 if (Invalid)
14374 return false;
14375
14376 if (LocInfo.second > Buffer.size())
14377 return false;
14378
14379 const char *LexStart = Buffer.data() + LocInfo.second;
14380 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14381
14382 return StartTok.consume_front("const") &&
14383 (StartTok.empty() || isWhitespace(StartTok[0]) ||
14384 StartTok.startswith("/*") || StartTok.startswith("//"));
14385 };
14386
14387 auto findBeginLoc = [&]() {
14388 // If the return type has `const` qualifier, we want to insert
14389 // `static` before `const` (and not before the typename).
14390 if ((FD->getReturnType()->isAnyPointerType() &&
14391 FD->getReturnType()->getPointeeType().isConstQualified()) ||
14392 FD->getReturnType().isConstQualified()) {
14393 // But only do this if we can determine where the `const` is.
14394
14395 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14396 getLangOpts()))
14397
14398 return FD->getBeginLoc();
14399 }
14400 return FD->getTypeSpecStartLoc();
14401 };
14402 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14403 << /* function */ 1
14404 << (FD->getStorageClass() == SC_None
14405 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14406 : FixItHint{});
14407 }
14408
14409 // GNU warning -Wstrict-prototypes
14410 // Warn if K&R function is defined without a previous declaration.
14411 // This warning is issued only if the definition itself does not provide
14412 // a prototype. Only K&R definitions do not provide a prototype.
14413 if (!FD->hasWrittenPrototype()) {
14414 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14415 TypeLoc TL = TI->getTypeLoc();
14416 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14417 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14418 }
14419 }
14420
14421 // Warn on CPUDispatch with an actual body.
14422 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14423 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14424 if (!CmpndBody->body_empty())
14425 Diag(CmpndBody->body_front()->getBeginLoc(),
14426 diag::warn_dispatch_body_ignored);
14427
14428 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14429 const CXXMethodDecl *KeyFunction;
14430 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14431 MD->isVirtual() &&
14432 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14433 MD == KeyFunction->getCanonicalDecl()) {
14434 // Update the key-function state if necessary for this ABI.
14435 if (FD->isInlined() &&
14436 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14437 Context.setNonKeyFunction(MD);
14438
14439 // If the newly-chosen key function is already defined, then we
14440 // need to mark the vtable as used retroactively.
14441 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14442 const FunctionDecl *Definition;
14443 if (KeyFunction && KeyFunction->isDefined(Definition))
14444 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14445 } else {
14446 // We just defined they key function; mark the vtable as used.
14447 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14448 }
14449 }
14450 }
14451
14452 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator
== FD) && "Function parsing confused") ? static_cast
<void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14453, __PRETTY_FUNCTION__))
14453 "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator
== FD) && "Function parsing confused") ? static_cast
<void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14453, __PRETTY_FUNCTION__))
;
14454 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14455 assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused"
) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14455, __PRETTY_FUNCTION__))
;
14456 MD->setBody(Body);
14457 if (!MD->isInvalidDecl()) {
14458 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14459 MD->getReturnType(), MD);
14460
14461 if (Body)
14462 computeNRVO(Body, getCurFunction());
14463 }
14464 if (getCurFunction()->ObjCShouldCallSuper) {
14465 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14466 << MD->getSelector().getAsString();
14467 getCurFunction()->ObjCShouldCallSuper = false;
14468 }
14469 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14470 const ObjCMethodDecl *InitMethod = nullptr;
14471 bool isDesignated =
14472 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14473 assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void>
(0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14473, __PRETTY_FUNCTION__))
;
14474 (void)isDesignated;
14475
14476 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14477 auto IFace = MD->getClassInterface();
14478 if (!IFace)
14479 return false;
14480 auto SuperD = IFace->getSuperClass();
14481 if (!SuperD)
14482 return false;
14483 return SuperD->getIdentifier() ==
14484 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14485 };
14486 // Don't issue this warning for unavailable inits or direct subclasses
14487 // of NSObject.
14488 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14489 Diag(MD->getLocation(),
14490 diag::warn_objc_designated_init_missing_super_call);
14491 Diag(InitMethod->getLocation(),
14492 diag::note_objc_designated_init_marked_here);
14493 }
14494 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14495 }
14496 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14497 // Don't issue this warning for unavaialable inits.
14498 if (!MD->isUnavailable())
14499 Diag(MD->getLocation(),
14500 diag::warn_objc_secondary_init_missing_init_call);
14501 getCurFunction()->ObjCWarnForNoInitDelegation = false;
14502 }
14503
14504 diagnoseImplicitlyRetainedSelf(*this);
14505 } else {
14506 // Parsing the function declaration failed in some way. Pop the fake scope
14507 // we pushed on.
14508 PopFunctionScopeInfo(ActivePolicy, dcl);
14509 return nullptr;
14510 }
14511
14512 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14513 DiagnoseUnguardedAvailabilityViolations(dcl);
14514
14515 assert(!getCurFunction()->ObjCShouldCallSuper &&((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14517, __PRETTY_FUNCTION__))
14516 "This should only be set for ObjC methods, which should have been "((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14517, __PRETTY_FUNCTION__))
14517 "handled in the block above.")((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14517, __PRETTY_FUNCTION__))
;
14518
14519 // Verify and clean out per-function state.
14520 if (Body && (!FD || !FD->isDefaulted())) {
14521 // C++ constructors that have function-try-blocks can't have return
14522 // statements in the handlers of that block. (C++ [except.handle]p14)
14523 // Verify this.
14524 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14525 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14526
14527 // Verify that gotos and switch cases don't jump into scopes illegally.
14528 if (getCurFunction()->NeedsScopeChecking() &&
14529 !PP.isCodeCompletionEnabled())
14530 DiagnoseInvalidJumps(Body);
14531
14532 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14533 if (!Destructor->getParent()->isDependentType())
14534 CheckDestructor(Destructor);
14535
14536 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14537 Destructor->getParent());
14538 }
14539
14540 // If any errors have occurred, clear out any temporaries that may have
14541 // been leftover. This ensures that these temporaries won't be picked up for
14542 // deletion in some later function.
14543 if (getDiagnostics().hasUncompilableErrorOccurred() ||
14544 getDiagnostics().getSuppressAllDiagnostics()) {
14545 DiscardCleanupsInEvaluationContext();
14546 }
14547 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14548 !isa<FunctionTemplateDecl>(dcl)) {
14549 // Since the body is valid, issue any analysis-based warnings that are
14550 // enabled.
14551 ActivePolicy = &WP;
14552 }
14553
14554 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14555 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14556 FD->setInvalidDecl();
14557
14558 if (FD && FD->hasAttr<NakedAttr>()) {
14559 for (const Stmt *S : Body->children()) {
14560 // Allow local register variables without initializer as they don't
14561 // require prologue.
14562 bool RegisterVariables = false;
14563 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14564 for (const auto *Decl : DS->decls()) {
14565 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14566 RegisterVariables =
14567 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14568 if (!RegisterVariables)
14569 break;
14570 }
14571 }
14572 }
14573 if (RegisterVariables)
14574 continue;
14575 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14576 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14577 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14578 FD->setInvalidDecl();
14579 break;
14580 }
14581 }
14582 }
14583
14584 assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14586, __PRETTY_FUNCTION__))
14585 ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14586, __PRETTY_FUNCTION__))
14586 "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects
&& "Leftover temporaries in function") ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14586, __PRETTY_FUNCTION__))
;
14587 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"
) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14587, __PRETTY_FUNCTION__))
;
14588 assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14589, __PRETTY_FUNCTION__))
14589 "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking"
) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14589, __PRETTY_FUNCTION__))
;
14590 }
14591
14592 if (!IsInstantiation)
14593 PopDeclContext();
14594
14595 PopFunctionScopeInfo(ActivePolicy, dcl);
14596 // If any errors have occurred, clear out any temporaries that may have
14597 // been leftover. This ensures that these temporaries won't be picked up for
14598 // deletion in some later function.
14599 if (getDiagnostics().hasUncompilableErrorOccurred()) {
14600 DiscardCleanupsInEvaluationContext();
14601 }
14602
14603 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14604 auto ES = getEmissionStatus(FD);
14605 if (ES == Sema::FunctionEmissionStatus::Emitted ||
14606 ES == Sema::FunctionEmissionStatus::Unknown)
14607 DeclsToCheckForDeferredDiags.push_back(FD);
14608 }
14609
14610 return dcl;
14611}
14612
14613/// When we finish delayed parsing of an attribute, we must attach it to the
14614/// relevant Decl.
14615void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14616 ParsedAttributes &Attrs) {
14617 // Always attach attributes to the underlying decl.
14618 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14619 D = TD->getTemplatedDecl();
14620 ProcessDeclAttributeList(S, D, Attrs);
14621
14622 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14623 if (Method->isStatic())
14624 checkThisInStaticMemberFunctionAttributes(Method);
14625}
14626
14627/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14628/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14629NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14630 IdentifierInfo &II, Scope *S) {
14631 // Find the scope in which the identifier is injected and the corresponding
14632 // DeclContext.
14633 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14634 // In that case, we inject the declaration into the translation unit scope
14635 // instead.
14636 Scope *BlockScope = S;
14637 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14638 BlockScope = BlockScope->getParent();
14639
14640 Scope *ContextScope = BlockScope;
14641 while (!ContextScope->getEntity())
14642 ContextScope = ContextScope->getParent();
14643 ContextRAII SavedContext(*this, ContextScope->getEntity());
14644
14645 // Before we produce a declaration for an implicitly defined
14646 // function, see whether there was a locally-scoped declaration of
14647 // this name as a function or variable. If so, use that
14648 // (non-visible) declaration, and complain about it.
14649 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14650 if (ExternCPrev) {
14651 // We still need to inject the function into the enclosing block scope so
14652 // that later (non-call) uses can see it.
14653 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14654
14655 // C89 footnote 38:
14656 // If in fact it is not defined as having type "function returning int",
14657 // the behavior is undefined.
14658 if (!isa<FunctionDecl>(ExternCPrev) ||
14659 !Context.typesAreCompatible(
14660 cast<FunctionDecl>(ExternCPrev)->getType(),
14661 Context.getFunctionNoProtoType(Context.IntTy))) {
14662 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14663 << ExternCPrev << !getLangOpts().C99;
14664 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14665 return ExternCPrev;
14666 }
14667 }
14668
14669 // Extension in C99. Legal in C90, but warn about it.
14670 unsigned diag_id;
14671 if (II.getName().startswith("__builtin_"))
14672 diag_id = diag::warn_builtin_unknown;
14673 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14674 else if (getLangOpts().OpenCL)
14675 diag_id = diag::err_opencl_implicit_function_decl;
14676 else if (getLangOpts().C99)
14677 diag_id = diag::ext_implicit_function_decl;
14678 else
14679 diag_id = diag::warn_implicit_function_decl;
14680 Diag(Loc, diag_id) << &II;
14681
14682 // If we found a prior declaration of this function, don't bother building
14683 // another one. We've already pushed that one into scope, so there's nothing
14684 // more to do.
14685 if (ExternCPrev)
14686 return ExternCPrev;
14687
14688 // Because typo correction is expensive, only do it if the implicit
14689 // function declaration is going to be treated as an error.
14690 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14691 TypoCorrection Corrected;
14692 DeclFilterCCC<FunctionDecl> CCC{};
14693 if (S && (Corrected =
14694 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14695 S, nullptr, CCC, CTK_NonError)))
14696 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14697 /*ErrorRecovery*/false);
14698 }
14699
14700 // Set a Declarator for the implicit definition: int foo();
14701 const char *Dummy;
14702 AttributeFactory attrFactory;
14703 DeclSpec DS(attrFactory);
14704 unsigned DiagID;
14705 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14706 Context.getPrintingPolicy());
14707 (void)Error; // Silence warning.
14708 assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast
<void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14708, __PRETTY_FUNCTION__))
;
14709 SourceLocation NoLoc;
14710 Declarator D(DS, DeclaratorContext::BlockContext);
14711 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14712 /*IsAmbiguous=*/false,
14713 /*LParenLoc=*/NoLoc,
14714 /*Params=*/nullptr,
14715 /*NumParams=*/0,
14716 /*EllipsisLoc=*/NoLoc,
14717 /*RParenLoc=*/NoLoc,
14718 /*RefQualifierIsLvalueRef=*/true,
14719 /*RefQualifierLoc=*/NoLoc,
14720 /*MutableLoc=*/NoLoc, EST_None,
14721 /*ESpecRange=*/SourceRange(),
14722 /*Exceptions=*/nullptr,
14723 /*ExceptionRanges=*/nullptr,
14724 /*NumExceptions=*/0,
14725 /*NoexceptExpr=*/nullptr,
14726 /*ExceptionSpecTokens=*/nullptr,
14727 /*DeclsInPrototype=*/None, Loc,
14728 Loc, D),
14729 std::move(DS.getAttributes()), SourceLocation());
14730 D.SetIdentifier(&II, Loc);
14731
14732 // Insert this function into the enclosing block scope.
14733 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14734 FD->setImplicit();
14735
14736 AddKnownFunctionAttributes(FD);
14737
14738 return FD;
14739}
14740
14741/// If this function is a C++ replaceable global allocation function
14742/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14743/// adds any function attributes that we know a priori based on the standard.
14744///
14745/// We need to check for duplicate attributes both here and where user-written
14746/// attributes are applied to declarations.
14747void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14748 FunctionDecl *FD) {
14749 if (FD->isInvalidDecl())
14750 return;
14751
14752 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14753 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14754 return;
14755
14756 Optional<unsigned> AlignmentParam;
14757 bool IsNothrow = false;
14758 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14759 return;
14760
14761 // C++2a [basic.stc.dynamic.allocation]p4:
14762 // An allocation function that has a non-throwing exception specification
14763 // indicates failure by returning a null pointer value. Any other allocation
14764 // function never returns a null pointer value and indicates failure only by
14765 // throwing an exception [...]
14766 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14767 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14768
14769 // C++2a [basic.stc.dynamic.allocation]p2:
14770 // An allocation function attempts to allocate the requested amount of
14771 // storage. [...] If the request succeeds, the value returned by a
14772 // replaceable allocation function is a [...] pointer value p0 different
14773 // from any previously returned value p1 [...]
14774 //
14775 // However, this particular information is being added in codegen,
14776 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14777
14778 // C++2a [basic.stc.dynamic.allocation]p2:
14779 // An allocation function attempts to allocate the requested amount of
14780 // storage. If it is successful, it returns the address of the start of a
14781 // block of storage whose length in bytes is at least as large as the
14782 // requested size.
14783 if (!FD->hasAttr<AllocSizeAttr>()) {
14784 FD->addAttr(AllocSizeAttr::CreateImplicit(
14785 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14786 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14787 }
14788
14789 // C++2a [basic.stc.dynamic.allocation]p3:
14790 // For an allocation function [...], the pointer returned on a successful
14791 // call shall represent the address of storage that is aligned as follows:
14792 // (3.1) If the allocation function takes an argument of type
14793 // std​::​align_­val_­t, the storage will have the alignment
14794 // specified by the value of this argument.
14795 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14796 FD->addAttr(AllocAlignAttr::CreateImplicit(
14797 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14798 }
14799
14800 // FIXME:
14801 // C++2a [basic.stc.dynamic.allocation]p3:
14802 // For an allocation function [...], the pointer returned on a successful
14803 // call shall represent the address of storage that is aligned as follows:
14804 // (3.2) Otherwise, if the allocation function is named operator new[],
14805 // the storage is aligned for any object that does not have
14806 // new-extended alignment ([basic.align]) and is no larger than the
14807 // requested size.
14808 // (3.3) Otherwise, the storage is aligned for any object that does not
14809 // have new-extended alignment and is of the requested size.
14810}
14811
14812/// Adds any function attributes that we know a priori based on
14813/// the declaration of this function.
14814///
14815/// These attributes can apply both to implicitly-declared builtins
14816/// (like __builtin___printf_chk) or to library-declared functions
14817/// like NSLog or printf.
14818///
14819/// We need to check for duplicate attributes both here and where user-written
14820/// attributes are applied to declarations.
14821void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14822 if (FD->isInvalidDecl())
14823 return;
14824
14825 // If this is a built-in function, map its builtin attributes to
14826 // actual attributes.
14827 if (unsigned BuiltinID = FD->getBuiltinID()) {
14828 // Handle printf-formatting attributes.
14829 unsigned FormatIdx;
14830 bool HasVAListArg;
14831 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14832 if (!FD->hasAttr<FormatAttr>()) {
14833 const char *fmt = "printf";
14834 unsigned int NumParams = FD->getNumParams();
14835 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14836 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14837 fmt = "NSString";
14838 FD->addAttr(FormatAttr::CreateImplicit(Context,
14839 &Context.Idents.get(fmt),
14840 FormatIdx+1,
14841 HasVAListArg ? 0 : FormatIdx+2,
14842 FD->getLocation()));
14843 }
14844 }
14845 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14846 HasVAListArg)) {
14847 if (!FD->hasAttr<FormatAttr>())
14848 FD->addAttr(FormatAttr::CreateImplicit(Context,
14849 &Context.Idents.get("scanf"),
14850 FormatIdx+1,
14851 HasVAListArg ? 0 : FormatIdx+2,
14852 FD->getLocation()));
14853 }
14854
14855 // Handle automatically recognized callbacks.
14856 SmallVector<int, 4> Encoding;
14857 if (!FD->hasAttr<CallbackAttr>() &&
14858 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14859 FD->addAttr(CallbackAttr::CreateImplicit(
14860 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14861
14862 // Mark const if we don't care about errno and that is the only thing
14863 // preventing the function from being const. This allows IRgen to use LLVM
14864 // intrinsics for such functions.
14865 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14866 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14867 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14868
14869 // We make "fma" on some platforms const because we know it does not set
14870 // errno in those environments even though it could set errno based on the
14871 // C standard.
14872 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14873 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14874 !FD->hasAttr<ConstAttr>()) {
14875 switch (BuiltinID) {
14876 case Builtin::BI__builtin_fma:
14877 case Builtin::BI__builtin_fmaf:
14878 case Builtin::BI__builtin_fmal:
14879 case Builtin::BIfma:
14880 case Builtin::BIfmaf:
14881 case Builtin::BIfmal:
14882 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14883 break;
14884 default:
14885 break;
14886 }
14887 }
14888
14889 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14890 !FD->hasAttr<ReturnsTwiceAttr>())
14891 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14892 FD->getLocation()));
14893 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14894 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14895 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14896 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14897 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14898 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14899 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14900 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14901 // Add the appropriate attribute, depending on the CUDA compilation mode
14902 // and which target the builtin belongs to. For example, during host
14903 // compilation, aux builtins are __device__, while the rest are __host__.
14904 if (getLangOpts().CUDAIsDevice !=
14905 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14906 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14907 else
14908 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14909 }
14910 }
14911
14912 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14913
14914 // If C++ exceptions are enabled but we are told extern "C" functions cannot
14915 // throw, add an implicit nothrow attribute to any extern "C" function we come
14916 // across.
14917 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14918 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14919 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14920 if (!FPT || FPT->getExceptionSpecType() == EST_None)
14921 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14922 }
14923
14924 IdentifierInfo *Name = FD->getIdentifier();
14925 if (!Name)
14926 return;
14927 if ((!getLangOpts().CPlusPlus &&
14928 FD->getDeclContext()->isTranslationUnit()) ||
14929 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14930 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14931 LinkageSpecDecl::lang_c)) {
14932 // Okay: this could be a libc/libm/Objective-C function we know
14933 // about.
14934 } else
14935 return;
14936
14937 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14938 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14939 // target-specific builtins, perhaps?
14940 if (!FD->hasAttr<FormatAttr>())
14941 FD->addAttr(FormatAttr::CreateImplicit(Context,
14942 &Context.Idents.get("printf"), 2,
14943 Name->isStr("vasprintf") ? 0 : 3,
14944 FD->getLocation()));
14945 }
14946
14947 if (Name->isStr("__CFStringMakeConstantString")) {
14948 // We already have a __builtin___CFStringMakeConstantString,
14949 // but builds that use -fno-constant-cfstrings don't go through that.
14950 if (!FD->hasAttr<FormatArgAttr>())
14951 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14952 FD->getLocation()));
14953 }
14954}
14955
14956TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14957 TypeSourceInfo *TInfo) {
14958 assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator"
) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14958, __PRETTY_FUNCTION__))
;
14959 assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type"
) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14959, __PRETTY_FUNCTION__))
;
14960
14961 if (!TInfo) {
14962 assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type"
) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 14962, __PRETTY_FUNCTION__))
;
14963 TInfo = Context.getTrivialTypeSourceInfo(T);
14964 }
14965
14966 // Scope manipulation handled by caller.
14967 TypedefDecl *NewTD =
14968 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14969 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14970
14971 // Bail out immediately if we have an invalid declaration.
14972 if (D.isInvalidType()) {
14973 NewTD->setInvalidDecl();
14974 return NewTD;
14975 }
14976
14977 if (D.getDeclSpec().isModulePrivateSpecified()) {
14978 if (CurContext->isFunctionOrMethod())
14979 Diag(NewTD->getLocation(), diag::err_module_private_local)
14980 << 2 << NewTD
14981 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14982 << FixItHint::CreateRemoval(
14983 D.getDeclSpec().getModulePrivateSpecLoc());
14984 else
14985 NewTD->setModulePrivate();
14986 }
14987
14988 // C++ [dcl.typedef]p8:
14989 // If the typedef declaration defines an unnamed class (or
14990 // enum), the first typedef-name declared by the declaration
14991 // to be that class type (or enum type) is used to denote the
14992 // class type (or enum type) for linkage purposes only.
14993 // We need to check whether the type was declared in the declaration.
14994 switch (D.getDeclSpec().getTypeSpecType()) {
14995 case TST_enum:
14996 case TST_struct:
14997 case TST_interface:
14998 case TST_union:
14999 case TST_class: {
15000 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15001 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15002 break;
15003 }
15004
15005 default:
15006 break;
15007 }
15008
15009 return NewTD;
15010}
15011
15012/// Check that this is a valid underlying type for an enum declaration.
15013bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15014 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15015 QualType T = TI->getType();
15016
15017 if (T->isDependentType())
15018 return false;
15019
15020 // This doesn't use 'isIntegralType' despite the error message mentioning
15021 // integral type because isIntegralType would also allow enum types in C.
15022 if (const BuiltinType *BT = T->getAs<BuiltinType>())
15023 if (BT->isInteger())
15024 return false;
15025
15026 if (T->isExtIntType())
15027 return false;
15028
15029 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15030}
15031
15032/// Check whether this is a valid redeclaration of a previous enumeration.
15033/// \return true if the redeclaration was invalid.
15034bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15035 QualType EnumUnderlyingTy, bool IsFixed,
15036 const EnumDecl *Prev) {
15037 if (IsScoped != Prev->isScoped()) {
15038 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15039 << Prev->isScoped();
15040 Diag(Prev->getLocation(), diag::note_previous_declaration);
15041 return true;
15042 }
15043
15044 if (IsFixed && Prev->isFixed()) {
15045 if (!EnumUnderlyingTy->isDependentType() &&
15046 !Prev->getIntegerType()->isDependentType() &&
15047 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15048 Prev->getIntegerType())) {
15049 // TODO: Highlight the underlying type of the redeclaration.
15050 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15051 << EnumUnderlyingTy << Prev->getIntegerType();
15052 Diag(Prev->getLocation(), diag::note_previous_declaration)
15053 << Prev->getIntegerTypeRange();
15054 return true;
15055 }
15056 } else if (IsFixed != Prev->isFixed()) {
15057 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15058 << Prev->isFixed();
15059 Diag(Prev->getLocation(), diag::note_previous_declaration);
15060 return true;
15061 }
15062
15063 return false;
15064}
15065
15066/// Get diagnostic %select index for tag kind for
15067/// redeclaration diagnostic message.
15068/// WARNING: Indexes apply to particular diagnostics only!
15069///
15070/// \returns diagnostic %select index.
15071static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15072 switch (Tag) {
15073 case TTK_Struct: return 0;
15074 case TTK_Interface: return 1;
15075 case TTK_Class: return 2;
15076 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 15076)
;
15077 }
15078}
15079
15080/// Determine if tag kind is a class-key compatible with
15081/// class for redeclaration (class, struct, or __interface).
15082///
15083/// \returns true iff the tag kind is compatible.
15084static bool isClassCompatTagKind(TagTypeKind Tag)
15085{
15086 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15087}
15088
15089Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15090 TagTypeKind TTK) {
15091 if (isa<TypedefDecl>(PrevDecl))
15092 return NTK_Typedef;
15093 else if (isa<TypeAliasDecl>(PrevDecl))
15094 return NTK_TypeAlias;
15095 else if (isa<ClassTemplateDecl>(PrevDecl))
15096 return NTK_Template;
15097 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15098 return NTK_TypeAliasTemplate;
15099 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15100 return NTK_TemplateTemplateArgument;
15101 switch (TTK) {
15102 case TTK_Struct:
15103 case TTK_Interface:
15104 case TTK_Class:
15105 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15106 case TTK_Union:
15107 return NTK_NonUnion;
15108 case TTK_Enum:
15109 return NTK_NonEnum;
15110 }
15111 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 15111)
;
15112}
15113
15114/// Determine whether a tag with a given kind is acceptable
15115/// as a redeclaration of the given tag declaration.
15116///
15117/// \returns true if the new tag kind is acceptable, false otherwise.
15118bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15119 TagTypeKind NewTag, bool isDefinition,
15120 SourceLocation NewTagLoc,
15121 const IdentifierInfo *Name) {
15122 // C++ [dcl.type.elab]p3:
15123 // The class-key or enum keyword present in the
15124 // elaborated-type-specifier shall agree in kind with the
15125 // declaration to which the name in the elaborated-type-specifier
15126 // refers. This rule also applies to the form of
15127 // elaborated-type-specifier that declares a class-name or
15128 // friend class since it can be construed as referring to the
15129 // definition of the class. Thus, in any
15130 // elaborated-type-specifier, the enum keyword shall be used to
15131 // refer to an enumeration (7.2), the union class-key shall be
15132 // used to refer to a union (clause 9), and either the class or
15133 // struct class-key shall be used to refer to a class (clause 9)
15134 // declared using the class or struct class-key.
15135 TagTypeKind OldTag = Previous->getTagKind();
15136 if (OldTag != NewTag &&
15137 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15138 return false;
15139
15140 // Tags are compatible, but we might still want to warn on mismatched tags.
15141 // Non-class tags can't be mismatched at this point.
15142 if (!isClassCompatTagKind(NewTag))
15143 return true;
15144
15145 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15146 // by our warning analysis. We don't want to warn about mismatches with (eg)
15147 // declarations in system headers that are designed to be specialized, but if
15148 // a user asks us to warn, we should warn if their code contains mismatched
15149 // declarations.
15150 auto IsIgnoredLoc = [&](SourceLocation Loc) {
15151 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15152 Loc);
15153 };
15154 if (IsIgnoredLoc(NewTagLoc))
15155 return true;
15156
15157 auto IsIgnored = [&](const TagDecl *Tag) {
15158 return IsIgnoredLoc(Tag->getLocation());
15159 };
15160 while (IsIgnored(Previous)) {
15161 Previous = Previous->getPreviousDecl();
15162 if (!Previous)
15163 return true;
15164 OldTag = Previous->getTagKind();
15165 }
15166
15167 bool isTemplate = false;
15168 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15169 isTemplate = Record->getDescribedClassTemplate();
15170
15171 if (inTemplateInstantiation()) {
15172 if (OldTag != NewTag) {
15173 // In a template instantiation, do not offer fix-its for tag mismatches
15174 // since they usually mess up the template instead of fixing the problem.
15175 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15176 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15177 << getRedeclDiagFromTagKind(OldTag);
15178 // FIXME: Note previous location?
15179 }
15180 return true;
15181 }
15182
15183 if (isDefinition) {
15184 // On definitions, check all previous tags and issue a fix-it for each
15185 // one that doesn't match the current tag.
15186 if (Previous->getDefinition()) {
15187 // Don't suggest fix-its for redefinitions.
15188 return true;
15189 }
15190
15191 bool previousMismatch = false;
15192 for (const TagDecl *I : Previous->redecls()) {
15193 if (I->getTagKind() != NewTag) {
15194 // Ignore previous declarations for which the warning was disabled.
15195 if (IsIgnored(I))
15196 continue;
15197
15198 if (!previousMismatch) {
15199 previousMismatch = true;
15200 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15201 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15202 << getRedeclDiagFromTagKind(I->getTagKind());
15203 }
15204 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15205 << getRedeclDiagFromTagKind(NewTag)
15206 << FixItHint::CreateReplacement(I->getInnerLocStart(),
15207 TypeWithKeyword::getTagTypeKindName(NewTag));
15208 }
15209 }
15210 return true;
15211 }
15212
15213 // Identify the prevailing tag kind: this is the kind of the definition (if
15214 // there is a non-ignored definition), or otherwise the kind of the prior
15215 // (non-ignored) declaration.
15216 const TagDecl *PrevDef = Previous->getDefinition();
15217 if (PrevDef && IsIgnored(PrevDef))
15218 PrevDef = nullptr;
15219 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15220 if (Redecl->getTagKind() != NewTag) {
15221 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15222 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15223 << getRedeclDiagFromTagKind(OldTag);
15224 Diag(Redecl->getLocation(), diag::note_previous_use);
15225
15226 // If there is a previous definition, suggest a fix-it.
15227 if (PrevDef) {
15228 Diag(NewTagLoc, diag::note_struct_class_suggestion)
15229 << getRedeclDiagFromTagKind(Redecl->getTagKind())
15230 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15231 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15232 }
15233 }
15234
15235 return true;
15236}
15237
15238/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15239/// from an outer enclosing namespace or file scope inside a friend declaration.
15240/// This should provide the commented out code in the following snippet:
15241/// namespace N {
15242/// struct X;
15243/// namespace M {
15244/// struct Y { friend struct /*N::*/ X; };
15245/// }
15246/// }
15247static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15248 SourceLocation NameLoc) {
15249 // While the decl is in a namespace, do repeated lookup of that name and see
15250 // if we get the same namespace back. If we do not, continue until
15251 // translation unit scope, at which point we have a fully qualified NNS.
15252 SmallVector<IdentifierInfo *, 4> Namespaces;
15253 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15254 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15255 // This tag should be declared in a namespace, which can only be enclosed by
15256 // other namespaces. Bail if there's an anonymous namespace in the chain.
15257 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15258 if (!Namespace || Namespace->isAnonymousNamespace())
15259 return FixItHint();
15260 IdentifierInfo *II = Namespace->getIdentifier();
15261 Namespaces.push_back(II);
15262 NamedDecl *Lookup = SemaRef.LookupSingleName(
15263 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15264 if (Lookup == Namespace)
15265 break;
15266 }
15267
15268 // Once we have all the namespaces, reverse them to go outermost first, and
15269 // build an NNS.
15270 SmallString<64> Insertion;
15271 llvm::raw_svector_ostream OS(Insertion);
15272 if (DC->isTranslationUnit())
15273 OS << "::";
15274 std::reverse(Namespaces.begin(), Namespaces.end());
15275 for (auto *II : Namespaces)
15276 OS << II->getName() << "::";
15277 return FixItHint::CreateInsertion(NameLoc, Insertion);
15278}
15279
15280/// Determine whether a tag originally declared in context \p OldDC can
15281/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15282/// found a declaration in \p OldDC as a previous decl, perhaps through a
15283/// using-declaration).
15284static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15285 DeclContext *NewDC) {
15286 OldDC = OldDC->getRedeclContext();
15287 NewDC = NewDC->getRedeclContext();
15288
15289 if (OldDC->Equals(NewDC))
15290 return true;
15291
15292 // In MSVC mode, we allow a redeclaration if the contexts are related (either
15293 // encloses the other).
15294 if (S.getLangOpts().MSVCCompat &&
15295 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15296 return true;
15297
15298 return false;
15299}
15300
15301/// This is invoked when we see 'struct foo' or 'struct {'. In the
15302/// former case, Name will be non-null. In the later case, Name will be null.
15303/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15304/// reference/declaration/definition of a tag.
15305///
15306/// \param IsTypeSpecifier \c true if this is a type-specifier (or
15307/// trailing-type-specifier) other than one in an alias-declaration.
15308///
15309/// \param SkipBody If non-null, will be set to indicate if the caller should
15310/// skip the definition of this tag and treat it as if it were a declaration.
15311Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15312 SourceLocation KWLoc, CXXScopeSpec &SS,
15313 IdentifierInfo *Name, SourceLocation NameLoc,
15314 const ParsedAttributesView &Attrs, AccessSpecifier AS,
15315 SourceLocation ModulePrivateLoc,
15316 MultiTemplateParamsArg TemplateParameterLists,
15317 bool &OwnedDecl, bool &IsDependent,
15318 SourceLocation ScopedEnumKWLoc,
15319 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15320 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15321 SkipBodyInfo *SkipBody) {
15322 // If this is not a definition, it must have a name.
15323 IdentifierInfo *OrigName = Name;
15324 assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!"
) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 15325, __PRETTY_FUNCTION__))
15325 "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!"
) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 15325, __PRETTY_FUNCTION__))
;
15326 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference)
? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 15326, __PRETTY_FUNCTION__))
;
15327
15328 OwnedDecl = false;
15329 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15330 bool ScopedEnum = ScopedEnumKWLoc.isValid();
15331
15332 // FIXME: Check member specializations more carefully.
15333 bool isMemberSpecialization = false;
15334 bool Invalid = false;
15335
15336 // We only need to do this matching if we have template parameters
15337 // or a scope specifier, which also conveniently avoids this work
15338 // for non-C++ cases.
15339 if (TemplateParameterLists.size() > 0 ||
15340 (SS.isNotEmpty() && TUK != TUK_Reference)) {
15341 if (TemplateParameterList *TemplateParams =
15342 MatchTemplateParametersToScopeSpecifier(
15343 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15344 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15345 if (Kind == TTK_Enum) {
15346 Diag(KWLoc, diag::err_enum_template);
15347 return nullptr;
15348 }
15349
15350 if (TemplateParams->size() > 0) {
15351 // This is a declaration or definition of a class template (which may
15352 // be a member of another template).
15353
15354 if (Invalid)
15355 return nullptr;
15356
15357 OwnedDecl = false;
15358 DeclResult Result = CheckClassTemplate(
15359 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15360 AS, ModulePrivateLoc,
15361 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15362 TemplateParameterLists.data(), SkipBody);
15363 return Result.get();
15364 } else {
15365 // The "template<>" header is extraneous.
15366 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15367 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15368 isMemberSpecialization = true;
15369 }
15370 }
15371
15372 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15373 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15374 return nullptr;
15375 }
15376
15377 // Figure out the underlying type if this a enum declaration. We need to do
15378 // this early, because it's needed to detect if this is an incompatible
15379 // redeclaration.
15380 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15381 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15382
15383 if (Kind == TTK_Enum) {
15384 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15385 // No underlying type explicitly specified, or we failed to parse the
15386 // type, default to int.
15387 EnumUnderlying = Context.IntTy.getTypePtr();
15388 } else if (UnderlyingType.get()) {
15389 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15390 // integral type; any cv-qualification is ignored.
15391 TypeSourceInfo *TI = nullptr;
15392 GetTypeFromParser(UnderlyingType.get(), &TI);
15393 EnumUnderlying = TI;
15394
15395 if (CheckEnumUnderlyingType(TI))
15396 // Recover by falling back to int.
15397 EnumUnderlying = Context.IntTy.getTypePtr();
15398
15399 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15400 UPPC_FixedUnderlyingType))
15401 EnumUnderlying = Context.IntTy.getTypePtr();
15402
15403 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15404 // For MSVC ABI compatibility, unfixed enums must use an underlying type
15405 // of 'int'. However, if this is an unfixed forward declaration, don't set
15406 // the underlying type unless the user enables -fms-compatibility. This
15407 // makes unfixed forward declared enums incomplete and is more conforming.
15408 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15409 EnumUnderlying = Context.IntTy.getTypePtr();
15410 }
15411 }
15412
15413 DeclContext *SearchDC = CurContext;
15414 DeclContext *DC = CurContext;
15415 bool isStdBadAlloc = false;
15416 bool isStdAlignValT = false;
15417
15418 RedeclarationKind Redecl = forRedeclarationInCurContext();
15419 if (TUK == TUK_Friend || TUK == TUK_Reference)
15420 Redecl = NotForRedeclaration;
15421
15422 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15423 /// implemented asks for structural equivalence checking, the returned decl
15424 /// here is passed back to the parser, allowing the tag body to be parsed.
15425 auto createTagFromNewDecl = [&]() -> TagDecl * {
15426 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage"
) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 15426, __PRETTY_FUNCTION__))
;
15427 // If there is an identifier, use the location of the identifier as the
15428 // location of the decl, otherwise use the location of the struct/union
15429 // keyword.
15430 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15431 TagDecl *New = nullptr;
15432
15433 if (Kind == TTK_Enum) {
15434 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15435 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15436 // If this is an undefined enum, bail.
15437 if (TUK != TUK_Definition && !Invalid)
15438 return nullptr;
15439 if (EnumUnderlying) {
15440 EnumDecl *ED = cast<EnumDecl>(New);
15441 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15442 ED->setIntegerTypeSourceInfo(TI);
15443 else
15444 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15445 ED->setPromotionType(ED->getIntegerType());
15446 }
15447 } else { // struct/union
15448 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15449 nullptr);
15450 }
15451
15452 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15453 // Add alignment attributes if necessary; these attributes are checked
15454 // when the ASTContext lays out the structure.
15455 //
15456 // It is important for implementing the correct semantics that this
15457 // happen here (in ActOnTag). The #pragma pack stack is
15458 // maintained as a result of parser callbacks which can occur at
15459 // many points during the parsing of a struct declaration (because
15460 // the #pragma tokens are effectively skipped over during the
15461 // parsing of the struct).
15462 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15463 AddAlignmentAttributesForRecord(RD);
15464 AddMsStructLayoutForRecord(RD);
15465 }
15466 }
15467 New->setLexicalDeclContext(CurContext);
15468 return New;
15469 };
15470
15471 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15472 if (Name && SS.isNotEmpty()) {
15473 // We have a nested-name tag ('struct foo::bar').
15474
15475 // Check for invalid 'foo::'.
15476 if (SS.isInvalid()) {
15477 Name = nullptr;
15478 goto CreateNewDecl;
15479 }
15480
15481 // If this is a friend or a reference to a class in a dependent
15482 // context, don't try to make a decl for it.
15483 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15484 DC = computeDeclContext(SS, false);
15485 if (!DC) {
15486 IsDependent = true;
15487 return nullptr;
15488 }
15489 } else {
15490 DC = computeDeclContext(SS, true);
15491 if (!DC) {
15492 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15493 << SS.getRange();
15494 return nullptr;
15495 }
15496 }
15497
15498 if (RequireCompleteDeclContext(SS, DC))
15499 return nullptr;
15500
15501 SearchDC = DC;
15502 // Look-up name inside 'foo::'.
15503 LookupQualifiedName(Previous, DC);
15504
15505 if (Previous.isAmbiguous())
15506 return nullptr;
15507
15508 if (Previous.empty()) {
15509 // Name lookup did not find anything. However, if the
15510 // nested-name-specifier refers to the current instantiation,
15511 // and that current instantiation has any dependent base
15512 // classes, we might find something at instantiation time: treat
15513 // this as a dependent elaborated-type-specifier.
15514 // But this only makes any sense for reference-like lookups.
15515 if (Previous.wasNotFoundInCurrentInstantiation() &&
15516 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15517 IsDependent = true;
15518 return nullptr;
15519 }
15520
15521 // A tag 'foo::bar' must already exist.
15522 Diag(NameLoc, diag::err_not_tag_in_scope)
15523 << Kind << Name << DC << SS.getRange();
15524 Name = nullptr;
15525 Invalid = true;
15526 goto CreateNewDecl;
15527 }
15528 } else if (Name) {
15529 // C++14 [class.mem]p14:
15530 // If T is the name of a class, then each of the following shall have a
15531 // name different from T:
15532 // -- every member of class T that is itself a type
15533 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15534 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15535 return nullptr;
15536
15537 // If this is a named struct, check to see if there was a previous forward
15538 // declaration or definition.
15539 // FIXME: We're looking into outer scopes here, even when we
15540 // shouldn't be. Doing so can result in ambiguities that we
15541 // shouldn't be diagnosing.
15542 LookupName(Previous, S);
15543
15544 // When declaring or defining a tag, ignore ambiguities introduced
15545 // by types using'ed into this scope.
15546 if (Previous.isAmbiguous() &&
15547 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15548 LookupResult::Filter F = Previous.makeFilter();
15549 while (F.hasNext()) {
15550 NamedDecl *ND = F.next();
15551 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15552 SearchDC->getRedeclContext()))
15553 F.erase();
15554 }
15555 F.done();
15556 }
15557
15558 // C++11 [namespace.memdef]p3:
15559 // If the name in a friend declaration is neither qualified nor
15560 // a template-id and the declaration is a function or an
15561 // elaborated-type-specifier, the lookup to determine whether
15562 // the entity has been previously declared shall not consider
15563 // any scopes outside the innermost enclosing namespace.
15564 //
15565 // MSVC doesn't implement the above rule for types, so a friend tag
15566 // declaration may be a redeclaration of a type declared in an enclosing
15567 // scope. They do implement this rule for friend functions.
15568 //
15569 // Does it matter that this should be by scope instead of by
15570 // semantic context?
15571 if (!Previous.empty() && TUK == TUK_Friend) {
15572 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15573 LookupResult::Filter F = Previous.makeFilter();
15574 bool FriendSawTagOutsideEnclosingNamespace = false;
15575 while (F.hasNext()) {
15576 NamedDecl *ND = F.next();
15577 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15578 if (DC->isFileContext() &&
15579 !EnclosingNS->Encloses(ND->getDeclContext())) {
15580 if (getLangOpts().MSVCCompat)
15581 FriendSawTagOutsideEnclosingNamespace = true;
15582 else
15583 F.erase();
15584 }
15585 }
15586 F.done();
15587
15588 // Diagnose this MSVC extension in the easy case where lookup would have
15589 // unambiguously found something outside the enclosing namespace.
15590 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15591 NamedDecl *ND = Previous.getFoundDecl();
15592 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15593 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15594 }
15595 }
15596
15597 // Note: there used to be some attempt at recovery here.
15598 if (Previous.isAmbiguous())
15599 return nullptr;
15600
15601 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15602 // FIXME: This makes sure that we ignore the contexts associated
15603 // with C structs, unions, and enums when looking for a matching
15604 // tag declaration or definition. See the similar lookup tweak
15605 // in Sema::LookupName; is there a better way to deal with this?
15606 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15607 SearchDC = SearchDC->getParent();
15608 }
15609 }
15610
15611 if (Previous.isSingleResult() &&
15612 Previous.getFoundDecl()->isTemplateParameter()) {
15613 // Maybe we will complain about the shadowed template parameter.
15614 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15615 // Just pretend that we didn't see the previous declaration.
15616 Previous.clear();
15617 }
15618
15619 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15620 DC->Equals(getStdNamespace())) {
15621 if (Name->isStr("bad_alloc")) {
15622 // This is a declaration of or a reference to "std::bad_alloc".
15623 isStdBadAlloc = true;
15624
15625 // If std::bad_alloc has been implicitly declared (but made invisible to
15626 // name lookup), fill in this implicit declaration as the previous
15627 // declaration, so that the declarations get chained appropriately.
15628 if (Previous.empty() && StdBadAlloc)
15629 Previous.addDecl(getStdBadAlloc());
15630 } else if (Name->isStr("align_val_t")) {
15631 isStdAlignValT = true;
15632 if (Previous.empty() && StdAlignValT)
15633 Previous.addDecl(getStdAlignValT());
15634 }
15635 }
15636
15637 // If we didn't find a previous declaration, and this is a reference
15638 // (or friend reference), move to the correct scope. In C++, we
15639 // also need to do a redeclaration lookup there, just in case
15640 // there's a shadow friend decl.
15641 if (Name && Previous.empty() &&
15642 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15643 if (Invalid) goto CreateNewDecl;
15644 assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 15644, __PRETTY_FUNCTION__))
;
15645
15646 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15647 // C++ [basic.scope.pdecl]p5:
15648 // -- for an elaborated-type-specifier of the form
15649 //
15650 // class-key identifier
15651 //
15652 // if the elaborated-type-specifier is used in the
15653 // decl-specifier-seq or parameter-declaration-clause of a
15654 // function defined in namespace scope, the identifier is
15655 // declared as a class-name in the namespace that contains
15656 // the declaration; otherwise, except as a friend
15657 // declaration, the identifier is declared in the smallest
15658 // non-class, non-function-prototype scope that contains the
15659 // declaration.
15660 //
15661 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15662 // C structs and unions.
15663 //
15664 // It is an error in C++ to declare (rather than define) an enum
15665 // type, including via an elaborated type specifier. We'll
15666 // diagnose that later; for now, declare the enum in the same
15667 // scope as we would have picked for any other tag type.
15668 //
15669 // GNU C also supports this behavior as part of its incomplete
15670 // enum types extension, while GNU C++ does not.
15671 //
15672 // Find the context where we'll be declaring the tag.
15673 // FIXME: We would like to maintain the current DeclContext as the
15674 // lexical context,
15675 SearchDC = getTagInjectionContext(SearchDC);
15676
15677 // Find the scope where we'll be declaring the tag.
15678 S = getTagInjectionScope(S, getLangOpts());
15679 } else {
15680 assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 15680, __PRETTY_FUNCTION__))
;
15681 // C++ [namespace.memdef]p3:
15682 // If a friend declaration in a non-local class first declares a
15683 // class or function, the friend class or function is a member of
15684 // the innermost enclosing namespace.
15685 SearchDC = SearchDC->getEnclosingNamespaceContext();
15686 }
15687
15688 // In C++, we need to do a redeclaration lookup to properly
15689 // diagnose some problems.
15690 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15691 // hidden declaration so that we don't get ambiguity errors when using a
15692 // type declared by an elaborated-type-specifier. In C that is not correct
15693 // and we should instead merge compatible types found by lookup.
15694 if (getLangOpts().CPlusPlus) {
15695 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15696 LookupQualifiedName(Previous, SearchDC);
15697 } else {
15698 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15699 LookupName(Previous, S);
15700 }
15701 }
15702
15703 // If we have a known previous declaration to use, then use it.
15704 if (Previous.empty() && SkipBody && SkipBody->Previous)
15705 Previous.addDecl(SkipBody->Previous);
15706
15707 if (!Previous.empty()) {
15708 NamedDecl *PrevDecl = Previous.getFoundDecl();
15709 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15710
15711 // It's okay to have a tag decl in the same scope as a typedef
15712 // which hides a tag decl in the same scope. Finding this
15713 // insanity with a redeclaration lookup can only actually happen
15714 // in C++.
15715 //
15716 // This is also okay for elaborated-type-specifiers, which is
15717 // technically forbidden by the current standard but which is
15718 // okay according to the likely resolution of an open issue;
15719 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15720 if (getLangOpts().CPlusPlus) {
15721 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15722 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15723 TagDecl *Tag = TT->getDecl();
15724 if (Tag->getDeclName() == Name &&
15725 Tag->getDeclContext()->getRedeclContext()
15726 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15727 PrevDecl = Tag;
15728 Previous.clear();
15729 Previous.addDecl(Tag);
15730 Previous.resolveKind();
15731 }
15732 }
15733 }
15734 }
15735
15736 // If this is a redeclaration of a using shadow declaration, it must
15737 // declare a tag in the same context. In MSVC mode, we allow a
15738 // redefinition if either context is within the other.
15739 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15740 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15741 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15742 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15743 !(OldTag && isAcceptableTagRedeclContext(
15744 *this, OldTag->getDeclContext(), SearchDC))) {
15745 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15746 Diag(Shadow->getTargetDecl()->getLocation(),
15747 diag::note_using_decl_target);
15748 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15749 << 0;
15750 // Recover by ignoring the old declaration.
15751 Previous.clear();
15752 goto CreateNewDecl;
15753 }
15754 }
15755
15756 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15757 // If this is a use of a previous tag, or if the tag is already declared
15758 // in the same scope (so that the definition/declaration completes or
15759 // rementions the tag), reuse the decl.
15760 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15761 isDeclInScope(DirectPrevDecl, SearchDC, S,
15762 SS.isNotEmpty() || isMemberSpecialization)) {
15763 // Make sure that this wasn't declared as an enum and now used as a
15764 // struct or something similar.
15765 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15766 TUK == TUK_Definition, KWLoc,
15767 Name)) {
15768 bool SafeToContinue
15769 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15770 Kind != TTK_Enum);
15771 if (SafeToContinue)
15772 Diag(KWLoc, diag::err_use_with_wrong_tag)
15773 << Name
15774 << FixItHint::CreateReplacement(SourceRange(KWLoc),
15775 PrevTagDecl->getKindName());
15776 else
15777 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15778 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15779
15780 if (SafeToContinue)
15781 Kind = PrevTagDecl->getTagKind();
15782 else {
15783 // Recover by making this an anonymous redefinition.
15784 Name = nullptr;
15785 Previous.clear();
15786 Invalid = true;
15787 }
15788 }
15789
15790 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15791 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15792 if (TUK == TUK_Reference || TUK == TUK_Friend)
15793 return PrevTagDecl;
15794
15795 QualType EnumUnderlyingTy;
15796 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15797 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15798 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15799 EnumUnderlyingTy = QualType(T, 0);
15800
15801 // All conflicts with previous declarations are recovered by
15802 // returning the previous declaration, unless this is a definition,
15803 // in which case we want the caller to bail out.
15804 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15805 ScopedEnum, EnumUnderlyingTy,
15806 IsFixed, PrevEnum))
15807 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15808 }
15809
15810 // C++11 [class.mem]p1:
15811 // A member shall not be declared twice in the member-specification,
15812 // except that a nested class or member class template can be declared
15813 // and then later defined.
15814 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15815 S->isDeclScope(PrevDecl)) {
15816 Diag(NameLoc, diag::ext_member_redeclared);
15817 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15818 }
15819
15820 if (!Invalid) {
15821 // If this is a use, just return the declaration we found, unless
15822 // we have attributes.
15823 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15824 if (!Attrs.empty()) {
15825 // FIXME: Diagnose these attributes. For now, we create a new
15826 // declaration to hold them.
15827 } else if (TUK == TUK_Reference &&
15828 (PrevTagDecl->getFriendObjectKind() ==
15829 Decl::FOK_Undeclared ||
15830 PrevDecl->getOwningModule() != getCurrentModule()) &&
15831 SS.isEmpty()) {
15832 // This declaration is a reference to an existing entity, but
15833 // has different visibility from that entity: it either makes
15834 // a friend visible or it makes a type visible in a new module.
15835 // In either case, create a new declaration. We only do this if
15836 // the declaration would have meant the same thing if no prior
15837 // declaration were found, that is, if it was found in the same
15838 // scope where we would have injected a declaration.
15839 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15840 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15841 return PrevTagDecl;
15842 // This is in the injected scope, create a new declaration in
15843 // that scope.
15844 S = getTagInjectionScope(S, getLangOpts());
15845 } else {
15846 return PrevTagDecl;
15847 }
15848 }
15849
15850 // Diagnose attempts to redefine a tag.
15851 if (TUK == TUK_Definition) {
15852 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15853 // If we're defining a specialization and the previous definition
15854 // is from an implicit instantiation, don't emit an error
15855 // here; we'll catch this in the general case below.
15856 bool IsExplicitSpecializationAfterInstantiation = false;
15857 if (isMemberSpecialization) {
15858 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15859 IsExplicitSpecializationAfterInstantiation =
15860 RD->getTemplateSpecializationKind() !=
15861 TSK_ExplicitSpecialization;
15862 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15863 IsExplicitSpecializationAfterInstantiation =
15864 ED->getTemplateSpecializationKind() !=
15865 TSK_ExplicitSpecialization;
15866 }
15867
15868 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15869 // not keep more that one definition around (merge them). However,
15870 // ensure the decl passes the structural compatibility check in
15871 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15872 NamedDecl *Hidden = nullptr;
15873 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15874 // There is a definition of this tag, but it is not visible. We
15875 // explicitly make use of C++'s one definition rule here, and
15876 // assume that this definition is identical to the hidden one
15877 // we already have. Make the existing definition visible and
15878 // use it in place of this one.
15879 if (!getLangOpts().CPlusPlus) {
15880 // Postpone making the old definition visible until after we
15881 // complete parsing the new one and do the structural
15882 // comparison.
15883 SkipBody->CheckSameAsPrevious = true;
15884 SkipBody->New = createTagFromNewDecl();
15885 SkipBody->Previous = Def;
15886 return Def;
15887 } else {
15888 SkipBody->ShouldSkip = true;
15889 SkipBody->Previous = Def;
15890 makeMergedDefinitionVisible(Hidden);
15891 // Carry on and handle it like a normal definition. We'll
15892 // skip starting the definitiion later.
15893 }
15894 } else if (!IsExplicitSpecializationAfterInstantiation) {
15895 // A redeclaration in function prototype scope in C isn't
15896 // visible elsewhere, so merely issue a warning.
15897 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15898 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15899 else
15900 Diag(NameLoc, diag::err_redefinition) << Name;
15901 notePreviousDefinition(Def,
15902 NameLoc.isValid() ? NameLoc : KWLoc);
15903 // If this is a redefinition, recover by making this
15904 // struct be anonymous, which will make any later
15905 // references get the previous definition.
15906 Name = nullptr;
15907 Previous.clear();
15908 Invalid = true;
15909 }
15910 } else {
15911 // If the type is currently being defined, complain
15912 // about a nested redefinition.
15913 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15914 if (TD->isBeingDefined()) {
15915 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15916 Diag(PrevTagDecl->getLocation(),
15917 diag::note_previous_definition);
15918 Name = nullptr;
15919 Previous.clear();
15920 Invalid = true;
15921 }
15922 }
15923
15924 // Okay, this is definition of a previously declared or referenced
15925 // tag. We're going to create a new Decl for it.
15926 }
15927
15928 // Okay, we're going to make a redeclaration. If this is some kind
15929 // of reference, make sure we build the redeclaration in the same DC
15930 // as the original, and ignore the current access specifier.
15931 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15932 SearchDC = PrevTagDecl->getDeclContext();
15933 AS = AS_none;
15934 }
15935 }
15936 // If we get here we have (another) forward declaration or we
15937 // have a definition. Just create a new decl.
15938
15939 } else {
15940 // If we get here, this is a definition of a new tag type in a nested
15941 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15942 // new decl/type. We set PrevDecl to NULL so that the entities
15943 // have distinct types.
15944 Previous.clear();
15945 }
15946 // If we get here, we're going to create a new Decl. If PrevDecl
15947 // is non-NULL, it's a definition of the tag declared by
15948 // PrevDecl. If it's NULL, we have a new definition.
15949
15950 // Otherwise, PrevDecl is not a tag, but was found with tag
15951 // lookup. This is only actually possible in C++, where a few
15952 // things like templates still live in the tag namespace.
15953 } else {
15954 // Use a better diagnostic if an elaborated-type-specifier
15955 // found the wrong kind of type on the first
15956 // (non-redeclaration) lookup.
15957 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15958 !Previous.isForRedeclaration()) {
15959 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15960 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15961 << Kind;
15962 Diag(PrevDecl->getLocation(), diag::note_declared_at);
15963 Invalid = true;
15964
15965 // Otherwise, only diagnose if the declaration is in scope.
15966 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15967 SS.isNotEmpty() || isMemberSpecialization)) {
15968 // do nothing
15969
15970 // Diagnose implicit declarations introduced by elaborated types.
15971 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15972 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15973 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15974 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15975 Invalid = true;
15976
15977 // Otherwise it's a declaration. Call out a particularly common
15978 // case here.
15979 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15980 unsigned Kind = 0;
15981 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15982 Diag(NameLoc, diag::err_tag_definition_of_typedef)
15983 << Name << Kind << TND->getUnderlyingType();
15984 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15985 Invalid = true;
15986
15987 // Otherwise, diagnose.
15988 } else {
15989 // The tag name clashes with something else in the target scope,
15990 // issue an error and recover by making this tag be anonymous.
15991 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15992 notePreviousDefinition(PrevDecl, NameLoc);
15993 Name = nullptr;
15994 Invalid = true;
15995 }
15996
15997 // The existing declaration isn't relevant to us; we're in a
15998 // new scope, so clear out the previous declaration.
15999 Previous.clear();
16000 }
16001 }
16002
16003CreateNewDecl:
16004
16005 TagDecl *PrevDecl = nullptr;
16006 if (Previous.isSingleResult())
16007 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16008
16009 // If there is an identifier, use the location of the identifier as the
16010 // location of the decl, otherwise use the location of the struct/union
16011 // keyword.
16012 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16013
16014 // Otherwise, create a new declaration. If there is a previous
16015 // declaration of the same entity, the two will be linked via
16016 // PrevDecl.
16017 TagDecl *New;
16018
16019 if (Kind == TTK_Enum) {
16020 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16021 // enum X { A, B, C } D; D should chain to X.
16022 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16023 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16024 ScopedEnumUsesClassTag, IsFixed);
16025
16026 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16027 StdAlignValT = cast<EnumDecl>(New);
16028
16029 // If this is an undefined enum, warn.
16030 if (TUK != TUK_Definition && !Invalid) {
16031 TagDecl *Def;
16032 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16033 // C++0x: 7.2p2: opaque-enum-declaration.
16034 // Conflicts are diagnosed above. Do nothing.
16035 }
16036 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16037 Diag(Loc, diag::ext_forward_ref_enum_def)
16038 << New;
16039 Diag(Def->getLocation(), diag::note_previous_definition);
16040 } else {
16041 unsigned DiagID = diag::ext_forward_ref_enum;
16042 if (getLangOpts().MSVCCompat)
16043 DiagID = diag::ext_ms_forward_ref_enum;
16044 else if (getLangOpts().CPlusPlus)
16045 DiagID = diag::err_forward_ref_enum;
16046 Diag(Loc, DiagID);
16047 }
16048 }
16049
16050 if (EnumUnderlying) {
16051 EnumDecl *ED = cast<EnumDecl>(New);
16052 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16053 ED->setIntegerTypeSourceInfo(TI);
16054 else
16055 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16056 ED->setPromotionType(ED->getIntegerType());
16057 assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete"
) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16057, __PRETTY_FUNCTION__))
;
16058 }
16059 } else {
16060 // struct/union/class
16061
16062 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16063 // struct X { int A; } D; D should chain to X.
16064 if (getLangOpts().CPlusPlus) {
16065 // FIXME: Look for a way to use RecordDecl for simple structs.
16066 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16067 cast_or_null<CXXRecordDecl>(PrevDecl));
16068
16069 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16070 StdBadAlloc = cast<CXXRecordDecl>(New);
16071 } else
16072 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16073 cast_or_null<RecordDecl>(PrevDecl));
16074 }
16075
16076 // C++11 [dcl.type]p3:
16077 // A type-specifier-seq shall not define a class or enumeration [...].
16078 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16079 TUK == TUK_Definition) {
16080 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16081 << Context.getTagDeclType(New);
16082 Invalid = true;
16083 }
16084
16085 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16086 DC->getDeclKind() == Decl::Enum) {
16087 Diag(New->getLocation(), diag::err_type_defined_in_enum)
16088 << Context.getTagDeclType(New);
16089 Invalid = true;
16090 }
16091
16092 // Maybe add qualifier info.
16093 if (SS.isNotEmpty()) {
16094 if (SS.isSet()) {
16095 // If this is either a declaration or a definition, check the
16096 // nested-name-specifier against the current context.
16097 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16098 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16099 isMemberSpecialization))
16100 Invalid = true;
16101
16102 New->setQualifierInfo(SS.getWithLocInContext(Context));
16103 if (TemplateParameterLists.size() > 0) {
16104 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16105 }
16106 }
16107 else
16108 Invalid = true;
16109 }
16110
16111 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16112 // Add alignment attributes if necessary; these attributes are checked when
16113 // the ASTContext lays out the structure.
16114 //
16115 // It is important for implementing the correct semantics that this
16116 // happen here (in ActOnTag). The #pragma pack stack is
16117 // maintained as a result of parser callbacks which can occur at
16118 // many points during the parsing of a struct declaration (because
16119 // the #pragma tokens are effectively skipped over during the
16120 // parsing of the struct).
16121 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16122 AddAlignmentAttributesForRecord(RD);
16123 AddMsStructLayoutForRecord(RD);
16124 }
16125 }
16126
16127 if (ModulePrivateLoc.isValid()) {
16128 if (isMemberSpecialization)
16129 Diag(New->getLocation(), diag::err_module_private_specialization)
16130 << 2
16131 << FixItHint::CreateRemoval(ModulePrivateLoc);
16132 // __module_private__ does not apply to local classes. However, we only
16133 // diagnose this as an error when the declaration specifiers are
16134 // freestanding. Here, we just ignore the __module_private__.
16135 else if (!SearchDC->isFunctionOrMethod())
16136 New->setModulePrivate();
16137 }
16138
16139 // If this is a specialization of a member class (of a class template),
16140 // check the specialization.
16141 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16142 Invalid = true;
16143
16144 // If we're declaring or defining a tag in function prototype scope in C,
16145 // note that this type can only be used within the function and add it to
16146 // the list of decls to inject into the function definition scope.
16147 if ((Name || Kind == TTK_Enum) &&
16148 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16149 if (getLangOpts().CPlusPlus) {
16150 // C++ [dcl.fct]p6:
16151 // Types shall not be defined in return or parameter types.
16152 if (TUK == TUK_Definition && !IsTypeSpecifier) {
16153 Diag(Loc, diag::err_type_defined_in_param_type)
16154 << Name;
16155 Invalid = true;
16156 }
16157 } else if (!PrevDecl) {
16158 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16159 }
16160 }
16161
16162 if (Invalid)
16163 New->setInvalidDecl();
16164
16165 // Set the lexical context. If the tag has a C++ scope specifier, the
16166 // lexical context will be different from the semantic context.
16167 New->setLexicalDeclContext(CurContext);
16168
16169 // Mark this as a friend decl if applicable.
16170 // In Microsoft mode, a friend declaration also acts as a forward
16171 // declaration so we always pass true to setObjectOfFriendDecl to make
16172 // the tag name visible.
16173 if (TUK == TUK_Friend)
16174 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16175
16176 // Set the access specifier.
16177 if (!Invalid && SearchDC->isRecord())
16178 SetMemberAccessSpecifier(New, PrevDecl, AS);
16179
16180 if (PrevDecl)
16181 CheckRedeclarationModuleOwnership(New, PrevDecl);
16182
16183 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16184 New->startDefinition();
16185
16186 ProcessDeclAttributeList(S, New, Attrs);
16187 AddPragmaAttributes(S, New);
16188
16189 // If this has an identifier, add it to the scope stack.
16190 if (TUK == TUK_Friend) {
16191 // We might be replacing an existing declaration in the lookup tables;
16192 // if so, borrow its access specifier.
16193 if (PrevDecl)
16194 New->setAccess(PrevDecl->getAccess());
16195
16196 DeclContext *DC = New->getDeclContext()->getRedeclContext();
16197 DC->makeDeclVisibleInContext(New);
16198 if (Name) // can be null along some error paths
16199 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16200 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16201 } else if (Name) {
16202 S = getNonFieldDeclScope(S);
16203 PushOnScopeChains(New, S, true);
16204 } else {
16205 CurContext->addDecl(New);
16206 }
16207
16208 // If this is the C FILE type, notify the AST context.
16209 if (IdentifierInfo *II = New->getIdentifier())
16210 if (!New->isInvalidDecl() &&
16211 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16212 II->isStr("FILE"))
16213 Context.setFILEDecl(New);
16214
16215 if (PrevDecl)
16216 mergeDeclAttributes(New, PrevDecl);
16217
16218 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16219 inferGslOwnerPointerAttribute(CXXRD);
16220
16221 // If there's a #pragma GCC visibility in scope, set the visibility of this
16222 // record.
16223 AddPushedVisibilityAttribute(New);
16224
16225 if (isMemberSpecialization && !New->isInvalidDecl())
16226 CompleteMemberSpecialization(New, Previous);
16227
16228 OwnedDecl = true;
16229 // In C++, don't return an invalid declaration. We can't recover well from
16230 // the cases where we make the type anonymous.
16231 if (Invalid && getLangOpts().CPlusPlus) {
16232 if (New->isBeingDefined())
16233 if (auto RD = dyn_cast<RecordDecl>(New))
16234 RD->completeDefinition();
16235 return nullptr;
16236 } else if (SkipBody && SkipBody->ShouldSkip) {
16237 return SkipBody->Previous;
16238 } else {
16239 return New;
16240 }
16241}
16242
16243void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16244 AdjustDeclIfTemplate(TagD);
16245 TagDecl *Tag = cast<TagDecl>(TagD);
16246
16247 // Enter the tag context.
16248 PushDeclContext(S, Tag);
16249
16250 ActOnDocumentableDecl(TagD);
16251
16252 // If there's a #pragma GCC visibility in scope, set the visibility of this
16253 // record.
16254 AddPushedVisibilityAttribute(Tag);
16255}
16256
16257bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16258 SkipBodyInfo &SkipBody) {
16259 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16260 return false;
16261
16262 // Make the previous decl visible.
16263 makeMergedDefinitionVisible(SkipBody.Previous);
16264 return true;
16265}
16266
16267Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16268 assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16269, __PRETTY_FUNCTION__))
16269 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16269, __PRETTY_FUNCTION__))
;
16270 DeclContext *OCD = cast<DeclContext>(IDecl);
16271 assert(OCD->getLexicalParent() == CurContext &&((OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16272, __PRETTY_FUNCTION__))
16272 "The next DeclContext should be lexically contained in the current one.")((OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one."
) ? static_cast<void> (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16272, __PRETTY_FUNCTION__))
;
16273 CurContext = OCD;
16274 return IDecl;
16275}
16276
16277void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16278 SourceLocation FinalLoc,
16279 bool IsFinalSpelledSealed,
16280 SourceLocation LBraceLoc) {
16281 AdjustDeclIfTemplate(TagD);
16282 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16283
16284 FieldCollector->StartClass();
16285
16286 if (!Record->getIdentifier())
16287 return;
16288
16289 if (FinalLoc.isValid())
16290 Record->addAttr(FinalAttr::Create(
16291 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16292 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16293
16294 // C++ [class]p2:
16295 // [...] The class-name is also inserted into the scope of the
16296 // class itself; this is known as the injected-class-name. For
16297 // purposes of access checking, the injected-class-name is treated
16298 // as if it were a public member name.
16299 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16300 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16301 Record->getLocation(), Record->getIdentifier(),
16302 /*PrevDecl=*/nullptr,
16303 /*DelayTypeCreation=*/true);
16304 Context.getTypeDeclType(InjectedClassName, Record);
16305 InjectedClassName->setImplicit();
16306 InjectedClassName->setAccess(AS_public);
16307 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16308 InjectedClassName->setDescribedClassTemplate(Template);
16309 PushOnScopeChains(InjectedClassName, S);
16310 assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name"
) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16311, __PRETTY_FUNCTION__))
16311 "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name"
) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16311, __PRETTY_FUNCTION__))
;
16312}
16313
16314void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16315 SourceRange BraceRange) {
16316 AdjustDeclIfTemplate(TagD);
16317 TagDecl *Tag = cast<TagDecl>(TagD);
16318 Tag->setBraceRange(BraceRange);
16319
16320 // Make sure we "complete" the definition even it is invalid.
16321 if (Tag->isBeingDefined()) {
16322 assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it"
) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16322, __PRETTY_FUNCTION__))
;
16323 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16324 RD->completeDefinition();
16325 }
16326
16327 if (isa<CXXRecordDecl>(Tag)) {
16328 FieldCollector->FinishClass();
16329 }
16330
16331 // Exit this scope of this tag's definition.
16332 PopDeclContext();
16333
16334 if (getCurLexicalContext()->isObjCContainer() &&
16335 Tag->getDeclContext()->isFileContext())
16336 Tag->setTopLevelDeclInObjCContainer();
16337
16338 // Notify the consumer that we've defined a tag.
16339 if (!Tag->isInvalidDecl())
16340 Consumer.HandleTagDeclDefinition(Tag);
16341}
16342
16343void Sema::ActOnObjCContainerFinishDefinition() {
16344 // Exit this scope of this interface definition.
16345 PopDeclContext();
16346}
16347
16348void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16349 assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts"
) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16349, __PRETTY_FUNCTION__))
;
16350 OriginalLexicalContext = DC;
16351 ActOnObjCContainerFinishDefinition();
16352}
16353
16354void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16355 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16356 OriginalLexicalContext = nullptr;
16357}
16358
16359void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16360 AdjustDeclIfTemplate(TagD);
16361 TagDecl *Tag = cast<TagDecl>(TagD);
16362 Tag->setInvalidDecl();
16363
16364 // Make sure we "complete" the definition even it is invalid.
16365 if (Tag->isBeingDefined()) {
16366 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16367 RD->completeDefinition();
16368 }
16369
16370 // We're undoing ActOnTagStartDefinition here, not
16371 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16372 // the FieldCollector.
16373
16374 PopDeclContext();
16375}
16376
16377// Note that FieldName may be null for anonymous bitfields.
16378ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16379 IdentifierInfo *FieldName,
16380 QualType FieldTy, bool IsMsStruct,
16381 Expr *BitWidth, bool *ZeroWidth) {
16382 assert(BitWidth)((BitWidth) ? static_cast<void> (0) : __assert_fail ("BitWidth"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16382, __PRETTY_FUNCTION__))
;
16383 if (BitWidth->containsErrors())
16384 return ExprError();
16385
16386 // Default to true; that shouldn't confuse checks for emptiness
16387 if (ZeroWidth)
16388 *ZeroWidth = true;
16389
16390 // C99 6.7.2.1p4 - verify the field type.
16391 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16392 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16393 // Handle incomplete and sizeless types with a specific error.
16394 if (RequireCompleteSizedType(FieldLoc, FieldTy,
16395 diag::err_field_incomplete_or_sizeless))
16396 return ExprError();
16397 if (FieldName)
16398 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16399 << FieldName << FieldTy << BitWidth->getSourceRange();
16400 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16401 << FieldTy << BitWidth->getSourceRange();
16402 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16403 UPPC_BitFieldWidth))
16404 return ExprError();
16405
16406 // If the bit-width is type- or value-dependent, don't try to check
16407 // it now.
16408 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16409 return BitWidth;
16410
16411 llvm::APSInt Value;
16412 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16413 if (ICE.isInvalid())
16414 return ICE;
16415 BitWidth = ICE.get();
16416
16417 if (Value != 0 && ZeroWidth)
16418 *ZeroWidth = false;
16419
16420 // Zero-width bitfield is ok for anonymous field.
16421 if (Value == 0 && FieldName)
16422 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16423
16424 if (Value.isSigned() && Value.isNegative()) {
16425 if (FieldName)
16426 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16427 << FieldName << Value.toString(10);
16428 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16429 << Value.toString(10);
16430 }
16431
16432 if (!FieldTy->isDependentType()) {
16433 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16434 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16435 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16436
16437 // Over-wide bitfields are an error in C or when using the MSVC bitfield
16438 // ABI.
16439 bool CStdConstraintViolation =
16440 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16441 bool MSBitfieldViolation =
16442 Value.ugt(TypeStorageSize) &&
16443 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16444 if (CStdConstraintViolation || MSBitfieldViolation) {
16445 unsigned DiagWidth =
16446 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16447 if (FieldName)
16448 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16449 << FieldName << (unsigned)Value.getZExtValue()
16450 << !CStdConstraintViolation << DiagWidth;
16451
16452 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16453 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16454 << DiagWidth;
16455 }
16456
16457 // Warn on types where the user might conceivably expect to get all
16458 // specified bits as value bits: that's all integral types other than
16459 // 'bool'.
16460 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16461 if (FieldName)
16462 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16463 << FieldName << (unsigned)Value.getZExtValue()
16464 << (unsigned)TypeWidth;
16465 else
16466 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16467 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16468 }
16469 }
16470
16471 return BitWidth;
16472}
16473
16474/// ActOnField - Each field of a C struct/union is passed into this in order
16475/// to create a FieldDecl object for it.
16476Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16477 Declarator &D, Expr *BitfieldWidth) {
16478 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16479 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16480 /*InitStyle=*/ICIS_NoInit, AS_public);
16481 return Res;
16482}
16483
16484/// HandleField - Analyze a field of a C struct or a C++ data member.
16485///
16486FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16487 SourceLocation DeclStart,
16488 Declarator &D, Expr *BitWidth,
16489 InClassInitStyle InitStyle,
16490 AccessSpecifier AS) {
16491 if (D.isDecompositionDeclarator()) {
16492 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16493 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16494 << Decomp.getSourceRange();
16495 return nullptr;
16496 }
16497
16498 IdentifierInfo *II = D.getIdentifier();
16499 SourceLocation Loc = DeclStart;
16500 if (II) Loc = D.getIdentifierLoc();
16501
16502 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16503 QualType T = TInfo->getType();
16504 if (getLangOpts().CPlusPlus) {
16505 CheckExtraCXXDefaultArguments(D);
16506
16507 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16508 UPPC_DataMemberType)) {
16509 D.setInvalidType();
16510 T = Context.IntTy;
16511 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16512 }
16513 }
16514
16515 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16516
16517 if (D.getDeclSpec().isInlineSpecified())
16518 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16519 << getLangOpts().CPlusPlus17;
16520 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16521 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16522 diag::err_invalid_thread)
16523 << DeclSpec::getSpecifierName(TSCS);
16524
16525 // Check to see if this name was declared as a member previously
16526 NamedDecl *PrevDecl = nullptr;
16527 LookupResult Previous(*this, II, Loc, LookupMemberName,
16528 ForVisibleRedeclaration);
16529 LookupName(Previous, S);
16530 switch (Previous.getResultKind()) {
16531 case LookupResult::Found:
16532 case LookupResult::FoundUnresolvedValue:
16533 PrevDecl = Previous.getAsSingle<NamedDecl>();
16534 break;
16535
16536 case LookupResult::FoundOverloaded:
16537 PrevDecl = Previous.getRepresentativeDecl();
16538 break;
16539
16540 case LookupResult::NotFound:
16541 case LookupResult::NotFoundInCurrentInstantiation:
16542 case LookupResult::Ambiguous:
16543 break;
16544 }
16545 Previous.suppressDiagnostics();
16546
16547 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16548 // Maybe we will complain about the shadowed template parameter.
16549 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16550 // Just pretend that we didn't see the previous declaration.
16551 PrevDecl = nullptr;
16552 }
16553
16554 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16555 PrevDecl = nullptr;
16556
16557 bool Mutable
16558 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16559 SourceLocation TSSL = D.getBeginLoc();
16560 FieldDecl *NewFD
16561 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16562 TSSL, AS, PrevDecl, &D);
16563
16564 if (NewFD->isInvalidDecl())
16565 Record->setInvalidDecl();
16566
16567 if (D.getDeclSpec().isModulePrivateSpecified())
16568 NewFD->setModulePrivate();
16569
16570 if (NewFD->isInvalidDecl() && PrevDecl) {
16571 // Don't introduce NewFD into scope; there's already something
16572 // with the same name in the same scope.
16573 } else if (II) {
16574 PushOnScopeChains(NewFD, S);
16575 } else
16576 Record->addDecl(NewFD);
16577
16578 return NewFD;
16579}
16580
16581/// Build a new FieldDecl and check its well-formedness.
16582///
16583/// This routine builds a new FieldDecl given the fields name, type,
16584/// record, etc. \p PrevDecl should refer to any previous declaration
16585/// with the same name and in the same scope as the field to be
16586/// created.
16587///
16588/// \returns a new FieldDecl.
16589///
16590/// \todo The Declarator argument is a hack. It will be removed once
16591FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16592 TypeSourceInfo *TInfo,
16593 RecordDecl *Record, SourceLocation Loc,
16594 bool Mutable, Expr *BitWidth,
16595 InClassInitStyle InitStyle,
16596 SourceLocation TSSL,
16597 AccessSpecifier AS, NamedDecl *PrevDecl,
16598 Declarator *D) {
16599 IdentifierInfo *II = Name.getAsIdentifierInfo();
16600 bool InvalidDecl = false;
16601 if (D) InvalidDecl = D->isInvalidType();
16602
16603 // If we receive a broken type, recover by assuming 'int' and
16604 // marking this declaration as invalid.
16605 if (T.isNull() || T->containsErrors()) {
16606 InvalidDecl = true;
16607 T = Context.IntTy;
16608 }
16609
16610 QualType EltTy = Context.getBaseElementType(T);
16611 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16612 if (RequireCompleteSizedType(Loc, EltTy,
16613 diag::err_field_incomplete_or_sizeless)) {
16614 // Fields of incomplete type force their record to be invalid.
16615 Record->setInvalidDecl();
16616 InvalidDecl = true;
16617 } else {
16618 NamedDecl *Def;
16619 EltTy->isIncompleteType(&Def);
16620 if (Def && Def->isInvalidDecl()) {
16621 Record->setInvalidDecl();
16622 InvalidDecl = true;
16623 }
16624 }
16625 }
16626
16627 // TR 18037 does not allow fields to be declared with address space
16628 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16629 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16630 Diag(Loc, diag::err_field_with_address_space);
16631 Record->setInvalidDecl();
16632 InvalidDecl = true;
16633 }
16634
16635 if (LangOpts.OpenCL) {
16636 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16637 // used as structure or union field: image, sampler, event or block types.
16638 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16639 T->isBlockPointerType()) {
16640 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16641 Record->setInvalidDecl();
16642 InvalidDecl = true;
16643 }
16644 // OpenCL v1.2 s6.9.c: bitfields are not supported.
16645 if (BitWidth) {
16646 Diag(Loc, diag::err_opencl_bitfields);
16647 InvalidDecl = true;
16648 }
16649 }
16650
16651 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16652 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16653 T.hasQualifiers()) {
16654 InvalidDecl = true;
16655 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16656 }
16657
16658 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16659 // than a variably modified type.
16660 if (!InvalidDecl && T->isVariablyModifiedType()) {
16661 bool SizeIsNegative;
16662 llvm::APSInt Oversized;
16663
16664 TypeSourceInfo *FixedTInfo =
16665 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16666 SizeIsNegative,
16667 Oversized);
16668 if (FixedTInfo) {
16669 Diag(Loc, diag::warn_illegal_constant_array_size);
16670 TInfo = FixedTInfo;
16671 T = FixedTInfo->getType();
16672 } else {
16673 if (SizeIsNegative)
16674 Diag(Loc, diag::err_typecheck_negative_array_size);
16675 else if (Oversized.getBoolValue())
16676 Diag(Loc, diag::err_array_too_large)
16677 << Oversized.toString(10);
16678 else
16679 Diag(Loc, diag::err_typecheck_field_variable_size);
16680 InvalidDecl = true;
16681 }
16682 }
16683
16684 // Fields can not have abstract class types
16685 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16686 diag::err_abstract_type_in_decl,
16687 AbstractFieldType))
16688 InvalidDecl = true;
16689
16690 bool ZeroWidth = false;
16691 if (InvalidDecl)
16692 BitWidth = nullptr;
16693 // If this is declared as a bit-field, check the bit-field.
16694 if (BitWidth) {
16695 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16696 &ZeroWidth).get();
16697 if (!BitWidth) {
16698 InvalidDecl = true;
16699 BitWidth = nullptr;
16700 ZeroWidth = false;
16701 }
16702
16703 // Only data members can have in-class initializers.
16704 if (BitWidth && !II && InitStyle) {
16705 Diag(Loc, diag::err_anon_bitfield_init);
16706 InvalidDecl = true;
16707 BitWidth = nullptr;
16708 ZeroWidth = false;
16709 }
16710 }
16711
16712 // Check that 'mutable' is consistent with the type of the declaration.
16713 if (!InvalidDecl && Mutable) {
16714 unsigned DiagID = 0;
16715 if (T->isReferenceType())
16716 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16717 : diag::err_mutable_reference;
16718 else if (T.isConstQualified())
16719 DiagID = diag::err_mutable_const;
16720
16721 if (DiagID) {
16722 SourceLocation ErrLoc = Loc;
16723 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16724 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16725 Diag(ErrLoc, DiagID);
16726 if (DiagID != diag::ext_mutable_reference) {
16727 Mutable = false;
16728 InvalidDecl = true;
16729 }
16730 }
16731 }
16732
16733 // C++11 [class.union]p8 (DR1460):
16734 // At most one variant member of a union may have a
16735 // brace-or-equal-initializer.
16736 if (InitStyle != ICIS_NoInit)
16737 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16738
16739 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16740 BitWidth, Mutable, InitStyle);
16741 if (InvalidDecl)
16742 NewFD->setInvalidDecl();
16743
16744 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16745 Diag(Loc, diag::err_duplicate_member) << II;
16746 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16747 NewFD->setInvalidDecl();
16748 }
16749
16750 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16751 if (Record->isUnion()) {
16752 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16753 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16754 if (RDecl->getDefinition()) {
16755 // C++ [class.union]p1: An object of a class with a non-trivial
16756 // constructor, a non-trivial copy constructor, a non-trivial
16757 // destructor, or a non-trivial copy assignment operator
16758 // cannot be a member of a union, nor can an array of such
16759 // objects.
16760 if (CheckNontrivialField(NewFD))
16761 NewFD->setInvalidDecl();
16762 }
16763 }
16764
16765 // C++ [class.union]p1: If a union contains a member of reference type,
16766 // the program is ill-formed, except when compiling with MSVC extensions
16767 // enabled.
16768 if (EltTy->isReferenceType()) {
16769 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16770 diag::ext_union_member_of_reference_type :
16771 diag::err_union_member_of_reference_type)
16772 << NewFD->getDeclName() << EltTy;
16773 if (!getLangOpts().MicrosoftExt)
16774 NewFD->setInvalidDecl();
16775 }
16776 }
16777 }
16778
16779 // FIXME: We need to pass in the attributes given an AST
16780 // representation, not a parser representation.
16781 if (D) {
16782 // FIXME: The current scope is almost... but not entirely... correct here.
16783 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16784
16785 if (NewFD->hasAttrs())
16786 CheckAlignasUnderalignment(NewFD);
16787 }
16788
16789 // In auto-retain/release, infer strong retension for fields of
16790 // retainable type.
16791 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16792 NewFD->setInvalidDecl();
16793
16794 if (T.isObjCGCWeak())
16795 Diag(Loc, diag::warn_attribute_weak_on_field);
16796
16797 NewFD->setAccess(AS);
16798 return NewFD;
16799}
16800
16801bool Sema::CheckNontrivialField(FieldDecl *FD) {
16802 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16802, __PRETTY_FUNCTION__))
;
16803 assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16803, __PRETTY_FUNCTION__))
;
16804
16805 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16806 return false;
16807
16808 QualType EltTy = Context.getBaseElementType(FD->getType());
16809 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16810 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16811 if (RDecl->getDefinition()) {
16812 // We check for copy constructors before constructors
16813 // because otherwise we'll never get complaints about
16814 // copy constructors.
16815
16816 CXXSpecialMember member = CXXInvalid;
16817 // We're required to check for any non-trivial constructors. Since the
16818 // implicit default constructor is suppressed if there are any
16819 // user-declared constructors, we just need to check that there is a
16820 // trivial default constructor and a trivial copy constructor. (We don't
16821 // worry about move constructors here, since this is a C++98 check.)
16822 if (RDecl->hasNonTrivialCopyConstructor())
16823 member = CXXCopyConstructor;
16824 else if (!RDecl->hasTrivialDefaultConstructor())
16825 member = CXXDefaultConstructor;
16826 else if (RDecl->hasNonTrivialCopyAssignment())
16827 member = CXXCopyAssignment;
16828 else if (RDecl->hasNonTrivialDestructor())
16829 member = CXXDestructor;
16830
16831 if (member != CXXInvalid) {
16832 if (!getLangOpts().CPlusPlus11 &&
16833 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16834 // Objective-C++ ARC: it is an error to have a non-trivial field of
16835 // a union. However, system headers in Objective-C programs
16836 // occasionally have Objective-C lifetime objects within unions,
16837 // and rather than cause the program to fail, we make those
16838 // members unavailable.
16839 SourceLocation Loc = FD->getLocation();
16840 if (getSourceManager().isInSystemHeader(Loc)) {
16841 if (!FD->hasAttr<UnavailableAttr>())
16842 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16843 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16844 return false;
16845 }
16846 }
16847
16848 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16849 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16850 diag::err_illegal_union_or_anon_struct_member)
16851 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16852 DiagnoseNontrivial(RDecl, member);
16853 return !getLangOpts().CPlusPlus11;
16854 }
16855 }
16856 }
16857
16858 return false;
16859}
16860
16861/// TranslateIvarVisibility - Translate visibility from a token ID to an
16862/// AST enum value.
16863static ObjCIvarDecl::AccessControl
16864TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16865 switch (ivarVisibility) {
16866 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16866)
;
16867 case tok::objc_private: return ObjCIvarDecl::Private;
16868 case tok::objc_public: return ObjCIvarDecl::Public;
16869 case tok::objc_protected: return ObjCIvarDecl::Protected;
16870 case tok::objc_package: return ObjCIvarDecl::Package;
16871 }
16872}
16873
16874/// ActOnIvar - Each ivar field of an objective-c class is passed into this
16875/// in order to create an IvarDecl object for it.
16876Decl *Sema::ActOnIvar(Scope *S,
16877 SourceLocation DeclStart,
16878 Declarator &D, Expr *BitfieldWidth,
16879 tok::ObjCKeywordKind Visibility) {
16880
16881 IdentifierInfo *II = D.getIdentifier();
16882 Expr *BitWidth = (Expr*)BitfieldWidth;
16883 SourceLocation Loc = DeclStart;
16884 if (II) Loc = D.getIdentifierLoc();
16885
16886 // FIXME: Unnamed fields can be handled in various different ways, for
16887 // example, unnamed unions inject all members into the struct namespace!
16888
16889 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16890 QualType T = TInfo->getType();
16891
16892 if (BitWidth) {
16893 // 6.7.2.1p3, 6.7.2.1p4
16894 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16895 if (!BitWidth)
16896 D.setInvalidType();
16897 } else {
16898 // Not a bitfield.
16899
16900 // validate II.
16901
16902 }
16903 if (T->isReferenceType()) {
16904 Diag(Loc, diag::err_ivar_reference_type);
16905 D.setInvalidType();
16906 }
16907 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16908 // than a variably modified type.
16909 else if (T->isVariablyModifiedType()) {
16910 Diag(Loc, diag::err_typecheck_ivar_variable_size);
16911 D.setInvalidType();
16912 }
16913
16914 // Get the visibility (access control) for this ivar.
16915 ObjCIvarDecl::AccessControl ac =
16916 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16917 : ObjCIvarDecl::None;
16918 // Must set ivar's DeclContext to its enclosing interface.
16919 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16920 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16921 return nullptr;
16922 ObjCContainerDecl *EnclosingContext;
16923 if (ObjCImplementationDecl *IMPDecl =
16924 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16925 if (LangOpts.ObjCRuntime.isFragile()) {
16926 // Case of ivar declared in an implementation. Context is that of its class.
16927 EnclosingContext = IMPDecl->getClassInterface();
16928 assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!"
) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 16928, __PRETTY_FUNCTION__))
;
16929 }
16930 else
16931 EnclosingContext = EnclosingDecl;
16932 } else {
16933 if (ObjCCategoryDecl *CDecl =
16934 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16935 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16936 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16937 return nullptr;
16938 }
16939 }
16940 EnclosingContext = EnclosingDecl;
16941 }
16942
16943 // Construct the decl.
16944 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16945 DeclStart, Loc, II, T,
16946 TInfo, ac, (Expr *)BitfieldWidth);
16947
16948 if (II) {
16949 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16950 ForVisibleRedeclaration);
16951 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16952 && !isa<TagDecl>(PrevDecl)) {
16953 Diag(Loc, diag::err_duplicate_member) << II;
16954 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16955 NewID->setInvalidDecl();
16956 }
16957 }
16958
16959 // Process attributes attached to the ivar.
16960 ProcessDeclAttributes(S, NewID, D);
16961
16962 if (D.isInvalidType())
16963 NewID->setInvalidDecl();
16964
16965 // In ARC, infer 'retaining' for ivars of retainable type.
16966 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16967 NewID->setInvalidDecl();
16968
16969 if (D.getDeclSpec().isModulePrivateSpecified())
16970 NewID->setModulePrivate();
16971
16972 if (II) {
16973 // FIXME: When interfaces are DeclContexts, we'll need to add
16974 // these to the interface.
16975 S->AddDecl(NewID);
16976 IdResolver.AddDecl(NewID);
16977 }
16978
16979 if (LangOpts.ObjCRuntime.isNonFragile() &&
16980 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16981 Diag(Loc, diag::warn_ivars_in_interface);
16982
16983 return NewID;
16984}
16985
16986/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16987/// class and class extensions. For every class \@interface and class
16988/// extension \@interface, if the last ivar is a bitfield of any type,
16989/// then add an implicit `char :0` ivar to the end of that interface.
16990void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16991 SmallVectorImpl<Decl *> &AllIvarDecls) {
16992 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16993 return;
16994
16995 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16996 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16997
16998 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16999 return;
17000 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17001 if (!ID) {
17002 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17003 if (!CD->IsClassExtension())
17004 return;
17005 }
17006 // No need to add this to end of @implementation.
17007 else
17008 return;
17009 }
17010 // All conditions are met. Add a new bitfield to the tail end of ivars.
17011 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17012 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17013
17014 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17015 DeclLoc, DeclLoc, nullptr,
17016 Context.CharTy,
17017 Context.getTrivialTypeSourceInfo(Context.CharTy,
17018 DeclLoc),
17019 ObjCIvarDecl::Private, BW,
17020 true);
17021 AllIvarDecls.push_back(Ivar);
17022}
17023
17024void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17025 ArrayRef<Decl *> Fields, SourceLocation LBrac,
17026 SourceLocation RBrac,
17027 const ParsedAttributesView &Attrs) {
17028 assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl"
) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17028, __PRETTY_FUNCTION__))
;
17029
17030 // If this is an Objective-C @implementation or category and we have
17031 // new fields here we should reset the layout of the interface since
17032 // it will now change.
17033 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17034 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17035 switch (DC->getKind()) {
17036 default: break;
17037 case Decl::ObjCCategory:
17038 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17039 break;
17040 case Decl::ObjCImplementation:
17041 Context.
17042 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17043 break;
17044 }
17045 }
17046
17047 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17048 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17049
17050 // Start counting up the number of named members; make sure to include
17051 // members of anonymous structs and unions in the total.
17052 unsigned NumNamedMembers = 0;
17053 if (Record) {
17054 for (const auto *I : Record->decls()) {
17055 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17056 if (IFD->getDeclName())
17057 ++NumNamedMembers;
17058 }
17059 }
17060
17061 // Verify that all the fields are okay.
17062 SmallVector<FieldDecl*, 32> RecFields;
17063
17064 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17065 i != end; ++i) {
17066 FieldDecl *FD = cast<FieldDecl>(*i);
17067
17068 // Get the type for the field.
17069 const Type *FDTy = FD->getType().getTypePtr();
17070
17071 if (!FD->isAnonymousStructOrUnion()) {
17072 // Remember all fields written by the user.
17073 RecFields.push_back(FD);
17074 }
17075
17076 // If the field is already invalid for some reason, don't emit more
17077 // diagnostics about it.
17078 if (FD->isInvalidDecl()) {
17079 EnclosingDecl->setInvalidDecl();
17080 continue;
17081 }
17082
17083 // C99 6.7.2.1p2:
17084 // A structure or union shall not contain a member with
17085 // incomplete or function type (hence, a structure shall not
17086 // contain an instance of itself, but may contain a pointer to
17087 // an instance of itself), except that the last member of a
17088 // structure with more than one named member may have incomplete
17089 // array type; such a structure (and any union containing,
17090 // possibly recursively, a member that is such a structure)
17091 // shall not be a member of a structure or an element of an
17092 // array.
17093 bool IsLastField = (i + 1 == Fields.end());
17094 if (FDTy->isFunctionType()) {
17095 // Field declared as a function.
17096 Diag(FD->getLocation(), diag::err_field_declared_as_function)
17097 << FD->getDeclName();
17098 FD->setInvalidDecl();
17099 EnclosingDecl->setInvalidDecl();
17100 continue;
17101 } else if (FDTy->isIncompleteArrayType() &&
17102 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17103 if (Record) {
17104 // Flexible array member.
17105 // Microsoft and g++ is more permissive regarding flexible array.
17106 // It will accept flexible array in union and also
17107 // as the sole element of a struct/class.
17108 unsigned DiagID = 0;
17109 if (!Record->isUnion() && !IsLastField) {
17110 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17111 << FD->getDeclName() << FD->getType() << Record->getTagKind();
17112 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17113 FD->setInvalidDecl();
17114 EnclosingDecl->setInvalidDecl();
17115 continue;
17116 } else if (Record->isUnion())
17117 DiagID = getLangOpts().MicrosoftExt
17118 ? diag::ext_flexible_array_union_ms
17119 : getLangOpts().CPlusPlus
17120 ? diag::ext_flexible_array_union_gnu
17121 : diag::err_flexible_array_union;
17122 else if (NumNamedMembers < 1)
17123 DiagID = getLangOpts().MicrosoftExt
17124 ? diag::ext_flexible_array_empty_aggregate_ms
17125 : getLangOpts().CPlusPlus
17126 ? diag::ext_flexible_array_empty_aggregate_gnu
17127 : diag::err_flexible_array_empty_aggregate;
17128
17129 if (DiagID)
17130 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17131 << Record->getTagKind();
17132 // While the layout of types that contain virtual bases is not specified
17133 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17134 // virtual bases after the derived members. This would make a flexible
17135 // array member declared at the end of an object not adjacent to the end
17136 // of the type.
17137 if (CXXRecord && CXXRecord->getNumVBases() != 0)
17138 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17139 << FD->getDeclName() << Record->getTagKind();
17140 if (!getLangOpts().C99)
17141 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17142 << FD->getDeclName() << Record->getTagKind();
17143
17144 // If the element type has a non-trivial destructor, we would not
17145 // implicitly destroy the elements, so disallow it for now.
17146 //
17147 // FIXME: GCC allows this. We should probably either implicitly delete
17148 // the destructor of the containing class, or just allow this.
17149 QualType BaseElem = Context.getBaseElementType(FD->getType());
17150 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17151 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17152 << FD->getDeclName() << FD->getType();
17153 FD->setInvalidDecl();
17154 EnclosingDecl->setInvalidDecl();
17155 continue;
17156 }
17157 // Okay, we have a legal flexible array member at the end of the struct.
17158 Record->setHasFlexibleArrayMember(true);
17159 } else {
17160 // In ObjCContainerDecl ivars with incomplete array type are accepted,
17161 // unless they are followed by another ivar. That check is done
17162 // elsewhere, after synthesized ivars are known.
17163 }
17164 } else if (!FDTy->isDependentType() &&
17165 RequireCompleteSizedType(
17166 FD->getLocation(), FD->getType(),
17167 diag::err_field_incomplete_or_sizeless)) {
17168 // Incomplete type
17169 FD->setInvalidDecl();
17170 EnclosingDecl->setInvalidDecl();
17171 continue;
17172 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17173 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17174 // A type which contains a flexible array member is considered to be a
17175 // flexible array member.
17176 Record->setHasFlexibleArrayMember(true);
17177 if (!Record->isUnion()) {
17178 // If this is a struct/class and this is not the last element, reject
17179 // it. Note that GCC supports variable sized arrays in the middle of
17180 // structures.
17181 if (!IsLastField)
17182 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17183 << FD->getDeclName() << FD->getType();
17184 else {
17185 // We support flexible arrays at the end of structs in
17186 // other structs as an extension.
17187 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17188 << FD->getDeclName();
17189 }
17190 }
17191 }
17192 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17193 RequireNonAbstractType(FD->getLocation(), FD->getType(),
17194 diag::err_abstract_type_in_decl,
17195 AbstractIvarType)) {
17196 // Ivars can not have abstract class types
17197 FD->setInvalidDecl();
17198 }
17199 if (Record && FDTTy->getDecl()->hasObjectMember())
17200 Record->setHasObjectMember(true);
17201 if (Record && FDTTy->getDecl()->hasVolatileMember())
17202 Record->setHasVolatileMember(true);
17203 } else if (FDTy->isObjCObjectType()) {
17204 /// A field cannot be an Objective-c object
17205 Diag(FD->getLocation(), diag::err_statically_allocated_object)
17206 << FixItHint::CreateInsertion(FD->getLocation(), "*");
17207 QualType T = Context.getObjCObjectPointerType(FD->getType());
17208 FD->setType(T);
17209 } else if (Record && Record->isUnion() &&
17210 FD->getType().hasNonTrivialObjCLifetime() &&
17211 getSourceManager().isInSystemHeader(FD->getLocation()) &&
17212 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17213 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17214 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17215 // For backward compatibility, fields of C unions declared in system
17216 // headers that have non-trivial ObjC ownership qualifications are marked
17217 // as unavailable unless the qualifier is explicit and __strong. This can
17218 // break ABI compatibility between programs compiled with ARC and MRR, but
17219 // is a better option than rejecting programs using those unions under
17220 // ARC.
17221 FD->addAttr(UnavailableAttr::CreateImplicit(
17222 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17223 FD->getLocation()));
17224 } else if (getLangOpts().ObjC &&
17225 getLangOpts().getGC() != LangOptions::NonGC && Record &&
17226 !Record->hasObjectMember()) {
17227 if (FD->getType()->isObjCObjectPointerType() ||
17228 FD->getType().isObjCGCStrong())
17229 Record->setHasObjectMember(true);
17230 else if (Context.getAsArrayType(FD->getType())) {
17231 QualType BaseType = Context.getBaseElementType(FD->getType());
17232 if (BaseType->isRecordType() &&
17233 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17234 Record->setHasObjectMember(true);
17235 else if (BaseType->isObjCObjectPointerType() ||
17236 BaseType.isObjCGCStrong())
17237 Record->setHasObjectMember(true);
17238 }
17239 }
17240
17241 if (Record && !getLangOpts().CPlusPlus &&
17242 !shouldIgnoreForRecordTriviality(FD)) {
17243 QualType FT = FD->getType();
17244 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17245 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17246 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17247 Record->isUnion())
17248 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17249 }
17250 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17251 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17252 Record->setNonTrivialToPrimitiveCopy(true);
17253 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17254 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17255 }
17256 if (FT.isDestructedType()) {
17257 Record->setNonTrivialToPrimitiveDestroy(true);
17258 Record->setParamDestroyedInCallee(true);
17259 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17260 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17261 }
17262
17263 if (const auto *RT = FT->getAs<RecordType>()) {
17264 if (RT->getDecl()->getArgPassingRestrictions() ==
17265 RecordDecl::APK_CanNeverPassInRegs)
17266 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17267 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17268 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17269 }
17270
17271 if (Record && FD->getType().isVolatileQualified())
17272 Record->setHasVolatileMember(true);
17273 // Keep track of the number of named members.
17274 if (FD->getIdentifier())
17275 ++NumNamedMembers;
17276 }
17277
17278 // Okay, we successfully defined 'Record'.
17279 if (Record) {
17280 bool Completed = false;
17281 if (CXXRecord) {
17282 if (!CXXRecord->isInvalidDecl()) {
17283 // Set access bits correctly on the directly-declared conversions.
17284 for (CXXRecordDecl::conversion_iterator
17285 I = CXXRecord->conversion_begin(),
17286 E = CXXRecord->conversion_end(); I != E; ++I)
17287 I.setAccess((*I)->getAccess());
17288 }
17289
17290 // Add any implicitly-declared members to this class.
17291 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17292
17293 if (!CXXRecord->isDependentType()) {
17294 if (!CXXRecord->isInvalidDecl()) {
17295 // If we have virtual base classes, we may end up finding multiple
17296 // final overriders for a given virtual function. Check for this
17297 // problem now.
17298 if (CXXRecord->getNumVBases()) {
17299 CXXFinalOverriderMap FinalOverriders;
17300 CXXRecord->getFinalOverriders(FinalOverriders);
17301
17302 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17303 MEnd = FinalOverriders.end();
17304 M != MEnd; ++M) {
17305 for (OverridingMethods::iterator SO = M->second.begin(),
17306 SOEnd = M->second.end();
17307 SO != SOEnd; ++SO) {
17308 assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17309, __PRETTY_FUNCTION__))
17309 "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?"
) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17309, __PRETTY_FUNCTION__))
;
17310 if (SO->second.size() == 1)
17311 continue;
17312
17313 // C++ [class.virtual]p2:
17314 // In a derived class, if a virtual member function of a base
17315 // class subobject has more than one final overrider the
17316 // program is ill-formed.
17317 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17318 << (const NamedDecl *)M->first << Record;
17319 Diag(M->first->getLocation(),
17320 diag::note_overridden_virtual_function);
17321 for (OverridingMethods::overriding_iterator
17322 OM = SO->second.begin(),
17323 OMEnd = SO->second.end();
17324 OM != OMEnd; ++OM)
17325 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17326 << (const NamedDecl *)M->first << OM->Method->getParent();
17327
17328 Record->setInvalidDecl();
17329 }
17330 }
17331 CXXRecord->completeDefinition(&FinalOverriders);
17332 Completed = true;
17333 }
17334 }
17335 }
17336 }
17337
17338 if (!Completed)
17339 Record->completeDefinition();
17340
17341 // Handle attributes before checking the layout.
17342 ProcessDeclAttributeList(S, Record, Attrs);
17343
17344 // We may have deferred checking for a deleted destructor. Check now.
17345 if (CXXRecord) {
17346 auto *Dtor = CXXRecord->getDestructor();
17347 if (Dtor && Dtor->isImplicit() &&
17348 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17349 CXXRecord->setImplicitDestructorIsDeleted();
17350 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17351 }
17352 }
17353
17354 if (Record->hasAttrs()) {
17355 CheckAlignasUnderalignment(Record);
17356
17357 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17358 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17359 IA->getRange(), IA->getBestCase(),
17360 IA->getInheritanceModel());
17361 }
17362
17363 // Check if the structure/union declaration is a type that can have zero
17364 // size in C. For C this is a language extension, for C++ it may cause
17365 // compatibility problems.
17366 bool CheckForZeroSize;
17367 if (!getLangOpts().CPlusPlus) {
17368 CheckForZeroSize = true;
17369 } else {
17370 // For C++ filter out types that cannot be referenced in C code.
17371 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17372 CheckForZeroSize =
17373 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17374 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17375 CXXRecord->isCLike();
17376 }
17377 if (CheckForZeroSize) {
17378 bool ZeroSize = true;
17379 bool IsEmpty = true;
17380 unsigned NonBitFields = 0;
17381 for (RecordDecl::field_iterator I = Record->field_begin(),
17382 E = Record->field_end();
17383 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17384 IsEmpty = false;
17385 if (I->isUnnamedBitfield()) {
17386 if (!I->isZeroLengthBitField(Context))
17387 ZeroSize = false;
17388 } else {
17389 ++NonBitFields;
17390 QualType FieldType = I->getType();
17391 if (FieldType->isIncompleteType() ||
17392 !Context.getTypeSizeInChars(FieldType).isZero())
17393 ZeroSize = false;
17394 }
17395 }
17396
17397 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17398 // allowed in C++, but warn if its declaration is inside
17399 // extern "C" block.
17400 if (ZeroSize) {
17401 Diag(RecLoc, getLangOpts().CPlusPlus ?
17402 diag::warn_zero_size_struct_union_in_extern_c :
17403 diag::warn_zero_size_struct_union_compat)
17404 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17405 }
17406
17407 // Structs without named members are extension in C (C99 6.7.2.1p7),
17408 // but are accepted by GCC.
17409 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17410 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17411 diag::ext_no_named_members_in_struct_union)
17412 << Record->isUnion();
17413 }
17414 }
17415 } else {
17416 ObjCIvarDecl **ClsFields =
17417 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17418 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17419 ID->setEndOfDefinitionLoc(RBrac);
17420 // Add ivar's to class's DeclContext.
17421 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17422 ClsFields[i]->setLexicalDeclContext(ID);
17423 ID->addDecl(ClsFields[i]);
17424 }
17425 // Must enforce the rule that ivars in the base classes may not be
17426 // duplicates.
17427 if (ID->getSuperClass())
17428 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17429 } else if (ObjCImplementationDecl *IMPDecl =
17430 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17431 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17431, __PRETTY_FUNCTION__))
;
17432 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17433 // Ivar declared in @implementation never belongs to the implementation.
17434 // Only it is in implementation's lexical context.
17435 ClsFields[I]->setLexicalDeclContext(IMPDecl);
17436 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17437 IMPDecl->setIvarLBraceLoc(LBrac);
17438 IMPDecl->setIvarRBraceLoc(RBrac);
17439 } else if (ObjCCategoryDecl *CDecl =
17440 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17441 // case of ivars in class extension; all other cases have been
17442 // reported as errors elsewhere.
17443 // FIXME. Class extension does not have a LocEnd field.
17444 // CDecl->setLocEnd(RBrac);
17445 // Add ivar's to class extension's DeclContext.
17446 // Diagnose redeclaration of private ivars.
17447 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17448 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17449 if (IDecl) {
17450 if (const ObjCIvarDecl *ClsIvar =
17451 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17452 Diag(ClsFields[i]->getLocation(),
17453 diag::err_duplicate_ivar_declaration);
17454 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17455 continue;
17456 }
17457 for (const auto *Ext : IDecl->known_extensions()) {
17458 if (const ObjCIvarDecl *ClsExtIvar
17459 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17460 Diag(ClsFields[i]->getLocation(),
17461 diag::err_duplicate_ivar_declaration);
17462 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17463 continue;
17464 }
17465 }
17466 }
17467 ClsFields[i]->setLexicalDeclContext(CDecl);
17468 CDecl->addDecl(ClsFields[i]);
17469 }
17470 CDecl->setIvarLBraceLoc(LBrac);
17471 CDecl->setIvarRBraceLoc(RBrac);
17472 }
17473 }
17474}
17475
17476/// Determine whether the given integral value is representable within
17477/// the given type T.
17478static bool isRepresentableIntegerValue(ASTContext &Context,
17479 llvm::APSInt &Value,
17480 QualType T) {
17481 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17482, __PRETTY_FUNCTION__))
17482 "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17482, __PRETTY_FUNCTION__))
;
17483 unsigned BitWidth = Context.getIntWidth(T);
17484
17485 if (Value.isUnsigned() || Value.isNonNegative()) {
17486 if (T->isSignedIntegerOrEnumerationType())
17487 --BitWidth;
17488 return Value.getActiveBits() <= BitWidth;
17489 }
17490 return Value.getMinSignedBits() <= BitWidth;
17491}
17492
17493// Given an integral type, return the next larger integral type
17494// (or a NULL type of no such type exists).
17495static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17496 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17497 // enum checking below.
17498 assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17499, __PRETTY_FUNCTION__))
17499 T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) &&
"Integral type required!") ? static_cast<void> (0) : __assert_fail
("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17499, __PRETTY_FUNCTION__))
;
17500 const unsigned NumTypes = 4;
17501 QualType SignedIntegralTypes[NumTypes] = {
17502 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17503 };
17504 QualType UnsignedIntegralTypes[NumTypes] = {
17505 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17506 Context.UnsignedLongLongTy
17507 };
17508
17509 unsigned BitWidth = Context.getTypeSize(T);
17510 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17511 : UnsignedIntegralTypes;
17512 for (unsigned I = 0; I != NumTypes; ++I)
17513 if (Context.getTypeSize(Types[I]) > BitWidth)
17514 return Types[I];
17515
17516 return QualType();
17517}
17518
17519EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17520 EnumConstantDecl *LastEnumConst,
17521 SourceLocation IdLoc,
17522 IdentifierInfo *Id,
17523 Expr *Val) {
17524 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17525 llvm::APSInt EnumVal(IntWidth);
17526 QualType EltTy;
17527
17528 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17529 Val = nullptr;
17530
17531 if (Val)
17532 Val = DefaultLvalueConversion(Val).get();
17533
17534 if (Val) {
17535 if (Enum->isDependentType() || Val->isTypeDependent())
17536 EltTy = Context.DependentTy;
17537 else {
17538 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17539 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17540 // constant-expression in the enumerator-definition shall be a converted
17541 // constant expression of the underlying type.
17542 EltTy = Enum->getIntegerType();
17543 ExprResult Converted =
17544 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17545 CCEK_Enumerator);
17546 if (Converted.isInvalid())
17547 Val = nullptr;
17548 else
17549 Val = Converted.get();
17550 } else if (!Val->isValueDependent() &&
17551 !(Val = VerifyIntegerConstantExpression(Val,
17552 &EnumVal).get())) {
17553 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17554 } else {
17555 if (Enum->isComplete()) {
17556 EltTy = Enum->getIntegerType();
17557
17558 // In Obj-C and Microsoft mode, require the enumeration value to be
17559 // representable in the underlying type of the enumeration. In C++11,
17560 // we perform a non-narrowing conversion as part of converted constant
17561 // expression checking.
17562 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17563 if (Context.getTargetInfo()
17564 .getTriple()
17565 .isWindowsMSVCEnvironment()) {
17566 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17567 } else {
17568 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17569 }
17570 }
17571
17572 // Cast to the underlying type.
17573 Val = ImpCastExprToType(Val, EltTy,
17574 EltTy->isBooleanType() ? CK_IntegralToBoolean
17575 : CK_IntegralCast)
17576 .get();
17577 } else if (getLangOpts().CPlusPlus) {
17578 // C++11 [dcl.enum]p5:
17579 // If the underlying type is not fixed, the type of each enumerator
17580 // is the type of its initializing value:
17581 // - If an initializer is specified for an enumerator, the
17582 // initializing value has the same type as the expression.
17583 EltTy = Val->getType();
17584 } else {
17585 // C99 6.7.2.2p2:
17586 // The expression that defines the value of an enumeration constant
17587 // shall be an integer constant expression that has a value
17588 // representable as an int.
17589
17590 // Complain if the value is not representable in an int.
17591 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17592 Diag(IdLoc, diag::ext_enum_value_not_int)
17593 << EnumVal.toString(10) << Val->getSourceRange()
17594 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17595 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17596 // Force the type of the expression to 'int'.
17597 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17598 }
17599 EltTy = Val->getType();
17600 }
17601 }
17602 }
17603 }
17604
17605 if (!Val) {
17606 if (Enum->isDependentType())
17607 EltTy = Context.DependentTy;
17608 else if (!LastEnumConst) {
17609 // C++0x [dcl.enum]p5:
17610 // If the underlying type is not fixed, the type of each enumerator
17611 // is the type of its initializing value:
17612 // - If no initializer is specified for the first enumerator, the
17613 // initializing value has an unspecified integral type.
17614 //
17615 // GCC uses 'int' for its unspecified integral type, as does
17616 // C99 6.7.2.2p3.
17617 if (Enum->isFixed()) {
17618 EltTy = Enum->getIntegerType();
17619 }
17620 else {
17621 EltTy = Context.IntTy;
17622 }
17623 } else {
17624 // Assign the last value + 1.
17625 EnumVal = LastEnumConst->getInitVal();
17626 ++EnumVal;
17627 EltTy = LastEnumConst->getType();
17628
17629 // Check for overflow on increment.
17630 if (EnumVal < LastEnumConst->getInitVal()) {
17631 // C++0x [dcl.enum]p5:
17632 // If the underlying type is not fixed, the type of each enumerator
17633 // is the type of its initializing value:
17634 //
17635 // - Otherwise the type of the initializing value is the same as
17636 // the type of the initializing value of the preceding enumerator
17637 // unless the incremented value is not representable in that type,
17638 // in which case the type is an unspecified integral type
17639 // sufficient to contain the incremented value. If no such type
17640 // exists, the program is ill-formed.
17641 QualType T = getNextLargerIntegralType(Context, EltTy);
17642 if (T.isNull() || Enum->isFixed()) {
17643 // There is no integral type larger enough to represent this
17644 // value. Complain, then allow the value to wrap around.
17645 EnumVal = LastEnumConst->getInitVal();
17646 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17647 ++EnumVal;
17648 if (Enum->isFixed())
17649 // When the underlying type is fixed, this is ill-formed.
17650 Diag(IdLoc, diag::err_enumerator_wrapped)
17651 << EnumVal.toString(10)
17652 << EltTy;
17653 else
17654 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17655 << EnumVal.toString(10);
17656 } else {
17657 EltTy = T;
17658 }
17659
17660 // Retrieve the last enumerator's value, extent that type to the
17661 // type that is supposed to be large enough to represent the incremented
17662 // value, then increment.
17663 EnumVal = LastEnumConst->getInitVal();
17664 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17665 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17666 ++EnumVal;
17667
17668 // If we're not in C++, diagnose the overflow of enumerator values,
17669 // which in C99 means that the enumerator value is not representable in
17670 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17671 // permits enumerator values that are representable in some larger
17672 // integral type.
17673 if (!getLangOpts().CPlusPlus && !T.isNull())
17674 Diag(IdLoc, diag::warn_enum_value_overflow);
17675 } else if (!getLangOpts().CPlusPlus &&
17676 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17677 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17678 Diag(IdLoc, diag::ext_enum_value_not_int)
17679 << EnumVal.toString(10) << 1;
17680 }
17681 }
17682 }
17683
17684 if (!EltTy->isDependentType()) {
17685 // Make the enumerator value match the signedness and size of the
17686 // enumerator's type.
17687 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17688 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17689 }
17690
17691 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17692 Val, EnumVal);
17693}
17694
17695Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17696 SourceLocation IILoc) {
17697 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17698 !getLangOpts().CPlusPlus)
17699 return SkipBodyInfo();
17700
17701 // We have an anonymous enum definition. Look up the first enumerator to
17702 // determine if we should merge the definition with an existing one and
17703 // skip the body.
17704 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17705 forRedeclarationInCurContext());
17706 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17707 if (!PrevECD)
17708 return SkipBodyInfo();
17709
17710 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17711 NamedDecl *Hidden;
17712 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17713 SkipBodyInfo Skip;
17714 Skip.Previous = Hidden;
17715 return Skip;
17716 }
17717
17718 return SkipBodyInfo();
17719}
17720
17721Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17722 SourceLocation IdLoc, IdentifierInfo *Id,
17723 const ParsedAttributesView &Attrs,
17724 SourceLocation EqualLoc, Expr *Val) {
17725 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17726 EnumConstantDecl *LastEnumConst =
17727 cast_or_null<EnumConstantDecl>(lastEnumConst);
17728
17729 // The scope passed in may not be a decl scope. Zip up the scope tree until
17730 // we find one that is.
17731 S = getNonFieldDeclScope(S);
17732
17733 // Verify that there isn't already something declared with this name in this
17734 // scope.
17735 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17736 LookupName(R, S);
17737 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17738
17739 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17740 // Maybe we will complain about the shadowed template parameter.
17741 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17742 // Just pretend that we didn't see the previous declaration.
17743 PrevDecl = nullptr;
17744 }
17745
17746 // C++ [class.mem]p15:
17747 // If T is the name of a class, then each of the following shall have a name
17748 // different from T:
17749 // - every enumerator of every member of class T that is an unscoped
17750 // enumerated type
17751 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17752 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17753 DeclarationNameInfo(Id, IdLoc));
17754
17755 EnumConstantDecl *New =
17756 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17757 if (!New)
17758 return nullptr;
17759
17760 if (PrevDecl) {
17761 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17762 // Check for other kinds of shadowing not already handled.
17763 CheckShadow(New, PrevDecl, R);
17764 }
17765
17766 // When in C++, we may get a TagDecl with the same name; in this case the
17767 // enum constant will 'hide' the tag.
17768 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!") ? static_cast<void>
(0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17769, __PRETTY_FUNCTION__))
17769 "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
"Received TagDecl when not in C++!") ? static_cast<void>
(0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17769, __PRETTY_FUNCTION__))
;
17770 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17771 if (isa<EnumConstantDecl>(PrevDecl))
17772 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17773 else
17774 Diag(IdLoc, diag::err_redefinition) << Id;
17775 notePreviousDefinition(PrevDecl, IdLoc);
17776 return nullptr;
17777 }
17778 }
17779
17780 // Process attributes.
17781 ProcessDeclAttributeList(S, New, Attrs);
17782 AddPragmaAttributes(S, New);
17783
17784 // Register this decl in the current scope stack.
17785 New->setAccess(TheEnumDecl->getAccess());
17786 PushOnScopeChains(New, S);
17787
17788 ActOnDocumentableDecl(New);
17789
17790 return New;
17791}
17792
17793// Returns true when the enum initial expression does not trigger the
17794// duplicate enum warning. A few common cases are exempted as follows:
17795// Element2 = Element1
17796// Element2 = Element1 + 1
17797// Element2 = Element1 - 1
17798// Where Element2 and Element1 are from the same enum.
17799static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17800 Expr *InitExpr = ECD->getInitExpr();
17801 if (!InitExpr)
17802 return true;
17803 InitExpr = InitExpr->IgnoreImpCasts();
17804
17805 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17806 if (!BO->isAdditiveOp())
17807 return true;
17808 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17809 if (!IL)
17810 return true;
17811 if (IL->getValue() != 1)
17812 return true;
17813
17814 InitExpr = BO->getLHS();
17815 }
17816
17817 // This checks if the elements are from the same enum.
17818 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17819 if (!DRE)
17820 return true;
17821
17822 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17823 if (!EnumConstant)
17824 return true;
17825
17826 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17827 Enum)
17828 return true;
17829
17830 return false;
17831}
17832
17833// Emits a warning when an element is implicitly set a value that
17834// a previous element has already been set to.
17835static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17836 EnumDecl *Enum, QualType EnumType) {
17837 // Avoid anonymous enums
17838 if (!Enum->getIdentifier())
17839 return;
17840
17841 // Only check for small enums.
17842 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17843 return;
17844
17845 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17846 return;
17847
17848 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17849 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17850
17851 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17852
17853 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17854 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17855
17856 // Use int64_t as a key to avoid needing special handling for map keys.
17857 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17858 llvm::APSInt Val = D->getInitVal();
17859 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17860 };
17861
17862 DuplicatesVector DupVector;
17863 ValueToVectorMap EnumMap;
17864
17865 // Populate the EnumMap with all values represented by enum constants without
17866 // an initializer.
17867 for (auto *Element : Elements) {
17868 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17869
17870 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17871 // this constant. Skip this enum since it may be ill-formed.
17872 if (!ECD) {
17873 return;
17874 }
17875
17876 // Constants with initalizers are handled in the next loop.
17877 if (ECD->getInitExpr())
17878 continue;
17879
17880 // Duplicate values are handled in the next loop.
17881 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17882 }
17883
17884 if (EnumMap.size() == 0)
17885 return;
17886
17887 // Create vectors for any values that has duplicates.
17888 for (auto *Element : Elements) {
17889 // The last loop returned if any constant was null.
17890 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17891 if (!ValidDuplicateEnum(ECD, Enum))
17892 continue;
17893
17894 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17895 if (Iter == EnumMap.end())
17896 continue;
17897
17898 DeclOrVector& Entry = Iter->second;
17899 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17900 // Ensure constants are different.
17901 if (D == ECD)
17902 continue;
17903
17904 // Create new vector and push values onto it.
17905 auto Vec = std::make_unique<ECDVector>();
17906 Vec->push_back(D);
17907 Vec->push_back(ECD);
17908
17909 // Update entry to point to the duplicates vector.
17910 Entry = Vec.get();
17911
17912 // Store the vector somewhere we can consult later for quick emission of
17913 // diagnostics.
17914 DupVector.emplace_back(std::move(Vec));
17915 continue;
17916 }
17917
17918 ECDVector *Vec = Entry.get<ECDVector*>();
17919 // Make sure constants are not added more than once.
17920 if (*Vec->begin() == ECD)
17921 continue;
17922
17923 Vec->push_back(ECD);
17924 }
17925
17926 // Emit diagnostics.
17927 for (const auto &Vec : DupVector) {
17928 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements."
) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17928, __PRETTY_FUNCTION__))
;
17929
17930 // Emit warning for one enum constant.
17931 auto *FirstECD = Vec->front();
17932 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17933 << FirstECD << FirstECD->getInitVal().toString(10)
17934 << FirstECD->getSourceRange();
17935
17936 // Emit one note for each of the remaining enum constants with
17937 // the same value.
17938 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17939 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17940 << ECD << ECD->getInitVal().toString(10)
17941 << ECD->getSourceRange();
17942 }
17943}
17944
17945bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17946 bool AllowMask) const {
17947 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum"
) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17947, __PRETTY_FUNCTION__))
;
17948 assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition"
) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 17948, __PRETTY_FUNCTION__))
;
17949
17950 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17951 llvm::APInt &FlagBits = R.first->second;
17952
17953 if (R.second) {
17954 for (auto *E : ED->enumerators()) {
17955 const auto &EVal = E->getInitVal();
17956 // Only single-bit enumerators introduce new flag values.
17957 if (EVal.isPowerOf2())
17958 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17959 }
17960 }
17961
17962 // A value is in a flag enum if either its bits are a subset of the enum's
17963 // flag bits (the first condition) or we are allowing masks and the same is
17964 // true of its complement (the second condition). When masks are allowed, we
17965 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17966 //
17967 // While it's true that any value could be used as a mask, the assumption is
17968 // that a mask will have all of the insignificant bits set. Anything else is
17969 // likely a logic error.
17970 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17971 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17972}
17973
17974void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17975 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17976 const ParsedAttributesView &Attrs) {
17977 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17978 QualType EnumType = Context.getTypeDeclType(Enum);
17979
17980 ProcessDeclAttributeList(S, Enum, Attrs);
17981
17982 if (Enum->isDependentType()) {
17983 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17984 EnumConstantDecl *ECD =
17985 cast_or_null<EnumConstantDecl>(Elements[i]);
17986 if (!ECD) continue;
17987
17988 ECD->setType(EnumType);
17989 }
17990
17991 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17992 return;
17993 }
17994
17995 // TODO: If the result value doesn't fit in an int, it must be a long or long
17996 // long value. ISO C does not support this, but GCC does as an extension,
17997 // emit a warning.
17998 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17999 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18000 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18001
18002 // Verify that all the values are okay, compute the size of the values, and
18003 // reverse the list.
18004 unsigned NumNegativeBits = 0;
18005 unsigned NumPositiveBits = 0;
18006
18007 // Keep track of whether all elements have type int.
18008 bool AllElementsInt = true;
18009
18010 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18011 EnumConstantDecl *ECD =
18012 cast_or_null<EnumConstantDecl>(Elements[i]);
18013 if (!ECD) continue; // Already issued a diagnostic.
18014
18015 const llvm::APSInt &InitVal = ECD->getInitVal();
18016
18017 // Keep track of the size of positive and negative values.
18018 if (InitVal.isUnsigned() || InitVal.isNonNegative())
18019 NumPositiveBits = std::max(NumPositiveBits,
18020 (unsigned)InitVal.getActiveBits());
18021 else
18022 NumNegativeBits = std::max(NumNegativeBits,
18023 (unsigned)InitVal.getMinSignedBits());
18024
18025 // Keep track of whether every enum element has type int (very common).
18026 if (AllElementsInt)
18027 AllElementsInt = ECD->getType() == Context.IntTy;
18028 }
18029
18030 // Figure out the type that should be used for this enum.
18031 QualType BestType;
18032 unsigned BestWidth;
18033
18034 // C++0x N3000 [conv.prom]p3:
18035 // An rvalue of an unscoped enumeration type whose underlying
18036 // type is not fixed can be converted to an rvalue of the first
18037 // of the following types that can represent all the values of
18038 // the enumeration: int, unsigned int, long int, unsigned long
18039 // int, long long int, or unsigned long long int.
18040 // C99 6.4.4.3p2:
18041 // An identifier declared as an enumeration constant has type int.
18042 // The C99 rule is modified by a gcc extension
18043 QualType BestPromotionType;
18044
18045 bool Packed = Enum->hasAttr<PackedAttr>();
18046 // -fshort-enums is the equivalent to specifying the packed attribute on all
18047 // enum definitions.
18048 if (LangOpts.ShortEnums)
18049 Packed = true;
18050
18051 // If the enum already has a type because it is fixed or dictated by the
18052 // target, promote that type instead of analyzing the enumerators.
18053 if (Enum->isComplete()) {
18054 BestType = Enum->getIntegerType();
18055 if (BestType->isPromotableIntegerType())
18056 BestPromotionType = Context.getPromotedIntegerType(BestType);
18057 else
18058 BestPromotionType = BestType;
18059
18060 BestWidth = Context.getIntWidth(BestType);
18061 }
18062 else if (NumNegativeBits) {
18063 // If there is a negative value, figure out the smallest integer type (of
18064 // int/long/longlong) that fits.
18065 // If it's packed, check also if it fits a char or a short.
18066 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18067 BestType = Context.SignedCharTy;
18068 BestWidth = CharWidth;
18069 } else if (Packed && NumNegativeBits <= ShortWidth &&
18070 NumPositiveBits < ShortWidth) {
18071 BestType = Context.ShortTy;
18072 BestWidth = ShortWidth;
18073 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18074 BestType = Context.IntTy;
18075 BestWidth = IntWidth;
18076 } else {
18077 BestWidth = Context.getTargetInfo().getLongWidth();
18078
18079 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18080 BestType = Context.LongTy;
18081 } else {
18082 BestWidth = Context.getTargetInfo().getLongLongWidth();
18083
18084 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18085 Diag(Enum->getLocation(), diag::ext_enum_too_large);
18086 BestType = Context.LongLongTy;
18087 }
18088 }
18089 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18090 } else {
18091 // If there is no negative value, figure out the smallest type that fits
18092 // all of the enumerator values.
18093 // If it's packed, check also if it fits a char or a short.
18094 if (Packed && NumPositiveBits <= CharWidth) {
18095 BestType = Context.UnsignedCharTy;
18096 BestPromotionType = Context.IntTy;
18097 BestWidth = CharWidth;
18098 } else if (Packed && NumPositiveBits <= ShortWidth) {
18099 BestType = Context.UnsignedShortTy;
18100 BestPromotionType = Context.IntTy;
18101 BestWidth = ShortWidth;
18102 } else if (NumPositiveBits <= IntWidth) {
18103 BestType = Context.UnsignedIntTy;
18104 BestWidth = IntWidth;
18105 BestPromotionType
18106 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18107 ? Context.UnsignedIntTy : Context.IntTy;
18108 } else if (NumPositiveBits <=
18109 (BestWidth = Context.getTargetInfo().getLongWidth())) {
18110 BestType = Context.UnsignedLongTy;
18111 BestPromotionType
18112 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18113 ? Context.UnsignedLongTy : Context.LongTy;
18114 } else {
18115 BestWidth = Context.getTargetInfo().getLongLongWidth();
18116 assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"
) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 18117, __PRETTY_FUNCTION__))
18117 "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?"
) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/lib/Sema/SemaDecl.cpp"
, 18117, __PRETTY_FUNCTION__))
;
18118 BestType = Context.UnsignedLongLongTy;
18119 BestPromotionType
18120 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18121 ? Context.UnsignedLongLongTy : Context.LongLongTy;
18122 }
18123 }
18124
18125 // Loop over all of the enumerator constants, changing their types to match
18126 // the type of the enum if needed.
18127 for (auto *D : Elements) {
18128 auto *ECD = cast_or_null<EnumConstantDecl>(D);
18129 if (!ECD) continue; // Already issued a diagnostic.
18130
18131 // Standard C says the enumerators have int type, but we allow, as an
18132 // extension, the enumerators to be larger than int size. If each
18133 // enumerator value fits in an int, type it as an int, otherwise type it the
18134 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
18135 // that X has type 'int', not 'unsigned'.
18136
18137 // Determine whether the value fits into an int.
18138 llvm::APSInt InitVal = ECD->getInitVal();
18139
18140 // If it fits into an integer type, force it. Otherwise force it to match
18141 // the enum decl type.
18142 QualType NewTy;
18143 unsigned NewWidth;
18144 bool NewSign;
18145 if (!getLangOpts().CPlusPlus &&
18146 !Enum->isFixed() &&
18147 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18148 NewTy = Context.IntTy;
18149 NewWidth = IntWidth;
18150 NewSign = true;
18151 } else if (ECD->getType() == BestType) {
18152 // Already the right type!
18153 if (getLangOpts().CPlusPlus)
18154 // C++ [dcl.enum]p4: Following the closing brace of an
18155 // enum-specifier, each enumerator has the type of its
18156 // enumeration.
18157 ECD->setType(EnumType);
18158 continue;
18159 } else {
18160 NewTy = BestType;
18161 NewWidth = BestWidth;
18162 NewSign = BestType->isSignedIntegerOrEnumerationType();
18163 }
18164
18165 // Adjust the APSInt value.
18166 InitVal = InitVal.extOrTrunc(NewWidth);
18167 InitVal.setIsSigned(NewSign);
18168 ECD->setInitVal(InitVal);
18169
18170 // Adjust the Expr initializer and type.
18171 if (ECD->getInitExpr() &&
18172 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18173 ECD->setInitExpr(ImplicitCastExpr::Create(
18174 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18175 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18176 if (getLangOpts().CPlusPlus)
18177 // C++ [dcl.enum]p4: Following the closing brace of an
18178 // enum-specifier, each enumerator has the type of its
18179 // enumeration.
18180 ECD->setType(EnumType);
18181 else
18182 ECD->setType(NewTy);
18183 }
18184
18185 Enum->completeDefinition(BestType, BestPromotionType,
18186 NumPositiveBits, NumNegativeBits);
18187
18188 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18189
18190 if (Enum->isClosedFlag()) {
18191 for (Decl *D : Elements) {
18192 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18193 if (!ECD) continue; // Already issued a diagnostic.
18194
18195 llvm::APSInt InitVal = ECD->getInitVal();
18196 if (InitVal != 0 && !InitVal.isPowerOf2() &&
18197 !IsValueInFlagEnum(Enum, InitVal, true))
18198 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18199 << ECD << Enum;
18200 }
18201 }
18202
18203 // Now that the enum type is defined, ensure it's not been underaligned.
18204 if (Enum->hasAttrs())
18205 CheckAlignasUnderalignment(Enum);
18206}
18207
18208Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18209 SourceLocation StartLoc,
18210 SourceLocation EndLoc) {
18211 StringLiteral *AsmString = cast<StringLiteral>(expr);
18212
18213 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18214 AsmString, StartLoc,
18215 EndLoc);
18216 CurContext->addDecl(New);
18217 return New;
18218}
18219
18220void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18221 IdentifierInfo* AliasName,
18222 SourceLocation PragmaLoc,
18223 SourceLocation NameLoc,
18224 SourceLocation AliasNameLoc) {
18225 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18226 LookupOrdinaryName);
18227 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18228 AttributeCommonInfo::AS_Pragma);
18229 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18230 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18231
18232 // If a declaration that:
18233 // 1) declares a function or a variable
18234 // 2) has external linkage
18235 // already exists, add a label attribute to it.
18236 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18237 if (isDeclExternC(PrevDecl))
18238 PrevDecl->addAttr(Attr);
18239 else
18240 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18241 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18242 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18243 } else
18244 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18245}
18246
18247void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18248 SourceLocation PragmaLoc,
18249 SourceLocation NameLoc) {
18250 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18251
18252 if (PrevDecl) {
18253 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18254 } else {
18255 (void)WeakUndeclaredIdentifiers.insert(
18256 std::pair<IdentifierInfo*,WeakInfo>
18257 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18258 }
18259}
18260
18261void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18262 IdentifierInfo* AliasName,
18263 SourceLocation PragmaLoc,
18264 SourceLocation NameLoc,
18265 SourceLocation AliasNameLoc) {
18266 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18267 LookupOrdinaryName);
18268 WeakInfo W = WeakInfo(Name, NameLoc);
18269
18270 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18271 if (!PrevDecl->hasAttr<AliasAttr>())
18272 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18273 DeclApplyPragmaWeak(TUScope, ND, W);
18274 } else {
18275 (void)WeakUndeclaredIdentifiers.insert(
18276 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18277 }
18278}
18279
18280Decl *Sema::getObjCDeclContext() const {
18281 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18282}
18283
18284Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18285 bool Final) {
18286 // SYCL functions can be template, so we check if they have appropriate
18287 // attribute prior to checking if it is a template.
18288 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18289 return FunctionEmissionStatus::Emitted;
18290
18291 // Templates are emitted when they're instantiated.
18292 if (FD->isDependentContext())
18293 return FunctionEmissionStatus::TemplateDiscarded;
18294
18295 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18296 if (LangOpts.OpenMPIsDevice) {
18297 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18298 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18299 if (DevTy.hasValue()) {
18300 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18301 OMPES = FunctionEmissionStatus::OMPDiscarded;
18302 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18303 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18304 OMPES = FunctionEmissionStatus::Emitted;
18305 }
18306 }
18307 } else if (LangOpts.OpenMP) {
18308 // In OpenMP 4.5 all the functions are host functions.
18309 if (LangOpts.OpenMP <= 45) {
18310 OMPES = FunctionEmissionStatus::Emitted;
18311 } else {
18312 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18313 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18314 // In OpenMP 5.0 or above, DevTy may be changed later by
18315 // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18316 // having no value does not imply host. The emission status will be
18317 // checked again at the end of compilation unit.
18318 if (DevTy.hasValue()) {
18319 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18320 OMPES = FunctionEmissionStatus::OMPDiscarded;
18321 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18322 *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18323 OMPES = FunctionEmissionStatus::Emitted;
18324 } else if (Final)
18325 OMPES = FunctionEmissionStatus::Emitted;
18326 }
18327 }
18328 if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18329 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18330 return OMPES;
18331
18332 if (LangOpts.CUDA) {
18333 // When compiling for device, host functions are never emitted. Similarly,
18334 // when compiling for host, device and global functions are never emitted.
18335 // (Technically, we do emit a host-side stub for global functions, but this
18336 // doesn't count for our purposes here.)
18337 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18338 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18339 return FunctionEmissionStatus::CUDADiscarded;
18340 if (!LangOpts.CUDAIsDevice &&
18341 (T == Sema::CFT_Device || T == Sema::CFT_Global))
18342 return FunctionEmissionStatus::CUDADiscarded;
18343
18344 // Check whether this function is externally visible -- if so, it's
18345 // known-emitted.
18346 //
18347 // We have to check the GVA linkage of the function's *definition* -- if we
18348 // only have a declaration, we don't know whether or not the function will
18349 // be emitted, because (say) the definition could include "inline".
18350 FunctionDecl *Def = FD->getDefinition();
18351
18352 if (Def &&
18353 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18354 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18355 return FunctionEmissionStatus::Emitted;
18356 }
18357
18358 // Otherwise, the function is known-emitted if it's in our set of
18359 // known-emitted functions.
18360 return FunctionEmissionStatus::Unknown;
18361}
18362
18363bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18364 // Host-side references to a __global__ function refer to the stub, so the
18365 // function itself is never emitted and therefore should not be marked.
18366 // If we have host fn calls kernel fn calls host+device, the HD function
18367 // does not get instantiated on the host. We model this by omitting at the
18368 // call to the kernel from the callgraph. This ensures that, when compiling
18369 // for host, only HD functions actually called from the host get marked as
18370 // known-emitted.
18371 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18372 IdentifyCUDATarget(Callee) == CFT_Global;
18373}

/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/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())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 475, __PRETTY_FUNCTION__))
;
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail
("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 479, __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")((isFromASTFile() && "Only works on a deserialized declaration"
) ? static_cast<void> (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 645, __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() &&((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 757, __PRETTY_FUNCTION__))
757 "owned local decl but no local module storage")((hasLocalOwningModuleStorage() && "owned local decl but no local module storage"
) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 757, __PRETTY_FUNCTION__))
;
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 763, __PRETTY_FUNCTION__))
762 hasLocalOwningModuleStorage() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 763, __PRETTY_FUNCTION__))
763 "should not have a cached owning module")((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage
() && "should not have a cached owning module") ? static_cast
<void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 763, __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 &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
809 !hasLocalOwningModuleStorage()) &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 810, __PRETTY_FUNCTION__))
810 "no storage available for owning module for this declaration")((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
MOK != ModuleOwnershipKind::Unowned && !isFromASTFile
() && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 810, __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")((Current && "Advancing while iterator has reached end"
) ? static_cast<void> (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 945, __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!")((Next && "Should return next redeclaration or itself, never null!"
) ? static_cast<void> (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 948, __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 &&(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag
)) == 0 && "namespace is not ordinary") ? static_cast
<void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1082, __PRETTY_FUNCTION__))
1082 "namespace is not ordinary")(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag
)) == 0 && "namespace is not ordinary") ? static_cast
<void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1082, __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 |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
1108 "namespace includes neither ordinary nor tag")(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend
| IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1108, __PRETTY_FUNCTION__))
;
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1112, __PRETTY_FUNCTION__))
1112 "namespace includes other than ordinary or tag")((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend
| IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator
)) && "namespace includes other than ordinary or tag"
) ? static_cast<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-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1112, __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;
12
Assuming 'mask' is not equal to 0, which participates in a condition later
13
Taking false branch
1147 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
14
Assuming the condition is false
15
'?' condition is false
16
Returning the value 2, which participates in a condition later
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)((getKind() == Function || getKind() == FunctionTemplate) ? static_cast
<void> (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate"
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1153, __PRETTY_FUNCTION__))
;
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace"
) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1155, __PRETTY_FUNCTION__))
1155 "visible non-member operators should be in ordinary namespace")(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace"
) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 1155, __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
1224/// The results of name lookup within a DeclContext. This is either a
1225/// single result (with no stable storage) or a collection of results (with
1226/// stable storage provided by the lookup table).
1227class DeclContextLookupResult {
1228 using ResultTy = ArrayRef<NamedDecl *>;
1229
1230 ResultTy Result;
1231
1232 // If there is only one lookup result, it would be invalidated by
1233 // reallocations of the name table, so store it separately.
1234 NamedDecl *Single = nullptr;
1235
1236 static NamedDecl *const SingleElementDummyList;
1237
1238public:
1239 DeclContextLookupResult() = default;
1240 DeclContextLookupResult(ArrayRef<NamedDecl *> Result)
1241 : Result(Result) {}
1242 DeclContextLookupResult(NamedDecl *Single)
1243 : Result(SingleElementDummyList), Single(Single) {}
1244
1245 class iterator;
1246
1247 using IteratorBase =
1248 llvm::iterator_adaptor_base<iterator, ResultTy::iterator,
1249 std::random_access_iterator_tag,
1250 NamedDecl *const>;
1251
1252 class iterator : public IteratorBase {
1253 value_type SingleElement;
1254
1255 public:
1256 explicit iterator(pointer Pos, value_type Single = nullptr)
1257 : IteratorBase(Pos), SingleElement(Single) {}
1258
1259 reference operator*() const {
1260 return SingleElement ? SingleElement : IteratorBase::operator*();
1261 }
1262 };
1263
1264 using const_iterator = iterator;
1265 using pointer = iterator::pointer;
1266 using reference = iterator::reference;
1267
1268 iterator begin() const { return iterator(Result.begin(), Single); }
1269 iterator end() const { return iterator(Result.end(), Single); }
1270
1271 bool empty() const { return Result.empty(); }
1272 pointer data() const { return Single ? &Single : Result.data(); }
1273 size_t size() const { return Single ? 1 : Result.size(); }
1274 reference front() const { return Single ? Single : Result.front(); }
1275 reference back() const { return Single ? Single : Result.back(); }
1276 reference operator[](size_t N) const { return Single ? Single : Result[N]; }
1277
1278 // FIXME: Remove this from the interface
1279 DeclContextLookupResult slice(size_t N) const {
1280 DeclContextLookupResult Sliced = Result.slice(N);
1281 Sliced.Single = Single;
1282 return Sliced;
1283 }
1284};
1285
1286/// DeclContext - This is used only as base class of specific decl types that
1287/// can act as declaration contexts. These decls are (only the top classes
1288/// that directly derive from DeclContext are mentioned, not their subclasses):
1289///
1290/// TranslationUnitDecl
1291/// ExternCContext
1292/// NamespaceDecl
1293/// TagDecl
1294/// OMPDeclareReductionDecl
1295/// OMPDeclareMapperDecl
1296/// FunctionDecl
1297/// ObjCMethodDecl
1298/// ObjCContainerDecl
1299/// LinkageSpecDecl
1300/// ExportDecl
1301/// BlockDecl
1302/// CapturedDecl
1303class DeclContext {
1304 /// For makeDeclVisibleInContextImpl
1305 friend class ASTDeclReader;
1306 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1307 /// hasNeedToReconcileExternalVisibleStorage
1308 friend class ExternalASTSource;
1309 /// For CreateStoredDeclsMap
1310 friend class DependentDiagnostic;
1311 /// For hasNeedToReconcileExternalVisibleStorage,
1312 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1313 friend class ASTWriter;
1314
1315 // We use uint64_t in the bit-fields below since some bit-fields
1316 // cross the unsigned boundary and this breaks the packing.
1317
1318 /// Stores the bits used by DeclContext.
1319 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1320 /// methods in DeclContext should be updated appropriately.
1321 class DeclContextBitfields {
1322 friend class DeclContext;
1323 /// DeclKind - This indicates which class this is.
1324 uint64_t DeclKind : 7;
1325
1326 /// Whether this declaration context also has some external
1327 /// storage that contains additional declarations that are lexically
1328 /// part of this context.
1329 mutable uint64_t ExternalLexicalStorage : 1;
1330
1331 /// Whether this declaration context also has some external
1332 /// storage that contains additional declarations that are visible
1333 /// in this context.
1334 mutable uint64_t ExternalVisibleStorage : 1;
1335
1336 /// Whether this declaration context has had externally visible
1337 /// storage added since the last lookup. In this case, \c LookupPtr's
1338 /// invariant may not hold and needs to be fixed before we perform
1339 /// another lookup.
1340 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1341
1342 /// If \c true, this context may have local lexical declarations
1343 /// that are missing from the lookup table.
1344 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1345
1346 /// If \c true, the external source may have lexical declarations
1347 /// that are missing from the lookup table.
1348 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1349
1350 /// If \c true, lookups should only return identifier from
1351 /// DeclContext scope (for example TranslationUnit). Used in
1352 /// LookupQualifiedName()
1353 mutable uint64_t UseQualifiedLookup : 1;
1354 };
1355
1356 /// Number of bits in DeclContextBitfields.
1357 enum { NumDeclContextBits = 13 };
1358
1359 /// Stores the bits used by TagDecl.
1360 /// If modified NumTagDeclBits and the accessor
1361 /// methods in TagDecl should be updated appropriately.
1362 class TagDeclBitfields {
1363 friend class TagDecl;
1364 /// For the bits in DeclContextBitfields
1365 uint64_t : NumDeclContextBits;
1366
1367 /// The TagKind enum.
1368 uint64_t TagDeclKind : 3;
1369
1370 /// True if this is a definition ("struct foo {};"), false if it is a
1371 /// declaration ("struct foo;"). It is not considered a definition
1372 /// until the definition has been fully processed.
1373 uint64_t IsCompleteDefinition : 1;
1374
1375 /// True if this is currently being defined.
1376 uint64_t IsBeingDefined : 1;
1377
1378 /// True if this tag declaration is "embedded" (i.e., defined or declared
1379 /// for the very first time) in the syntax of a declarator.
1380 uint64_t IsEmbeddedInDeclarator : 1;
1381
1382 /// True if this tag is free standing, e.g. "struct foo;".
1383 uint64_t IsFreeStanding : 1;
1384
1385 /// Indicates whether it is possible for declarations of this kind
1386 /// to have an out-of-date definition.
1387 ///
1388 /// This option is only enabled when modules are enabled.
1389 uint64_t MayHaveOutOfDateDef : 1;
1390
1391 /// Has the full definition of this type been required by a use somewhere in
1392 /// the TU.
1393 uint64_t IsCompleteDefinitionRequired : 1;
1394 };
1395
1396 /// Number of non-inherited bits in TagDeclBitfields.
1397 enum { NumTagDeclBits = 9 };
1398
1399 /// Stores the bits used by EnumDecl.
1400 /// If modified NumEnumDeclBit and the accessor
1401 /// methods in EnumDecl should be updated appropriately.
1402 class EnumDeclBitfields {
1403 friend class EnumDecl;
1404 /// For the bits in DeclContextBitfields.
1405 uint64_t : NumDeclContextBits;
1406 /// For the bits in TagDeclBitfields.
1407 uint64_t : NumTagDeclBits;
1408
1409 /// Width in bits required to store all the non-negative
1410 /// enumerators of this enum.
1411 uint64_t NumPositiveBits : 8;
1412
1413 /// Width in bits required to store all the negative
1414 /// enumerators of this enum.
1415 uint64_t NumNegativeBits : 8;
1416
1417 /// True if this tag declaration is a scoped enumeration. Only
1418 /// possible in C++11 mode.
1419 uint64_t IsScoped : 1;
1420
1421 /// If this tag declaration is a scoped enum,
1422 /// then this is true if the scoped enum was declared using the class
1423 /// tag, false if it was declared with the struct tag. No meaning is
1424 /// associated if this tag declaration is not a scoped enum.
1425 uint64_t IsScopedUsingClassTag : 1;
1426
1427 /// True if this is an enumeration with fixed underlying type. Only
1428 /// possible in C++11, Microsoft extensions, or Objective C mode.
1429 uint64_t IsFixed : 1;
1430
1431 /// True if a valid hash is stored in ODRHash.
1432 uint64_t HasODRHash : 1;
1433 };
1434
1435 /// Number of non-inherited bits in EnumDeclBitfields.
1436 enum { NumEnumDeclBits = 20 };
1437
1438 /// Stores the bits used by RecordDecl.
1439 /// If modified NumRecordDeclBits and the accessor
1440 /// methods in RecordDecl should be updated appropriately.
1441 class RecordDeclBitfields {
1442 friend class RecordDecl;
1443 /// For the bits in DeclContextBitfields.
1444 uint64_t : NumDeclContextBits;
1445 /// For the bits in TagDeclBitfields.
1446 uint64_t : NumTagDeclBits;
1447
1448 /// This is true if this struct ends with a flexible
1449 /// array member (e.g. int X[]) or if this union contains a struct that does.
1450 /// If so, this cannot be contained in arrays or other structs as a member.
1451 uint64_t HasFlexibleArrayMember : 1;
1452
1453 /// Whether this is the type of an anonymous struct or union.
1454 uint64_t AnonymousStructOrUnion : 1;
1455
1456 /// This is true if this struct has at least one member
1457 /// containing an Objective-C object pointer type.
1458 uint64_t HasObjectMember : 1;
1459
1460 /// This is true if struct has at least one member of
1461 /// 'volatile' type.
1462 uint64_t HasVolatileMember : 1;
1463
1464 /// Whether the field declarations of this record have been loaded
1465 /// from external storage. To avoid unnecessary deserialization of
1466 /// methods/nested types we allow deserialization of just the fields
1467 /// when needed.
1468 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1469
1470 /// Basic properties of non-trivial C structs.
1471 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1472 uint64_t NonTrivialToPrimitiveCopy : 1;
1473 uint64_t NonTrivialToPrimitiveDestroy : 1;
1474
1475 /// The following bits indicate whether this is or contains a C union that
1476 /// is non-trivial to default-initialize, destruct, or copy. These bits
1477 /// imply the associated basic non-triviality predicates declared above.
1478 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1479 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1480 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1481
1482 /// Indicates whether this struct is destroyed in the callee.
1483 uint64_t ParamDestroyedInCallee : 1;
1484
1485 /// Represents the way this type is passed to a function.
1486 uint64_t ArgPassingRestrictions : 2;
1487 };
1488
1489 /// Number of non-inherited bits in RecordDeclBitfields.
1490 enum { NumRecordDeclBits = 14 };
1491
1492 /// Stores the bits used by OMPDeclareReductionDecl.
1493 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1494 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1495 class OMPDeclareReductionDeclBitfields {
1496 friend class OMPDeclareReductionDecl;
1497 /// For the bits in DeclContextBitfields
1498 uint64_t : NumDeclContextBits;
1499
1500 /// Kind of initializer,
1501 /// function call or omp_priv<init_expr> initializtion.
1502 uint64_t InitializerKind : 2;
1503 };
1504
1505 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1506 enum { NumOMPDeclareReductionDeclBits = 2 };
1507
1508 /// Stores the bits used by FunctionDecl.
1509 /// If modified NumFunctionDeclBits and the accessor
1510 /// methods in FunctionDecl and CXXDeductionGuideDecl
1511 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1512 class FunctionDeclBitfields {
1513 friend class FunctionDecl;
1514 /// For IsCopyDeductionCandidate
1515 friend class CXXDeductionGuideDecl;
1516 /// For the bits in DeclContextBitfields.
1517 uint64_t : NumDeclContextBits;
1518
1519 uint64_t SClass : 3;
1520 uint64_t IsInline : 1;
1521 uint64_t IsInlineSpecified : 1;
1522
1523 uint64_t IsVirtualAsWritten : 1;
1524 uint64_t IsPure : 1;
1525 uint64_t HasInheritedPrototype : 1;
1526 uint64_t HasWrittenPrototype : 1;
1527 uint64_t IsDeleted : 1;
1528 /// Used by CXXMethodDecl
1529 uint64_t IsTrivial : 1;
1530
1531 /// This flag indicates whether this function is trivial for the purpose of
1532 /// calls. This is meaningful only when this function is a copy/move
1533 /// constructor or a destructor.
1534 uint64_t IsTrivialForCall : 1;
1535
1536 uint64_t IsDefaulted : 1;
1537 uint64_t IsExplicitlyDefaulted : 1;
1538 uint64_t HasDefaultedFunctionInfo : 1;
1539 uint64_t HasImplicitReturnZero : 1;
1540 uint64_t IsLateTemplateParsed : 1;
1541
1542 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1543 uint64_t ConstexprKind : 2;
1544 uint64_t InstantiationIsPending : 1;
1545
1546 /// Indicates if the function uses __try.
1547 uint64_t UsesSEHTry : 1;
1548
1549 /// Indicates if the function was a definition
1550 /// but its body was skipped.
1551 uint64_t HasSkippedBody : 1;
1552
1553 /// Indicates if the function declaration will
1554 /// have a body, once we're done parsing it.
1555 uint64_t WillHaveBody : 1;
1556
1557 /// Indicates that this function is a multiversioned
1558 /// function using attribute 'target'.
1559 uint64_t IsMultiVersion : 1;
1560
1561 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1562 /// the Deduction Guide is the implicitly generated 'copy
1563 /// deduction candidate' (is used during overload resolution).
1564 uint64_t IsCopyDeductionCandidate : 1;
1565
1566 /// Store the ODRHash after first calculation.
1567 uint64_t HasODRHash : 1;
1568
1569 /// Indicates if the function uses Floating Point Constrained Intrinsics
1570 uint64_t UsesFPIntrin : 1;
1571 };
1572
1573 /// Number of non-inherited bits in FunctionDeclBitfields.
1574 enum { NumFunctionDeclBits = 27 };
1575
1576 /// Stores the bits used by CXXConstructorDecl. If modified
1577 /// NumCXXConstructorDeclBits and the accessor
1578 /// methods in CXXConstructorDecl should be updated appropriately.
1579 class CXXConstructorDeclBitfields {
1580 friend class CXXConstructorDecl;
1581 /// For the bits in DeclContextBitfields.
1582 uint64_t : NumDeclContextBits;
1583 /// For the bits in FunctionDeclBitfields.
1584 uint64_t : NumFunctionDeclBits;
1585
1586 /// 24 bits to fit in the remaining available space.
1587 /// Note that this makes CXXConstructorDeclBitfields take
1588 /// exactly 64 bits and thus the width of NumCtorInitializers
1589 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1590 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1591 uint64_t NumCtorInitializers : 21;
1592 uint64_t IsInheritingConstructor : 1;
1593
1594 /// Whether this constructor has a trail-allocated explicit specifier.
1595 uint64_t HasTrailingExplicitSpecifier : 1;
1596 /// If this constructor does't have a trail-allocated explicit specifier.
1597 /// Whether this constructor is explicit specified.
1598 uint64_t IsSimpleExplicit : 1;
1599 };
1600
1601 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1602 enum {
1603 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1604 };
1605
1606 /// Stores the bits used by ObjCMethodDecl.
1607 /// If modified NumObjCMethodDeclBits and the accessor
1608 /// methods in ObjCMethodDecl should be updated appropriately.
1609 class ObjCMethodDeclBitfields {
1610 friend class ObjCMethodDecl;
1611
1612 /// For the bits in DeclContextBitfields.
1613 uint64_t : NumDeclContextBits;
1614
1615 /// The conventional meaning of this method; an ObjCMethodFamily.
1616 /// This is not serialized; instead, it is computed on demand and
1617 /// cached.
1618 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1619
1620 /// instance (true) or class (false) method.
1621 uint64_t IsInstance : 1;
1622 uint64_t IsVariadic : 1;
1623
1624 /// True if this method is the getter or setter for an explicit property.
1625 uint64_t IsPropertyAccessor : 1;
1626
1627 /// True if this method is a synthesized property accessor stub.
1628 uint64_t IsSynthesizedAccessorStub : 1;
1629
1630 /// Method has a definition.
1631 uint64_t IsDefined : 1;
1632
1633 /// Method redeclaration in the same interface.
1634 uint64_t IsRedeclaration : 1;
1635
1636 /// Is redeclared in the same interface.
1637 mutable uint64_t HasRedeclaration : 1;
1638
1639 /// \@required/\@optional
1640 uint64_t DeclImplementation : 2;
1641
1642 /// in, inout, etc.
1643 uint64_t objcDeclQualifier : 7;
1644
1645 /// Indicates whether this method has a related result type.
1646 uint64_t RelatedResultType : 1;
1647
1648 /// Whether the locations of the selector identifiers are in a
1649 /// "standard" position, a enum SelectorLocationsKind.
1650 uint64_t SelLocsKind : 2;
1651
1652 /// Whether this method overrides any other in the class hierarchy.
1653 ///
1654 /// A method is said to override any method in the class's
1655 /// base classes, its protocols, or its categories' protocols, that has
1656 /// the same selector and is of the same kind (class or instance).
1657 /// A method in an implementation is not considered as overriding the same
1658 /// method in the interface or its categories.
1659 uint64_t IsOverriding : 1;
1660
1661 /// Indicates if the method was a definition but its body was skipped.
1662 uint64_t HasSkippedBody : 1;
1663 };
1664
1665 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1666 enum { NumObjCMethodDeclBits = 24 };
1667
1668 /// Stores the bits used by ObjCContainerDecl.
1669 /// If modified NumObjCContainerDeclBits and the accessor
1670 /// methods in ObjCContainerDecl should be updated appropriately.
1671 class ObjCContainerDeclBitfields {
1672 friend class ObjCContainerDecl;
1673 /// For the bits in DeclContextBitfields
1674 uint32_t : NumDeclContextBits;
1675
1676 // Not a bitfield but this saves space.
1677 // Note that ObjCContainerDeclBitfields is full.
1678 SourceLocation AtStart;
1679 };
1680
1681 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1682 /// Note that here we rely on the fact that SourceLocation is 32 bits
1683 /// wide. We check this with the static_assert in the ctor of DeclContext.
1684 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1685
1686 /// Stores the bits used by LinkageSpecDecl.
1687 /// If modified NumLinkageSpecDeclBits and the accessor
1688 /// methods in LinkageSpecDecl should be updated appropriately.
1689 class LinkageSpecDeclBitfields {
1690 friend class LinkageSpecDecl;
1691 /// For the bits in DeclContextBitfields.
1692 uint64_t : NumDeclContextBits;
1693
1694 /// The language for this linkage specification with values
1695 /// in the enum LinkageSpecDecl::LanguageIDs.
1696 uint64_t Language : 3;
1697
1698 /// True if this linkage spec has braces.
1699 /// This is needed so that hasBraces() returns the correct result while the
1700 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1701 /// not used, so it doesn't need to be serialized.
1702 uint64_t HasBraces : 1;
1703 };
1704
1705 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1706 enum { NumLinkageSpecDeclBits = 4 };
1707
1708 /// Stores the bits used by BlockDecl.
1709 /// If modified NumBlockDeclBits and the accessor
1710 /// methods in BlockDecl should be updated appropriately.
1711 class BlockDeclBitfields {
1712 friend class BlockDecl;
1713 /// For the bits in DeclContextBitfields.
1714 uint64_t : NumDeclContextBits;
1715
1716 uint64_t IsVariadic : 1;
1717 uint64_t CapturesCXXThis : 1;
1718 uint64_t BlockMissingReturnType : 1;
1719 uint64_t IsConversionFromLambda : 1;
1720
1721 /// A bit that indicates this block is passed directly to a function as a
1722 /// non-escaping parameter.
1723 uint64_t DoesNotEscape : 1;
1724
1725 /// A bit that indicates whether it's possible to avoid coying this block to
1726 /// the heap when it initializes or is assigned to a local variable with
1727 /// automatic storage.
1728 uint64_t CanAvoidCopyToHeap : 1;
1729 };
1730
1731 /// Number of non-inherited bits in BlockDeclBitfields.
1732 enum { NumBlockDeclBits = 5 };
1733
1734 /// Pointer to the data structure used to lookup declarations
1735 /// within this context (or a DependentStoredDeclsMap if this is a
1736 /// dependent context). We maintain the invariant that, if the map
1737 /// contains an entry for a DeclarationName (and we haven't lazily
1738 /// omitted anything), then it contains all relevant entries for that
1739 /// name (modulo the hasExternalDecls() flag).
1740 mutable StoredDeclsMap *LookupPtr = nullptr;
1741
1742protected:
1743 /// This anonymous union stores the bits belonging to DeclContext and classes
1744 /// deriving from it. The goal is to use otherwise wasted
1745 /// space in DeclContext to store data belonging to derived classes.
1746 /// The space saved is especially significient when pointers are aligned
1747 /// to 8 bytes. In this case due to alignment requirements we have a
1748 /// little less than 8 bytes free in DeclContext which we can use.
1749 /// We check that none of the classes in this union is larger than
1750 /// 8 bytes with static_asserts in the ctor of DeclContext.
1751 union {
1752 DeclContextBitfields DeclContextBits;
1753 TagDeclBitfields TagDeclBits;
1754 EnumDeclBitfields EnumDeclBits;
1755 RecordDeclBitfields RecordDeclBits;
1756 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1757 FunctionDeclBitfields FunctionDeclBits;
1758 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1759 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1760 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1761 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1762 BlockDeclBitfields BlockDeclBits;
1763
1764 static_assert(sizeof(DeclContextBitfields) <= 8,
1765 "DeclContextBitfields is larger than 8 bytes!");
1766 static_assert(sizeof(TagDeclBitfields) <= 8,
1767 "TagDeclBitfields is larger than 8 bytes!");
1768 static_assert(sizeof(EnumDeclBitfields) <= 8,
1769 "EnumDeclBitfields is larger than 8 bytes!");
1770 static_assert(sizeof(RecordDeclBitfields) <= 8,
1771 "RecordDeclBitfields is larger than 8 bytes!");
1772 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1773 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1774 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1775 "FunctionDeclBitfields is larger than 8 bytes!");
1776 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1777 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1778 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1779 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1780 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1781 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1782 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1783 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1784 static_assert(sizeof(BlockDeclBitfields) <= 8,
1785 "BlockDeclBitfields is larger than 8 bytes!");
1786 };
1787
1788 /// FirstDecl - The first declaration stored within this declaration
1789 /// context.
1790 mutable Decl *FirstDecl = nullptr;
1791
1792 /// LastDecl - The last declaration stored within this declaration
1793 /// context. FIXME: We could probably cache this value somewhere
1794 /// outside of the DeclContext, to reduce the size of DeclContext by
1795 /// another pointer.
1796 mutable Decl *LastDecl = nullptr;
1797
1798 /// Build up a chain of declarations.
1799 ///
1800 /// \returns the first/last pair of declarations.
1801 static std::pair<Decl *, Decl *>
1802 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1803
1804 DeclContext(Decl::Kind K);
1805
1806public:
1807 ~DeclContext();
1808
1809 Decl::Kind getDeclKind() const {
1810 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1811 }
1812
1813 const char *getDeclKindName() const;
1814
1815 /// getParent - Returns the containing DeclContext.
1816 DeclContext *getParent() {
1817 return cast<Decl>(this)->getDeclContext();
1818 }
1819 const DeclContext *getParent() const {
1820 return const_cast<DeclContext*>(this)->getParent();
1821 }
1822
1823 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1824 /// different from getParent, e.g.:
1825 ///
1826 /// namespace A {
1827 /// struct S;
1828 /// }
1829 /// struct A::S {}; // getParent() == namespace 'A'
1830 /// // getLexicalParent() == translation unit
1831 ///
1832 DeclContext *getLexicalParent() {
1833 return cast<Decl>(this)->getLexicalDeclContext();
1834 }
1835 const DeclContext *getLexicalParent() const {
1836 return const_cast<DeclContext*>(this)->getLexicalParent();
1837 }
1838
1839 DeclContext *getLookupParent();
1840
1841 const DeclContext *getLookupParent() const {
1842 return const_cast<DeclContext*>(this)->getLookupParent();
1843 }
1844
1845 ASTContext &getParentASTContext() const {
1846 return cast<Decl>(this)->getASTContext();
1847 }
1848
1849 bool isClosure() const { return getDeclKind() == Decl::Block; }
1850
1851 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1852 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1853 const BlockDecl *getInnermostBlockDecl() const;
1854
1855 bool isObjCContainer() const {
1856 switch (getDeclKind()) {
1857 case Decl::ObjCCategory:
1858 case Decl::ObjCCategoryImpl:
1859 case Decl::ObjCImplementation:
1860 case Decl::ObjCInterface:
1861 case Decl::ObjCProtocol:
1862 return true;
1863 default:
1864 return false;
1865 }
1866 }
1867
1868 bool isFunctionOrMethod() const {
1869 switch (getDeclKind()) {
1870 case Decl::Block:
1871 case Decl::Captured:
1872 case Decl::ObjCMethod:
1873 return true;
1874 default:
1875 return getDeclKind() >= Decl::firstFunction &&
1876 getDeclKind() <= Decl::lastFunction;
1877 }
1878 }
1879
1880 /// Test whether the context supports looking up names.
1881 bool isLookupContext() const {
1882 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1883 getDeclKind() != Decl::Export;
1884 }
1885
1886 bool isFileContext() const {
1887 return getDeclKind() == Decl::TranslationUnit ||
1888 getDeclKind() == Decl::Namespace;
1889 }
1890
1891 bool isTranslationUnit() const {
1892 return getDeclKind() == Decl::TranslationUnit;
1893 }
1894
1895 bool isRecord() const {
1896 return getDeclKind() >= Decl::firstRecord &&
48
Assuming the condition is false
49
Returning zero, which participates in a condition later
1897 getDeclKind() <= Decl::lastRecord;
1898 }
1899
1900 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1901
1902 bool isStdNamespace() const;
1903
1904 bool isInlineNamespace() const;
1905
1906 /// Determines whether this context is dependent on a
1907 /// template parameter.
1908 bool isDependentContext() const;
1909
1910 /// isTransparentContext - Determines whether this context is a
1911 /// "transparent" context, meaning that the members declared in this
1912 /// context are semantically declared in the nearest enclosing
1913 /// non-transparent (opaque) context but are lexically declared in
1914 /// this context. For example, consider the enumerators of an
1915 /// enumeration type:
1916 /// @code
1917 /// enum E {
1918 /// Val1
1919 /// };
1920 /// @endcode
1921 /// Here, E is a transparent context, so its enumerator (Val1) will
1922 /// appear (semantically) that it is in the same context of E.
1923 /// Examples of transparent contexts include: enumerations (except for
1924 /// C++0x scoped enums), and C++ linkage specifications.
1925 bool isTransparentContext() const;
1926
1927 /// Determines whether this context or some of its ancestors is a
1928 /// linkage specification context that specifies C linkage.
1929 bool isExternCContext() const;
1930
1931 /// Retrieve the nearest enclosing C linkage specification context.
1932 const LinkageSpecDecl *getExternCContext() const;
1933
1934 /// Determines whether this context or some of its ancestors is a
1935 /// linkage specification context that specifies C++ linkage.
1936 bool isExternCXXContext() const;
1937
1938 /// Determine whether this declaration context is equivalent
1939 /// to the declaration context DC.
1940 bool Equals(const DeclContext *DC) const {
1941 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1942 }
1943
1944 /// Determine whether this declaration context encloses the
1945 /// declaration context DC.
1946 bool Encloses(const DeclContext *DC) const;
1947
1948 /// Find the nearest non-closure ancestor of this context,
1949 /// i.e. the innermost semantic parent of this context which is not
1950 /// a closure. A context may be its own non-closure ancestor.
1951 Decl *getNonClosureAncestor();
1952 const Decl *getNonClosureAncestor() const {
1953 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1954 }
1955
1956 /// getPrimaryContext - There may be many different
1957 /// declarations of the same entity (including forward declarations
1958 /// of classes, multiple definitions of namespaces, etc.), each with
1959 /// a different set of declarations. This routine returns the
1960 /// "primary" DeclContext structure, which will contain the
1961 /// information needed to perform name lookup into this context.
1962 DeclContext *getPrimaryContext();
1963 const DeclContext *getPrimaryContext() const {
1964 return const_cast<DeclContext*>(this)->getPrimaryContext();
1965 }
1966
1967 /// getRedeclContext - Retrieve the context in which an entity conflicts with
1968 /// other entities of the same name, or where it is a redeclaration if the
1969 /// two entities are compatible. This skips through transparent contexts.
1970 DeclContext *getRedeclContext();
1971 const DeclContext *getRedeclContext() const {
1972 return const_cast<DeclContext *>(this)->getRedeclContext();
1973 }
1974
1975 /// Retrieve the nearest enclosing namespace context.
1976 DeclContext *getEnclosingNamespaceContext();
1977 const DeclContext *getEnclosingNamespaceContext() const {
1978 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
1979 }
1980
1981 /// Retrieve the outermost lexically enclosing record context.
1982 RecordDecl *getOuterLexicalRecordContext();
1983 const RecordDecl *getOuterLexicalRecordContext() const {
1984 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
1985 }
1986
1987 /// Test if this context is part of the enclosing namespace set of
1988 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
1989 /// isn't a namespace, this is equivalent to Equals().
1990 ///
1991 /// The enclosing namespace set of a namespace is the namespace and, if it is
1992 /// inline, its enclosing namespace, recursively.
1993 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
1994
1995 /// Collects all of the declaration contexts that are semantically
1996 /// connected to this declaration context.
1997 ///
1998 /// For declaration contexts that have multiple semantically connected but
1999 /// syntactically distinct contexts, such as C++ namespaces, this routine
2000 /// retrieves the complete set of such declaration contexts in source order.
2001 /// For example, given:
2002 ///
2003 /// \code
2004 /// namespace N {
2005 /// int x;
2006 /// }
2007 /// namespace N {
2008 /// int y;
2009 /// }
2010 /// \endcode
2011 ///
2012 /// The \c Contexts parameter will contain both definitions of N.
2013 ///
2014 /// \param Contexts Will be cleared and set to the set of declaration
2015 /// contexts that are semanticaly connected to this declaration context,
2016 /// in source order, including this context (which may be the only result,
2017 /// for non-namespace contexts).
2018 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2019
2020 /// decl_iterator - Iterates through the declarations stored
2021 /// within this context.
2022 class decl_iterator {
2023 /// Current - The current declaration.
2024 Decl *Current = nullptr;
2025
2026 public:
2027 using value_type = Decl *;
2028 using reference = const value_type &;
2029 using pointer = const value_type *;
2030 using iterator_category = std::forward_iterator_tag;
2031 using difference_type = std::ptrdiff_t;
2032
2033 decl_iterator() = default;
2034 explicit decl_iterator(Decl *C) : Current(C) {}
2035
2036 reference operator*() const { return Current; }
2037
2038 // This doesn't meet the iterator requirements, but it's convenient
2039 value_type operator->() const { return Current; }
2040
2041 decl_iterator& operator++() {
2042 Current = Current->getNextDeclInContext();
2043 return *this;
2044 }
2045
2046 decl_iterator operator++(int) {
2047 decl_iterator tmp(*this);
2048 ++(*this);
2049 return tmp;
2050 }
2051
2052 friend bool operator==(decl_iterator x, decl_iterator y) {
2053 return x.Current == y.Current;
2054 }
2055
2056 friend bool operator!=(decl_iterator x, decl_iterator y) {
2057 return x.Current != y.Current;
2058 }
2059 };
2060
2061 using decl_range = llvm::iterator_range<decl_iterator>;
2062
2063 /// decls_begin/decls_end - Iterate over the declarations stored in
2064 /// this context.
2065 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2066 decl_iterator decls_begin() const;
2067 decl_iterator decls_end() const { return decl_iterator(); }
2068 bool decls_empty() const;
2069
2070 /// noload_decls_begin/end - Iterate over the declarations stored in this
2071 /// context that are currently loaded; don't attempt to retrieve anything
2072 /// from an external source.
2073 decl_range noload_decls() const {
2074 return decl_range(noload_decls_begin(), noload_decls_end());
2075 }
2076 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2077 decl_iterator noload_decls_end() const { return decl_iterator(); }
2078
2079 /// specific_decl_iterator - Iterates over a subrange of
2080 /// declarations stored in a DeclContext, providing only those that
2081 /// are of type SpecificDecl (or a class derived from it). This
2082 /// iterator is used, for example, to provide iteration over just
2083 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2084 template<typename SpecificDecl>
2085 class specific_decl_iterator {
2086 /// Current - The current, underlying declaration iterator, which
2087 /// will either be NULL or will point to a declaration of
2088 /// type SpecificDecl.
2089 DeclContext::decl_iterator Current;
2090
2091 /// SkipToNextDecl - Advances the current position up to the next
2092 /// declaration of type SpecificDecl that also meets the criteria
2093 /// required by Acceptable.
2094 void SkipToNextDecl() {
2095 while (*Current && !isa<SpecificDecl>(*Current))
2096 ++Current;
2097 }
2098
2099 public:
2100 using value_type = SpecificDecl *;
2101 // TODO: Add reference and pointer types (with some appropriate proxy type)
2102 // if we ever have a need for them.
2103 using reference = void;
2104 using pointer = void;
2105 using difference_type =
2106 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2107 using iterator_category = std::forward_iterator_tag;
2108
2109 specific_decl_iterator() = default;
2110
2111 /// specific_decl_iterator - Construct a new iterator over a
2112 /// subset of the declarations the range [C,
2113 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2114 /// member function of SpecificDecl that should return true for
2115 /// all of the SpecificDecl instances that will be in the subset
2116 /// of iterators. For example, if you want Objective-C instance
2117 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2118 /// &ObjCMethodDecl::isInstanceMethod.
2119 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2120 SkipToNextDecl();
2121 }
2122
2123 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2124
2125 // This doesn't meet the iterator requirements, but it's convenient
2126 value_type operator->() const { return **this; }
2127
2128 specific_decl_iterator& operator++() {
2129 ++Current;
2130 SkipToNextDecl();
2131 return *this;
2132 }
2133
2134 specific_decl_iterator operator++(int) {
2135 specific_decl_iterator tmp(*this);
2136 ++(*this);
2137 return tmp;
2138 }
2139
2140 friend bool operator==(const specific_decl_iterator& x,
2141 const specific_decl_iterator& y) {
2142 return x.Current == y.Current;
2143 }
2144
2145 friend bool operator!=(const specific_decl_iterator& x,
2146 const specific_decl_iterator& y) {
2147 return x.Current != y.Current;
2148 }
2149 };
2150
2151 /// Iterates over a filtered subrange of declarations stored
2152 /// in a DeclContext.
2153 ///
2154 /// This iterator visits only those declarations that are of type
2155 /// SpecificDecl (or a class derived from it) and that meet some
2156 /// additional run-time criteria. This iterator is used, for
2157 /// example, to provide access to the instance methods within an
2158 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2159 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2160 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2161 class filtered_decl_iterator {
2162 /// Current - The current, underlying declaration iterator, which
2163 /// will either be NULL or will point to a declaration of
2164 /// type SpecificDecl.
2165 DeclContext::decl_iterator Current;
2166
2167 /// SkipToNextDecl - Advances the current position up to the next
2168 /// declaration of type SpecificDecl that also meets the criteria
2169 /// required by Acceptable.
2170 void SkipToNextDecl() {
2171 while (*Current &&
2172 (!isa<SpecificDecl>(*Current) ||
2173 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2174 ++Current;
2175 }
2176
2177 public:
2178 using value_type = SpecificDecl *;
2179 // TODO: Add reference and pointer types (with some appropriate proxy type)
2180 // if we ever have a need for them.
2181 using reference = void;
2182 using pointer = void;
2183 using difference_type =
2184 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2185 using iterator_category = std::forward_iterator_tag;
2186
2187 filtered_decl_iterator() = default;
2188
2189 /// filtered_decl_iterator - Construct a new iterator over a
2190 /// subset of the declarations the range [C,
2191 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2192 /// member function of SpecificDecl that should return true for
2193 /// all of the SpecificDecl instances that will be in the subset
2194 /// of iterators. For example, if you want Objective-C instance
2195 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2196 /// &ObjCMethodDecl::isInstanceMethod.
2197 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2198 SkipToNextDecl();
2199 }
2200
2201 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2202 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2203
2204 filtered_decl_iterator& operator++() {
2205 ++Current;
2206 SkipToNextDecl();
2207 return *this;
2208 }
2209
2210 filtered_decl_iterator operator++(int) {
2211 filtered_decl_iterator tmp(*this);
2212 ++(*this);
2213 return tmp;
2214 }
2215
2216 friend bool operator==(const filtered_decl_iterator& x,
2217 const filtered_decl_iterator& y) {
2218 return x.Current == y.Current;
2219 }
2220
2221 friend bool operator!=(const filtered_decl_iterator& x,
2222 const filtered_decl_iterator& y) {
2223 return x.Current != y.Current;
2224 }
2225 };
2226
2227 /// Add the declaration D into this context.
2228 ///
2229 /// This routine should be invoked when the declaration D has first
2230 /// been declared, to place D into the context where it was
2231 /// (lexically) defined. Every declaration must be added to one
2232 /// (and only one!) context, where it can be visited via
2233 /// [decls_begin(), decls_end()). Once a declaration has been added
2234 /// to its lexical context, the corresponding DeclContext owns the
2235 /// declaration.
2236 ///
2237 /// If D is also a NamedDecl, it will be made visible within its
2238 /// semantic context via makeDeclVisibleInContext.
2239 void addDecl(Decl *D);
2240
2241 /// Add the declaration D into this context, but suppress
2242 /// searches for external declarations with the same name.
2243 ///
2244 /// Although analogous in function to addDecl, this removes an
2245 /// important check. This is only useful if the Decl is being
2246 /// added in response to an external search; in all other cases,
2247 /// addDecl() is the right function to use.
2248 /// See the ASTImporter for use cases.
2249 void addDeclInternal(Decl *D);
2250
2251 /// Add the declaration D to this context without modifying
2252 /// any lookup tables.
2253 ///
2254 /// This is useful for some operations in dependent contexts where
2255 /// the semantic context might not be dependent; this basically
2256 /// only happens with friends.
2257 void addHiddenDecl(Decl *D);
2258
2259 /// Removes a declaration from this context.
2260 void removeDecl(Decl *D);
2261
2262 /// Checks whether a declaration is in this context.
2263 bool containsDecl(Decl *D) const;
2264
2265 /// Checks whether a declaration is in this context.
2266 /// This also loads the Decls from the external source before the check.
2267 bool containsDeclAndLoad(Decl *D) const;
2268
2269 using lookup_result = DeclContextLookupResult;
2270 using lookup_iterator = lookup_result::iterator;
2271
2272 /// lookup - Find the declarations (if any) with the given Name in
2273 /// this context. Returns a range of iterators that contains all of
2274 /// the declarations with this name, with object, function, member,
2275 /// and enumerator names preceding any tag name. Note that this
2276 /// routine will not look into parent contexts.
2277 lookup_result lookup(DeclarationName Name) const;
2278
2279 /// Find the declarations with the given name that are visible
2280 /// within this context; don't attempt to retrieve anything from an
2281 /// external source.
2282 lookup_result noload_lookup(DeclarationName Name);
2283
2284 /// A simplistic name lookup mechanism that performs name lookup
2285 /// into this declaration context without consulting the external source.
2286 ///
2287 /// This function should almost never be used, because it subverts the
2288 /// usual relationship between a DeclContext and the external source.
2289 /// See the ASTImporter for the (few, but important) use cases.
2290 ///
2291 /// FIXME: This is very inefficient; replace uses of it with uses of
2292 /// noload_lookup.
2293 void localUncachedLookup(DeclarationName Name,
2294 SmallVectorImpl<NamedDecl *> &Results);
2295
2296 /// Makes a declaration visible within this context.
2297 ///
2298 /// This routine makes the declaration D visible to name lookup
2299 /// within this context and, if this is a transparent context,
2300 /// within its parent contexts up to the first enclosing
2301 /// non-transparent context. Making a declaration visible within a
2302 /// context does not transfer ownership of a declaration, and a
2303 /// declaration can be visible in many contexts that aren't its
2304 /// lexical context.
2305 ///
2306 /// If D is a redeclaration of an existing declaration that is
2307 /// visible from this context, as determined by
2308 /// NamedDecl::declarationReplaces, the previous declaration will be
2309 /// replaced with D.
2310 void makeDeclVisibleInContext(NamedDecl *D);
2311
2312 /// all_lookups_iterator - An iterator that provides a view over the results
2313 /// of looking up every possible name.
2314 class all_lookups_iterator;
2315
2316 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2317
2318 lookups_range lookups() const;
2319 // Like lookups(), but avoids loading external declarations.
2320 // If PreserveInternalState, avoids building lookup data structures too.
2321 lookups_range noload_lookups(bool PreserveInternalState) const;
2322
2323 /// Iterators over all possible lookups within this context.
2324 all_lookups_iterator lookups_begin() const;
2325 all_lookups_iterator lookups_end() const;
2326
2327 /// Iterators over all possible lookups within this context that are
2328 /// currently loaded; don't attempt to retrieve anything from an external
2329 /// source.
2330 all_lookups_iterator noload_lookups_begin() const;
2331 all_lookups_iterator noload_lookups_end() const;
2332
2333 struct udir_iterator;
2334
2335 using udir_iterator_base =
2336 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2337 std::random_access_iterator_tag,
2338 UsingDirectiveDecl *>;
2339
2340 struct udir_iterator : udir_iterator_base {
2341 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2342
2343 UsingDirectiveDecl *operator*() const;
2344 };
2345
2346 using udir_range = llvm::iterator_range<udir_iterator>;
2347
2348 udir_range using_directives() const;
2349
2350 // These are all defined in DependentDiagnostic.h.
2351 class ddiag_iterator;
2352
2353 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2354
2355 inline ddiag_range ddiags() const;
2356
2357 // Low-level accessors
2358
2359 /// Mark that there are external lexical declarations that we need
2360 /// to include in our lookup table (and that are not available as external
2361 /// visible lookups). These extra lookup results will be found by walking
2362 /// the lexical declarations of this context. This should be used only if
2363 /// setHasExternalLexicalStorage() has been called on any decl context for
2364 /// which this is the primary context.
2365 void setMustBuildLookupTable() {
2366 assert(this == getPrimaryContext() &&((this == getPrimaryContext() && "should only be called on primary context"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 2367, __PRETTY_FUNCTION__))
2367 "should only be called on primary context")((this == getPrimaryContext() && "should only be called on primary context"
) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\""
, "/build/llvm-toolchain-snapshot-12~++20200917111122+b03c2b8395b/clang/include/clang/AST/DeclBase.h"
, 2367, __PRETTY_FUNCTION__))
;
2368 DeclContextBits.HasLazyExternalLexicalLookups = true;
2369 }
2370
2371 /// Retrieve the internal representation of the lookup structure.
2372 /// This may omit some names if we are lazily building the structure.
2373 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2374
2375 /// Ensure the lookup structure is fully-built and return it.
2376 StoredDeclsMap *buildLookup();
2377
2378 /// Whether this DeclContext has external storage containing
2379 /// additional declarations that are lexically in this context.
2380 bool hasExternalLexicalStorage() const {
2381 return DeclContextBits.ExternalLexicalStorage;
2382 }
2383
2384 /// State whether this DeclContext has external storage for
2385 /// declarations lexically in this context.
2386 void setHasExternalLexicalStorage(bool ES = true) const {
2387 DeclContextBits.ExternalLexicalStorage = ES;
2388 }
2389
2390 /// Whether this DeclContext has external storage containing
2391 /// additional declarations that are visible in this context.
2392 bool hasExternalVisibleStorage() const {
2393 return DeclContextBits.ExternalVisibleStorage;
2394 }
2395
2396 /// State whether this DeclContext has external storage for
2397 /// declarations visible in this context.
2398 void setHasExternalVisibleStorage(bool ES = true) const {
2399 DeclContextBits.ExternalVisibleStorage = ES;
2400 if (ES && LookupPtr)
2401 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2402 }
2403
2404 /// Determine whether the given declaration is stored in the list of
2405 /// declarations lexically within this context.
2406 bool isDeclInLexicalTraversal(const Decl *D) const {
2407 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2408 D == LastDecl);
2409 }
2410
2411 bool setUseQualifiedLookup(bool use = true) const {
2412 bool old_value = DeclContextBits.UseQualifiedLookup;
2413 DeclContextBits.UseQualifiedLookup = use;
2414 return old_value;
2415 }
2416
2417 bool shouldUseQualifiedLookup() const {
2418 return DeclContextBits.UseQualifiedLookup;
2419 }
2420
2421 static bool classof(const Decl *D);
2422 static bool classof(const DeclContext *D) { return true; }
2423
2424 void dumpDeclContext() const;
2425 void dumpLookups() const;
2426 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2427 bool Deserialize = false) const;
2428
2429private:
2430 /// Whether this declaration context has had externally visible
2431 /// storage added since the last lookup. In this case, \c LookupPtr's
2432 /// invariant may not hold and needs to be fixed before we perform
2433 /// another lookup.
2434 bool hasNeedToReconcileExternalVisibleStorage() const {
2435 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2436 }
2437
2438 /// State that this declaration context has had externally visible
2439 /// storage added since the last lookup. In this case, \c LookupPtr's
2440 /// invariant may not hold and needs to be fixed before we perform
2441 /// another lookup.
2442 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2443 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2444 }
2445
2446 /// If \c true, this context may have local lexical declarations
2447 /// that are missing from the lookup table.
2448 bool hasLazyLocalLexicalLookups() const {
2449 return DeclContextBits.HasLazyLocalLexicalLookups;
2450 }
2451
2452 /// If \c true, this context may have local lexical declarations
2453 /// that are missing from the lookup table.
2454 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2455 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2456 }
2457
2458 /// If \c true, the external source may have lexical declarations
2459 /// that are missing from the lookup table.
2460 bool hasLazyExternalLexicalLookups() const {
2461 return DeclContextBits.HasLazyExternalLexicalLookups;
2462 }
2463
2464 /// If \c true, the external source may have lexical declarations
2465 /// that are missing from the lookup table.
2466 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2467 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2468 }
2469
2470 void reconcileExternalVisibleStorage() const;
2471 bool LoadLexicalDeclsFromExternalStorage() const;
2472
2473 /// Makes a declaration visible within this context, but
2474 /// suppresses searches for external declarations with the same
2475 /// name.
2476 ///
2477 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2478 /// use of addDeclInternal().
2479 void makeDeclVisibleInContextInternal(NamedDecl *D);
2480
2481 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2482
2483 void loadLazyLocalLexicalLookups();
2484 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2485 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2486 bool Rediscoverable);
2487 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2488};
2489
2490inline bool Decl::isTemplateParameter() const {
2491 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2492 getKind() == TemplateTemplateParm;
2493}
2494
2495// Specialization selected when ToTy is not a known subclass of DeclContext.
2496template <class ToTy,
2497 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2498struct cast_convert_decl_context {
2499 static const ToTy *doit(const DeclContext *Val) {
2500 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2501 }
2502
2503 static ToTy *doit(DeclContext *Val) {
2504 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2505 }
2506};
2507
2508// Specialization selected when ToTy is a known subclass of DeclContext.
2509template <class ToTy>
2510struct cast_convert_decl_context<ToTy, true> {
2511 static const ToTy *doit(const DeclContext *Val) {
2512 return static_cast<const ToTy*>(Val);
2513 }
2514
2515 static ToTy *doit(DeclContext *Val) {
2516 return static_cast<ToTy*>(Val);
2517 }
2518};
2519
2520} // namespace clang
2521
2522namespace llvm {
2523
2524/// isa<T>(DeclContext*)
2525template <typename To>
2526struct isa_impl<To, ::clang::DeclContext> {
2527 static bool doit(const ::clang::DeclContext &Val) {
2528 return To::classofKind(Val.getDeclKind());
2529 }
2530};
2531
2532/// cast<T>(DeclContext*)
2533template<class ToTy>
2534struct cast_convert_val<ToTy,
2535 const ::clang::DeclContext,const ::clang::DeclContext> {
2536 static const ToTy &doit(const ::clang::DeclContext &Val) {
2537 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2538 }
2539};
2540
2541template<class ToTy>
2542struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2543 static ToTy &doit(::clang::DeclContext &Val) {
2544 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2545 }
2546};
2547
2548template<class ToTy>
2549struct cast_convert_val<ToTy,
2550 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2551 static const ToTy *doit(const ::clang::DeclContext *Val) {
2552 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2553 }
2554};
2555
2556template<class ToTy>
2557struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2558 static ToTy *doit(::clang::DeclContext *Val) {
2559 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2560 }
2561};
2562
2563/// Implement cast_convert_val for Decl -> DeclContext conversions.
2564template<class FromTy>
2565struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2566 static ::clang::DeclContext &doit(const FromTy &Val) {
2567 return *FromTy::castToDeclContext(&Val);
2568 }
2569};
2570
2571template<class FromTy>
2572struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2573 static ::clang::DeclContext *doit(const FromTy *Val) {
2574 return FromTy::castToDeclContext(Val);
2575 }
2576};
2577
2578template<class FromTy>
2579struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2580 static const ::clang::DeclContext &doit(const FromTy &Val) {
2581 return *FromTy::castToDeclContext(&Val);
2582 }
2583};
2584
2585template<class FromTy>
2586struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2587 static const ::clang::DeclContext *doit(const FromTy *Val) {
2588 return FromTy::castToDeclContext(Val);
2589 }
2590};
2591
2592} // namespace llvm
2593
2594#endif // LLVM_CLANG_AST_DECLBASE_H