Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-09-26-161721-17566-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaDecl.cpp

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