Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 3681, 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~++20201029100616+6c2ad4cf875/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/clang/include -I /build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/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~++20201029100616+6c2ad4cf875/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875=. -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-10-30-042338-28487-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201029100616+6c2ad4cf875/clang/lib/Sema/SemaDecl.cpp

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