Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 16614, column 9
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.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/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.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191=. -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-11-21-121427-42170-1 -x c++ /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp

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