Bug Summary

File:tools/clang/lib/Sema/SemaDecl.cpp
Warning:line 16016, column 7
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~svn374877/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn374877/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn374877/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~svn374877/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn374877=. -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-233810-7101-1 -x c++ /build/llvm-toolchain-snapshot-10~svn374877/tools/clang/lib/Sema/SemaDecl.cpp

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