Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Sema/SemaDecl.cpp

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