Bug Summary

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