Bug Summary

File:tools/clang/lib/Sema/SemaDecl.cpp
Warning:line 12500, column 16
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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -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~svn374814/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374814/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374814/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374814/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374814/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374814/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~svn374814/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374814=. -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-10-15-035155-28452-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374814/tools/clang/lib/Sema/SemaDecl.cpp

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