Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaDecl.cpp

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