Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-26-233846-219801-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/Sema/SemaDecl.cpp

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