Bug Summary

File:tools/clang/lib/Sema/SemaDecl.cpp
Warning:line 11147, column 16
Called C++ object pointer is uninitialized

Annotated Source Code

1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TypeLocBuilder.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/CommentDiagnostic.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/ExprCXX.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 : 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 private:
110 bool AllowInvalidDecl;
111 bool WantClassName;
112 bool AllowTemplates;
113 bool AllowNonTemplates;
114};
115
116} // end anonymous namespace
117
118/// \brief Determine whether the token kind starts a simple-type-specifier.
119bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120 switch (Kind) {
121 // FIXME: Take into account the current language when deciding whether a
122 // token kind is a valid type specifier
123 case tok::kw_short:
124 case tok::kw_long:
125 case tok::kw___int64:
126 case tok::kw___int128:
127 case tok::kw_signed:
128 case tok::kw_unsigned:
129 case tok::kw_void:
130 case tok::kw_char:
131 case tok::kw_int:
132 case tok::kw_half:
133 case tok::kw_float:
134 case tok::kw_double:
135 case tok::kw___float128:
136 case tok::kw_wchar_t:
137 case tok::kw_bool:
138 case tok::kw___underlying_type:
139 case tok::kw___auto_type:
140 return true;
141
142 case tok::annot_typename:
143 case tok::kw_char16_t:
144 case tok::kw_char32_t:
145 case tok::kw_typeof:
146 case tok::annot_decltype:
147 case tok::kw_decltype:
148 return getLangOpts().CPlusPlus;
149
150 default:
151 break;
152 }
153
154 return false;
155}
156
157namespace {
158enum class UnqualifiedTypeNameLookupResult {
159 NotFound,
160 FoundNonType,
161 FoundType
162};
163} // end anonymous namespace
164
165/// \brief Tries to perform unqualified lookup of the type decls in bases for
166/// dependent class.
167/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
168/// type decl, \a FoundType if only type decls are found.
169static UnqualifiedTypeNameLookupResult
170lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
171 SourceLocation NameLoc,
172 const CXXRecordDecl *RD) {
173 if (!RD->hasDefinition())
174 return UnqualifiedTypeNameLookupResult::NotFound;
175 // Look for type decls in base classes.
176 UnqualifiedTypeNameLookupResult FoundTypeDecl =
177 UnqualifiedTypeNameLookupResult::NotFound;
178 for (const auto &Base : RD->bases()) {
179 const CXXRecordDecl *BaseRD = nullptr;
180 if (auto *BaseTT = Base.getType()->getAs<TagType>())
181 BaseRD = BaseTT->getAsCXXRecordDecl();
182 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
183 // Look for type decls in dependent base classes that have known primary
184 // templates.
185 if (!TST || !TST->isDependentType())
186 continue;
187 auto *TD = TST->getTemplateName().getAsTemplateDecl();
188 if (!TD)
189 continue;
190 if (auto *BasePrimaryTemplate =
191 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
192 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
193 BaseRD = BasePrimaryTemplate;
194 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
195 if (const ClassTemplatePartialSpecializationDecl *PS =
196 CTD->findPartialSpecialization(Base.getType()))
197 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
198 BaseRD = PS;
199 }
200 }
201 }
202 if (BaseRD) {
203 for (NamedDecl *ND : BaseRD->lookup(&II)) {
204 if (!isa<TypeDecl>(ND))
205 return UnqualifiedTypeNameLookupResult::FoundNonType;
206 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
207 }
208 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
209 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
210 case UnqualifiedTypeNameLookupResult::FoundNonType:
211 return UnqualifiedTypeNameLookupResult::FoundNonType;
212 case UnqualifiedTypeNameLookupResult::FoundType:
213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214 break;
215 case UnqualifiedTypeNameLookupResult::NotFound:
216 break;
217 }
218 }
219 }
220 }
221
222 return FoundTypeDecl;
223}
224
225static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
226 const IdentifierInfo &II,
227 SourceLocation NameLoc) {
228 // Lookup in the parent class template context, if any.
229 const CXXRecordDecl *RD = nullptr;
230 UnqualifiedTypeNameLookupResult FoundTypeDecl =
231 UnqualifiedTypeNameLookupResult::NotFound;
232 for (DeclContext *DC = S.CurContext;
233 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
234 DC = DC->getParent()) {
235 // Look for type decls in dependent base classes that have known primary
236 // templates.
237 RD = dyn_cast<CXXRecordDecl>(DC);
238 if (RD && RD->getDescribedClassTemplate())
239 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
240 }
241 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
242 return nullptr;
243
244 // We found some types in dependent base classes. Recover as if the user
245 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
246 // lookup during template instantiation.
247 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
248
249 ASTContext &Context = S.Context;
250 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
251 cast<Type>(Context.getRecordType(RD)));
252 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
253
254 CXXScopeSpec SS;
255 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
256
257 TypeLocBuilder Builder;
258 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
259 DepTL.setNameLoc(NameLoc);
260 DepTL.setElaboratedKeywordLoc(SourceLocation());
261 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
262 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
263}
264
265/// \brief If the identifier refers to a type name within this scope,
266/// return the declaration of that type.
267///
268/// This routine performs ordinary name lookup of the identifier II
269/// within the given scope, with optional C++ scope specifier SS, to
270/// determine whether the name refers to a type. If so, returns an
271/// opaque pointer (actually a QualType) corresponding to that
272/// type. Otherwise, returns NULL.
273ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
274 Scope *S, CXXScopeSpec *SS,
275 bool isClassName, bool HasTrailingDot,
276 ParsedType ObjectTypePtr,
277 bool IsCtorOrDtorName,
278 bool WantNontrivialTypeSourceInfo,
279 bool IsClassTemplateDeductionContext,
280 IdentifierInfo **CorrectedII) {
281 // FIXME: Consider allowing this outside C++1z mode as an extension.
282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
283 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName &&
284 !isClassName && !HasTrailingDot;
285
286 // Determine where we will perform name lookup.
287 DeclContext *LookupCtx = nullptr;
288 if (ObjectTypePtr) {
289 QualType ObjectType = ObjectTypePtr.get();
290 if (ObjectType->isRecordType())
291 LookupCtx = computeDeclContext(ObjectType);
292 } else if (SS && SS->isNotEmpty()) {
293 LookupCtx = computeDeclContext(*SS, false);
294
295 if (!LookupCtx) {
296 if (isDependentScopeSpecifier(*SS)) {
297 // C++ [temp.res]p3:
298 // A qualified-id that refers to a type and in which the
299 // nested-name-specifier depends on a template-parameter (14.6.2)
300 // shall be prefixed by the keyword typename to indicate that the
301 // qualified-id denotes a type, forming an
302 // elaborated-type-specifier (7.1.5.3).
303 //
304 // We therefore do not perform any name lookup if the result would
305 // refer to a member of an unknown specialization.
306 if (!isClassName && !IsCtorOrDtorName)
307 return nullptr;
308
309 // We know from the grammar that this name refers to a type,
310 // so build a dependent node to describe the type.
311 if (WantNontrivialTypeSourceInfo)
312 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
313
314 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
315 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
316 II, NameLoc);
317 return ParsedType::make(T);
318 }
319
320 return nullptr;
321 }
322
323 if (!LookupCtx->isDependentContext() &&
324 RequireCompleteDeclContext(*SS, LookupCtx))
325 return nullptr;
326 }
327
328 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
329 // lookup for class-names.
330 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
331 LookupOrdinaryName;
332 LookupResult Result(*this, &II, NameLoc, Kind);
333 if (LookupCtx) {
334 // Perform "qualified" name lookup into the declaration context we
335 // computed, which is either the type of the base of a member access
336 // expression or the declaration context associated with a prior
337 // nested-name-specifier.
338 LookupQualifiedName(Result, LookupCtx);
339
340 if (ObjectTypePtr && Result.empty()) {
341 // C++ [basic.lookup.classref]p3:
342 // If the unqualified-id is ~type-name, the type-name is looked up
343 // in the context of the entire postfix-expression. If the type T of
344 // the object expression is of a class type C, the type-name is also
345 // looked up in the scope of class C. At least one of the lookups shall
346 // find a name that refers to (possibly cv-qualified) T.
347 LookupName(Result, S);
348 }
349 } else {
350 // Perform unqualified name lookup.
351 LookupName(Result, S);
352
353 // For unqualified lookup in a class template in MSVC mode, look into
354 // dependent base classes where the primary class template is known.
355 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
356 if (ParsedType TypeInBase =
357 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
358 return TypeInBase;
359 }
360 }
361
362 NamedDecl *IIDecl = nullptr;
363 switch (Result.getResultKind()) {
364 case LookupResult::NotFound:
365 case LookupResult::NotFoundInCurrentInstantiation:
366 if (CorrectedII) {
367 TypoCorrection Correction =
368 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
369 llvm::make_unique<TypeNameValidatorCCC>(
370 true, isClassName, AllowDeducedTemplate),
371 CTK_ErrorRecovery);
372 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
373 TemplateTy Template;
374 bool MemberOfUnknownSpecialization;
375 UnqualifiedId TemplateName;
376 TemplateName.setIdentifier(NewII, NameLoc);
377 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
378 CXXScopeSpec NewSS, *NewSSPtr = SS;
379 if (SS && NNS) {
380 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
381 NewSSPtr = &NewSS;
382 }
383 if (Correction && (NNS || NewII != &II) &&
384 // Ignore a correction to a template type as the to-be-corrected
385 // identifier is not a template (typo correction for template names
386 // is handled elsewhere).
387 !(getLangOpts().CPlusPlus && NewSSPtr &&
388 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
389 Template, MemberOfUnknownSpecialization))) {
390 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
391 isClassName, HasTrailingDot, ObjectTypePtr,
392 IsCtorOrDtorName,
393 WantNontrivialTypeSourceInfo,
394 IsClassTemplateDeductionContext);
395 if (Ty) {
396 diagnoseTypo(Correction,
397 PDiag(diag::err_unknown_type_or_class_name_suggest)
398 << Result.getLookupName() << isClassName);
399 if (SS && NNS)
400 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
401 *CorrectedII = NewII;
402 return Ty;
403 }
404 }
405 }
406 // If typo correction failed or was not performed, fall through
407 LLVM_FALLTHROUGH[[clang::fallthrough]];
408 case LookupResult::FoundOverloaded:
409 case LookupResult::FoundUnresolvedValue:
410 Result.suppressDiagnostics();
411 return nullptr;
412
413 case LookupResult::Ambiguous:
414 // Recover from type-hiding ambiguities by hiding the type. We'll
415 // do the lookup again when looking for an object, and we can
416 // diagnose the error then. If we don't do this, then the error
417 // about hiding the type will be immediately followed by an error
418 // that only makes sense if the identifier was treated like a type.
419 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
420 Result.suppressDiagnostics();
421 return nullptr;
422 }
423
424 // Look to see if we have a type anywhere in the list of results.
425 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
426 Res != ResEnd; ++Res) {
427 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
428 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
429 if (!IIDecl ||
430 (*Res)->getLocation().getRawEncoding() <
431 IIDecl->getLocation().getRawEncoding())
432 IIDecl = *Res;
433 }
434 }
435
436 if (!IIDecl) {
437 // None of the entities we found is a type, so there is no way
438 // to even assume that the result is a type. In this case, don't
439 // complain about the ambiguity. The parser will either try to
440 // perform this lookup again (e.g., as an object name), which
441 // will produce the ambiguity, or will complain that it expected
442 // a type name.
443 Result.suppressDiagnostics();
444 return nullptr;
445 }
446
447 // We found a type within the ambiguous lookup; diagnose the
448 // ambiguity and then return that type. This might be the right
449 // answer, or it might not be, but it suppresses any attempt to
450 // perform the name lookup again.
451 break;
452
453 case LookupResult::Found:
454 IIDecl = Result.getFoundDecl();
455 break;
456 }
457
458 assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void
> (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 458, __PRETTY_FUNCTION__))
;
459
460 QualType T;
461 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
462 // C++ [class.qual]p2: A lookup that would find the injected-class-name
463 // instead names the constructors of the class, except when naming a class.
464 // This is ill-formed when we're not actually forming a ctor or dtor name.
465 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
466 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
467 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
468 FoundRD->isInjectedClassName() &&
469 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
470 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
471 << &II << /*Type*/1;
472
473 DiagnoseUseOfDecl(IIDecl, NameLoc);
474
475 T = Context.getTypeDeclType(TD);
476 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
477 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
478 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
479 if (!HasTrailingDot)
480 T = Context.getObjCInterfaceType(IDecl);
481 } else if (AllowDeducedTemplate) {
482 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
483 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
484 QualType(), false);
485 }
486
487 if (T.isNull()) {
488 // If it's not plausibly a type, suppress diagnostics.
489 Result.suppressDiagnostics();
490 return nullptr;
491 }
492
493 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
494 // constructor or destructor name (in such a case, the scope specifier
495 // will be attached to the enclosing Expr or Decl node).
496 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
497 !isa<ObjCInterfaceDecl>(IIDecl)) {
498 if (WantNontrivialTypeSourceInfo) {
499 // Construct a type with type-source information.
500 TypeLocBuilder Builder;
501 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
502
503 T = getElaboratedType(ETK_None, *SS, T);
504 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
505 ElabTL.setElaboratedKeywordLoc(SourceLocation());
506 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
507 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
508 } else {
509 T = getElaboratedType(ETK_None, *SS, T);
510 }
511 }
512
513 return ParsedType::make(T);
514}
515
516// Builds a fake NNS for the given decl context.
517static NestedNameSpecifier *
518synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
519 for (;; DC = DC->getLookupParent()) {
520 DC = DC->getPrimaryContext();
521 auto *ND = dyn_cast<NamespaceDecl>(DC);
522 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
523 return NestedNameSpecifier::Create(Context, nullptr, ND);
524 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
525 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
526 RD->getTypeForDecl());
527 else if (isa<TranslationUnitDecl>(DC))
528 return NestedNameSpecifier::GlobalSpecifier(Context);
529 }
530 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 530)
;
531}
532
533/// Find the parent class with dependent bases of the innermost enclosing method
534/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
535/// up allowing unqualified dependent type names at class-level, which MSVC
536/// correctly rejects.
537static const CXXRecordDecl *
538findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
539 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
540 DC = DC->getPrimaryContext();
541 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
542 if (MD->getParent()->hasAnyDependentBases())
543 return MD->getParent();
544 }
545 return nullptr;
546}
547
548ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
549 SourceLocation NameLoc,
550 bool IsTemplateTypeArg) {
551 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 551, __PRETTY_FUNCTION__))
;
552
553 NestedNameSpecifier *NNS = nullptr;
554 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
555 // If we weren't able to parse a default template argument, delay lookup
556 // until instantiation time by making a non-dependent DependentTypeName. We
557 // pretend we saw a NestedNameSpecifier referring to the current scope, and
558 // lookup is retried.
559 // FIXME: This hurts our diagnostic quality, since we get errors like "no
560 // type named 'Foo' in 'current_namespace'" when the user didn't write any
561 // name specifiers.
562 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
563 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
564 } else if (const CXXRecordDecl *RD =
565 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
566 // Build a DependentNameType that will perform lookup into RD at
567 // instantiation time.
568 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
569 RD->getTypeForDecl());
570
571 // Diagnose that this identifier was undeclared, and retry the lookup during
572 // template instantiation.
573 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
574 << RD;
575 } else {
576 // This is not a situation that we should recover from.
577 return ParsedType();
578 }
579
580 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
581
582 // Build type location information. We synthesized the qualifier, so we have
583 // to build a fake NestedNameSpecifierLoc.
584 NestedNameSpecifierLocBuilder NNSLocBuilder;
585 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
586 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
587
588 TypeLocBuilder Builder;
589 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
590 DepTL.setNameLoc(NameLoc);
591 DepTL.setElaboratedKeywordLoc(SourceLocation());
592 DepTL.setQualifierLoc(QualifierLoc);
593 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
594}
595
596/// isTagName() - This method is called *for error recovery purposes only*
597/// to determine if the specified name is a valid tag name ("struct foo"). If
598/// so, this returns the TST for the tag corresponding to it (TST_enum,
599/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
600/// cases in C where the user forgot to specify the tag.
601DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
602 // Do a tag name lookup in this scope.
603 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
604 LookupName(R, S, false);
605 R.suppressDiagnostics();
606 if (R.getResultKind() == LookupResult::Found)
607 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
608 switch (TD->getTagKind()) {
609 case TTK_Struct: return DeclSpec::TST_struct;
610 case TTK_Interface: return DeclSpec::TST_interface;
611 case TTK_Union: return DeclSpec::TST_union;
612 case TTK_Class: return DeclSpec::TST_class;
613 case TTK_Enum: return DeclSpec::TST_enum;
614 }
615 }
616
617 return DeclSpec::TST_unspecified;
618}
619
620/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
621/// if a CXXScopeSpec's type is equal to the type of one of the base classes
622/// then downgrade the missing typename error to a warning.
623/// This is needed for MSVC compatibility; Example:
624/// @code
625/// template<class T> class A {
626/// public:
627/// typedef int TYPE;
628/// };
629/// template<class T> class B : public A<T> {
630/// public:
631/// A<T>::TYPE a; // no typename required because A<T> is a base class.
632/// };
633/// @endcode
634bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
635 if (CurContext->isRecord()) {
636 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
637 return true;
638
639 const Type *Ty = SS->getScopeRep()->getAsType();
640
641 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
642 for (const auto &Base : RD->bases())
643 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
644 return true;
645 return S->isFunctionPrototypeScope();
646 }
647 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
648}
649
650void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
651 SourceLocation IILoc,
652 Scope *S,
653 CXXScopeSpec *SS,
654 ParsedType &SuggestedType,
655 bool IsTemplateName) {
656 // Don't report typename errors for editor placeholders.
657 if (II->isEditorPlaceholder())
658 return;
659 // We don't have anything to suggest (yet).
660 SuggestedType = nullptr;
661
662 // There may have been a typo in the name of the type. Look up typo
663 // results, in case we have something that we can suggest.
664 if (TypoCorrection Corrected =
665 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
666 llvm::make_unique<TypeNameValidatorCCC>(
667 false, false, IsTemplateName, !IsTemplateName),
668 CTK_ErrorRecovery)) {
669 // FIXME: Support error recovery for the template-name case.
670 bool CanRecover = !IsTemplateName;
671 if (Corrected.isKeyword()) {
672 // We corrected to a keyword.
673 diagnoseTypo(Corrected,
674 PDiag(IsTemplateName ? diag::err_no_template_suggest
675 : diag::err_unknown_typename_suggest)
676 << II);
677 II = Corrected.getCorrectionAsIdentifierInfo();
678 } else {
679 // We found a similarly-named type or interface; suggest that.
680 if (!SS || !SS->isSet()) {
681 diagnoseTypo(Corrected,
682 PDiag(IsTemplateName ? diag::err_no_template_suggest
683 : diag::err_unknown_typename_suggest)
684 << II, CanRecover);
685 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
686 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
687 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
688 II->getName().equals(CorrectedStr);
689 diagnoseTypo(Corrected,
690 PDiag(IsTemplateName
691 ? diag::err_no_member_template_suggest
692 : diag::err_unknown_nested_typename_suggest)
693 << II << DC << DroppedSpecifier << SS->getRange(),
694 CanRecover);
695 } else {
696 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 696)
;
697 }
698
699 if (!CanRecover)
700 return;
701
702 CXXScopeSpec tmpSS;
703 if (Corrected.getCorrectionSpecifier())
704 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
705 SourceRange(IILoc));
706 // FIXME: Support class template argument deduction here.
707 SuggestedType =
708 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
709 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
710 /*IsCtorOrDtorName=*/false,
711 /*NonTrivialTypeSourceInfo=*/true);
712 }
713 return;
714 }
715
716 if (getLangOpts().CPlusPlus && !IsTemplateName) {
717 // See if II is a class template that the user forgot to pass arguments to.
718 UnqualifiedId Name;
719 Name.setIdentifier(II, IILoc);
720 CXXScopeSpec EmptySS;
721 TemplateTy TemplateResult;
722 bool MemberOfUnknownSpecialization;
723 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
724 Name, nullptr, true, TemplateResult,
725 MemberOfUnknownSpecialization) == TNK_Type_template) {
726 TemplateName TplName = TemplateResult.get();
727 Diag(IILoc, diag::err_template_missing_args)
728 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
729 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
730 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
731 << TplDecl->getTemplateParameters()->getSourceRange();
732 }
733 return;
734 }
735 }
736
737 // FIXME: Should we move the logic that tries to recover from a missing tag
738 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
739
740 if (!SS || (!SS->isSet() && !SS->isInvalid()))
741 Diag(IILoc, IsTemplateName ? diag::err_no_template
742 : diag::err_unknown_typename)
743 << II;
744 else if (DeclContext *DC = computeDeclContext(*SS, false))
745 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
746 : diag::err_typename_nested_not_found)
747 << II << DC << SS->getRange();
748 else if (isDependentScopeSpecifier(*SS)) {
749 unsigned DiagID = diag::err_typename_missing;
750 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
751 DiagID = diag::ext_typename_missing;
752
753 Diag(SS->getRange().getBegin(), DiagID)
754 << SS->getScopeRep() << II->getName()
755 << SourceRange(SS->getRange().getBegin(), IILoc)
756 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
757 SuggestedType = ActOnTypenameType(S, SourceLocation(),
758 *SS, *II, IILoc).get();
759 } else {
760 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 761, __PRETTY_FUNCTION__))
761 "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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 761, __PRETTY_FUNCTION__))
;
762 }
763}
764
765/// \brief Determine whether the given result set contains either a type name
766/// or
767static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
768 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
769 NextToken.is(tok::less);
770
771 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
772 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
773 return true;
774
775 if (CheckTemplate && isa<TemplateDecl>(*I))
776 return true;
777 }
778
779 return false;
780}
781
782static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
783 Scope *S, CXXScopeSpec &SS,
784 IdentifierInfo *&Name,
785 SourceLocation NameLoc) {
786 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
787 SemaRef.LookupParsedName(R, S, &SS);
788 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
789 StringRef FixItTagName;
790 switch (Tag->getTagKind()) {
791 case TTK_Class:
792 FixItTagName = "class ";
793 break;
794
795 case TTK_Enum:
796 FixItTagName = "enum ";
797 break;
798
799 case TTK_Struct:
800 FixItTagName = "struct ";
801 break;
802
803 case TTK_Interface:
804 FixItTagName = "__interface ";
805 break;
806
807 case TTK_Union:
808 FixItTagName = "union ";
809 break;
810 }
811
812 StringRef TagName = FixItTagName.drop_back();
813 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
814 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
815 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
816
817 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
818 I != IEnd; ++I)
819 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
820 << Name << TagName;
821
822 // Replace lookup results with just the tag decl.
823 Result.clear(Sema::LookupTagName);
824 SemaRef.LookupParsedName(Result, S, &SS);
825 return true;
826 }
827
828 return false;
829}
830
831/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
832static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
833 QualType T, SourceLocation NameLoc) {
834 ASTContext &Context = S.Context;
835
836 TypeLocBuilder Builder;
837 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
838
839 T = S.getElaboratedType(ETK_None, SS, T);
840 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
841 ElabTL.setElaboratedKeywordLoc(SourceLocation());
842 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
843 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
844}
845
846Sema::NameClassification
847Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
848 SourceLocation NameLoc, const Token &NextToken,
849 bool IsAddressOfOperand,
850 std::unique_ptr<CorrectionCandidateCallback> CCC) {
851 DeclarationNameInfo NameInfo(Name, NameLoc);
852 ObjCMethodDecl *CurMethod = getCurMethodDecl();
853
854 if (NextToken.is(tok::coloncolon)) {
855 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
856 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
857 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858 isCurrentClassName(*Name, S, &SS)) {
859 // Per [class.qual]p2, this names the constructors of SS, not the
860 // injected-class-name. We don't have a classification for that.
861 // There's not much point caching this result, since the parser
862 // will reject it later.
863 return NameClassification::Unknown();
864 }
865
866 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
867 LookupParsedName(Result, S, &SS, !CurMethod);
868
869 // For unqualified lookup in a class template in MSVC mode, look into
870 // dependent base classes where the primary class template is known.
871 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872 if (ParsedType TypeInBase =
873 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
874 return TypeInBase;
875 }
876
877 // Perform lookup for Objective-C instance variables (including automatically
878 // synthesized instance variables), if we're in an Objective-C method.
879 // FIXME: This lookup really, really needs to be folded in to the normal
880 // unqualified lookup mechanism.
881 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
882 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
883 if (E.get() || E.isInvalid())
884 return E;
885 }
886
887 bool SecondTry = false;
888 bool IsFilteredTemplateName = false;
889
890Corrected:
891 switch (Result.getResultKind()) {
892 case LookupResult::NotFound:
893 // If an unqualified-id is followed by a '(', then we have a function
894 // call.
895 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896 // In C++, this is an ADL-only call.
897 // FIXME: Reference?
898 if (getLangOpts().CPlusPlus)
899 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
900
901 // C90 6.3.2.2:
902 // If the expression that precedes the parenthesized argument list in a
903 // function call consists solely of an identifier, and if no
904 // declaration is visible for this identifier, the identifier is
905 // implicitly declared exactly as if, in the innermost block containing
906 // the function call, the declaration
907 //
908 // extern int identifier ();
909 //
910 // appeared.
911 //
912 // We also allow this in C99 as an extension.
913 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
914 Result.addDecl(D);
915 Result.resolveKind();
916 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
917 }
918 }
919
920 // In C, we first see whether there is a tag type by the same name, in
921 // which case it's likely that the user just forgot to write "enum",
922 // "struct", or "union".
923 if (!getLangOpts().CPlusPlus && !SecondTry &&
924 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
925 break;
926 }
927
928 // Perform typo correction to determine if there is another name that is
929 // close to this name.
930 if (!SecondTry && CCC) {
931 SecondTry = true;
932 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
933 Result.getLookupKind(), S,
934 &SS, std::move(CCC),
935 CTK_ErrorRecovery)) {
936 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
937 unsigned QualifiedDiag = diag::err_no_member_suggest;
938
939 NamedDecl *FirstDecl = Corrected.getFoundDecl();
940 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
941 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
942 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
943 UnqualifiedDiag = diag::err_no_template_suggest;
944 QualifiedDiag = diag::err_no_member_template_suggest;
945 } else if (UnderlyingFirstDecl &&
946 (isa<TypeDecl>(UnderlyingFirstDecl) ||
947 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
948 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
949 UnqualifiedDiag = diag::err_unknown_typename_suggest;
950 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
951 }
952
953 if (SS.isEmpty()) {
954 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
955 } else {// FIXME: is this even reachable? Test it.
956 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
957 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
958 Name->getName().equals(CorrectedStr);
959 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
960 << Name << computeDeclContext(SS, false)
961 << DroppedSpecifier << SS.getRange());
962 }
963
964 // Update the name, so that the caller has the new name.
965 Name = Corrected.getCorrectionAsIdentifierInfo();
966
967 // Typo correction corrected to a keyword.
968 if (Corrected.isKeyword())
969 return Name;
970
971 // Also update the LookupResult...
972 // FIXME: This should probably go away at some point
973 Result.clear();
974 Result.setLookupName(Corrected.getCorrection());
975 if (FirstDecl)
976 Result.addDecl(FirstDecl);
977
978 // If we found an Objective-C instance variable, let
979 // LookupInObjCMethod build the appropriate expression to
980 // reference the ivar.
981 // FIXME: This is a gross hack.
982 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
983 Result.clear();
984 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
985 return E;
986 }
987
988 goto Corrected;
989 }
990 }
991
992 // We failed to correct; just fall through and let the parser deal with it.
993 Result.suppressDiagnostics();
994 return NameClassification::Unknown();
995
996 case LookupResult::NotFoundInCurrentInstantiation: {
997 // We performed name lookup into the current instantiation, and there were
998 // dependent bases, so we treat this result the same way as any other
999 // dependent nested-name-specifier.
1000
1001 // C++ [temp.res]p2:
1002 // A name used in a template declaration or definition and that is
1003 // dependent on a template-parameter is assumed not to name a type
1004 // unless the applicable name lookup finds a type name or the name is
1005 // qualified by the keyword typename.
1006 //
1007 // FIXME: If the next token is '<', we might want to ask the parser to
1008 // perform some heroics to see if we actually have a
1009 // template-argument-list, which would indicate a missing 'template'
1010 // keyword here.
1011 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1012 NameInfo, IsAddressOfOperand,
1013 /*TemplateArgs=*/nullptr);
1014 }
1015
1016 case LookupResult::Found:
1017 case LookupResult::FoundOverloaded:
1018 case LookupResult::FoundUnresolvedValue:
1019 break;
1020
1021 case LookupResult::Ambiguous:
1022 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1023 hasAnyAcceptableTemplateNames(Result)) {
1024 // C++ [temp.local]p3:
1025 // A lookup that finds an injected-class-name (10.2) can result in an
1026 // ambiguity in certain cases (for example, if it is found in more than
1027 // one base class). If all of the injected-class-names that are found
1028 // refer to specializations of the same class template, and if the name
1029 // is followed by a template-argument-list, the reference refers to the
1030 // class template itself and not a specialization thereof, and is not
1031 // ambiguous.
1032 //
1033 // This filtering can make an ambiguous result into an unambiguous one,
1034 // so try again after filtering out template names.
1035 FilterAcceptableTemplateNames(Result);
1036 if (!Result.isAmbiguous()) {
1037 IsFilteredTemplateName = true;
1038 break;
1039 }
1040 }
1041
1042 // Diagnose the ambiguity and return an error.
1043 return NameClassification::Error();
1044 }
1045
1046 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1048 // C++ [temp.names]p3:
1049 // After name lookup (3.4) finds that a name is a template-name or that
1050 // an operator-function-id or a literal- operator-id refers to a set of
1051 // overloaded functions any member of which is a function template if
1052 // this is followed by a <, the < is always taken as the delimiter of a
1053 // template-argument-list and never as the less-than operator.
1054 if (!IsFilteredTemplateName)
1055 FilterAcceptableTemplateNames(Result);
1056
1057 if (!Result.empty()) {
1058 bool IsFunctionTemplate;
1059 bool IsVarTemplate;
1060 TemplateName Template;
1061 if (Result.end() - Result.begin() > 1) {
1062 IsFunctionTemplate = true;
1063 Template = Context.getOverloadedTemplateName(Result.begin(),
1064 Result.end());
1065 } else {
1066 TemplateDecl *TD
1067 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1068 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1069 IsVarTemplate = isa<VarTemplateDecl>(TD);
1070
1071 if (SS.isSet() && !SS.isInvalid())
1072 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1073 /*TemplateKeyword=*/false,
1074 TD);
1075 else
1076 Template = TemplateName(TD);
1077 }
1078
1079 if (IsFunctionTemplate) {
1080 // Function templates always go through overload resolution, at which
1081 // point we'll perform the various checks (e.g., accessibility) we need
1082 // to based on which function we selected.
1083 Result.suppressDiagnostics();
1084
1085 return NameClassification::FunctionTemplate(Template);
1086 }
1087
1088 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1089 : NameClassification::TypeTemplate(Template);
1090 }
1091 }
1092
1093 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1094 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1095 DiagnoseUseOfDecl(Type, NameLoc);
1096 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1097 QualType T = Context.getTypeDeclType(Type);
1098 if (SS.isNotEmpty())
1099 return buildNestedType(*this, SS, T, NameLoc);
1100 return ParsedType::make(T);
1101 }
1102
1103 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1104 if (!Class) {
1105 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1106 if (ObjCCompatibleAliasDecl *Alias =
1107 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1108 Class = Alias->getClassInterface();
1109 }
1110
1111 if (Class) {
1112 DiagnoseUseOfDecl(Class, NameLoc);
1113
1114 if (NextToken.is(tok::period)) {
1115 // Interface. <something> is parsed as a property reference expression.
1116 // Just return "unknown" as a fall-through for now.
1117 Result.suppressDiagnostics();
1118 return NameClassification::Unknown();
1119 }
1120
1121 QualType T = Context.getObjCInterfaceType(Class);
1122 return ParsedType::make(T);
1123 }
1124
1125 // We can have a type template here if we're classifying a template argument.
1126 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1127 !isa<VarTemplateDecl>(FirstDecl))
1128 return NameClassification::TypeTemplate(
1129 TemplateName(cast<TemplateDecl>(FirstDecl)));
1130
1131 // Check for a tag type hidden by a non-type decl in a few cases where it
1132 // seems likely a type is wanted instead of the non-type that was found.
1133 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1134 if ((NextToken.is(tok::identifier) ||
1135 (NextIsOp &&
1136 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1137 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1138 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1139 DiagnoseUseOfDecl(Type, NameLoc);
1140 QualType T = Context.getTypeDeclType(Type);
1141 if (SS.isNotEmpty())
1142 return buildNestedType(*this, SS, T, NameLoc);
1143 return ParsedType::make(T);
1144 }
1145
1146 if (FirstDecl->isCXXClassMember())
1147 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1148 nullptr, S);
1149
1150 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1151 return BuildDeclarationNameExpr(SS, Result, ADL);
1152}
1153
1154Sema::TemplateNameKindForDiagnostics
1155Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1156 auto *TD = Name.getAsTemplateDecl();
1157 if (!TD)
1158 return TemplateNameKindForDiagnostics::DependentTemplate;
1159 if (isa<ClassTemplateDecl>(TD))
1160 return TemplateNameKindForDiagnostics::ClassTemplate;
1161 if (isa<FunctionTemplateDecl>(TD))
1162 return TemplateNameKindForDiagnostics::FunctionTemplate;
1163 if (isa<VarTemplateDecl>(TD))
1164 return TemplateNameKindForDiagnostics::VarTemplate;
1165 if (isa<TypeAliasTemplateDecl>(TD))
1166 return TemplateNameKindForDiagnostics::AliasTemplate;
1167 if (isa<TemplateTemplateParmDecl>(TD))
1168 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1169 return TemplateNameKindForDiagnostics::DependentTemplate;
1170}
1171
1172// Determines the context to return to after temporarily entering a
1173// context. This depends in an unnecessarily complicated way on the
1174// exact ordering of callbacks from the parser.
1175DeclContext *Sema::getContainingDC(DeclContext *DC) {
1176
1177 // Functions defined inline within classes aren't parsed until we've
1178 // finished parsing the top-level class, so the top-level class is
1179 // the context we'll need to return to.
1180 // A Lambda call operator whose parent is a class must not be treated
1181 // as an inline member function. A Lambda can be used legally
1182 // either as an in-class member initializer or a default argument. These
1183 // are parsed once the class has been marked complete and so the containing
1184 // context would be the nested class (when the lambda is defined in one);
1185 // If the class is not complete, then the lambda is being used in an
1186 // ill-formed fashion (such as to specify the width of a bit-field, or
1187 // in an array-bound) - in which case we still want to return the
1188 // lexically containing DC (which could be a nested class).
1189 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1190 DC = DC->getLexicalParent();
1191
1192 // A function not defined within a class will always return to its
1193 // lexical context.
1194 if (!isa<CXXRecordDecl>(DC))
1195 return DC;
1196
1197 // A C++ inline method/friend is parsed *after* the topmost class
1198 // it was declared in is fully parsed ("complete"); the topmost
1199 // class is the context we need to return to.
1200 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1201 DC = RD;
1202
1203 // Return the declaration context of the topmost class the inline method is
1204 // declared in.
1205 return DC;
1206 }
1207
1208 return DC->getLexicalParent();
1209}
1210
1211void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1212 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1213, __PRETTY_FUNCTION__))
1213 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1213, __PRETTY_FUNCTION__))
;
1214 CurContext = DC;
1215 S->setEntity(DC);
1216}
1217
1218void Sema::PopDeclContext() {
1219 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1219, __PRETTY_FUNCTION__))
;
1220
1221 CurContext = getContainingDC(CurContext);
1222 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1222, __PRETTY_FUNCTION__))
;
1223}
1224
1225Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1226 Decl *D) {
1227 // Unlike PushDeclContext, the context to which we return is not necessarily
1228 // the containing DC of TD, because the new context will be some pre-existing
1229 // TagDecl definition instead of a fresh one.
1230 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1231 CurContext = cast<TagDecl>(D)->getDefinition();
1232 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1232, __PRETTY_FUNCTION__))
;
1233 // Start lookups from the parent of the current context; we don't want to look
1234 // into the pre-existing complete definition.
1235 S->setEntity(CurContext->getLookupParent());
1236 return Result;
1237}
1238
1239void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1240 CurContext = static_cast<decltype(CurContext)>(Context);
1241}
1242
1243/// EnterDeclaratorContext - Used when we must lookup names in the context
1244/// of a declarator's nested name specifier.
1245///
1246void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1247 // C++0x [basic.lookup.unqual]p13:
1248 // A name used in the definition of a static data member of class
1249 // X (after the qualified-id of the static member) is looked up as
1250 // if the name was used in a member function of X.
1251 // C++0x [basic.lookup.unqual]p14:
1252 // If a variable member of a namespace is defined outside of the
1253 // scope of its namespace then any name used in the definition of
1254 // the variable member (after the declarator-id) is looked up as
1255 // if the definition of the variable member occurred in its
1256 // namespace.
1257 // Both of these imply that we should push a scope whose context
1258 // is the semantic context of the declaration. We can't use
1259 // PushDeclContext here because that context is not necessarily
1260 // lexically contained in the current context. Fortunately,
1261 // the containing scope should have the appropriate information.
1262
1263 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1263, __PRETTY_FUNCTION__))
;
1264
1265#ifndef NDEBUG
1266 Scope *Ancestor = S->getParent();
1267 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1268 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1268, __PRETTY_FUNCTION__))
;
1269#endif
1270
1271 CurContext = DC;
1272 S->setEntity(DC);
1273}
1274
1275void Sema::ExitDeclaratorContext(Scope *S) {
1276 assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!"
) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1276, __PRETTY_FUNCTION__))
;
1277
1278 // Switch back to the lexical context. The safety of this is
1279 // enforced by an assert in EnterDeclaratorContext.
1280 Scope *Ancestor = S->getParent();
1281 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1282 CurContext = Ancestor->getEntity();
1283
1284 // We don't need to do anything with the scope, which is going to
1285 // disappear.
1286}
1287
1288void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1289 // We assume that the caller has already called
1290 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1291 FunctionDecl *FD = D->getAsFunction();
1292 if (!FD)
1293 return;
1294
1295 // Same implementation as PushDeclContext, but enters the context
1296 // from the lexical parent, rather than the top-level class.
1297 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1298, __PRETTY_FUNCTION__))
1298 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1298, __PRETTY_FUNCTION__))
;
1299 CurContext = FD;
1300 S->setEntity(CurContext);
1301
1302 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1303 ParmVarDecl *Param = FD->getParamDecl(P);
1304 // If the parameter has an identifier, then add it to the scope
1305 if (Param->getIdentifier()) {
1306 S->AddDecl(Param);
1307 IdResolver.AddDecl(Param);
1308 }
1309 }
1310}
1311
1312void Sema::ActOnExitFunctionContext() {
1313 // Same implementation as PopDeclContext, but returns to the lexical parent,
1314 // rather than the top-level class.
1315 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1315, __PRETTY_FUNCTION__))
;
1316 CurContext = CurContext->getLexicalParent();
1317 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1317, __PRETTY_FUNCTION__))
;
1318}
1319
1320/// \brief Determine whether we allow overloading of the function
1321/// PrevDecl with another declaration.
1322///
1323/// This routine determines whether overloading is possible, not
1324/// whether some new function is actually an overload. It will return
1325/// true in C++ (where we can always provide overloads) or, as an
1326/// extension, in C when the previous function is already an
1327/// overloaded function declaration or has the "overloadable"
1328/// attribute.
1329static bool AllowOverloadingOfFunction(LookupResult &Previous,
1330 ASTContext &Context) {
1331 if (Context.getLangOpts().CPlusPlus)
1332 return true;
1333
1334 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1335 return true;
1336
1337 return (Previous.getResultKind() == LookupResult::Found
1338 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1339}
1340
1341/// Add this decl to the scope shadowed decl chains.
1342void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1343 // Move up the scope chain until we find the nearest enclosing
1344 // non-transparent context. The declaration will be introduced into this
1345 // scope.
1346 while (S->getEntity() && S->getEntity()->isTransparentContext())
1347 S = S->getParent();
1348
1349 // Add scoped declarations into their context, so that they can be
1350 // found later. Declarations without a context won't be inserted
1351 // into any context.
1352 if (AddToContext)
1353 CurContext->addDecl(D);
1354
1355 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1356 // are function-local declarations.
1357 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1358 !D->getDeclContext()->getRedeclContext()->Equals(
1359 D->getLexicalDeclContext()->getRedeclContext()) &&
1360 !D->getLexicalDeclContext()->isFunctionOrMethod())
1361 return;
1362
1363 // Template instantiations should also not be pushed into scope.
1364 if (isa<FunctionDecl>(D) &&
1365 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1366 return;
1367
1368 // If this replaces anything in the current scope,
1369 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1370 IEnd = IdResolver.end();
1371 for (; I != IEnd; ++I) {
1372 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1373 S->RemoveDecl(*I);
1374 IdResolver.RemoveDecl(*I);
1375
1376 // Should only need to replace one decl.
1377 break;
1378 }
1379 }
1380
1381 S->AddDecl(D);
1382
1383 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1384 // Implicitly-generated labels may end up getting generated in an order that
1385 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1386 // the label at the appropriate place in the identifier chain.
1387 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1388 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1389 if (IDC == CurContext) {
1390 if (!S->isDeclScope(*I))
1391 continue;
1392 } else if (IDC->Encloses(CurContext))
1393 break;
1394 }
1395
1396 IdResolver.InsertDeclAfter(I, D);
1397 } else {
1398 IdResolver.AddDecl(D);
1399 }
1400}
1401
1402void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1403 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1404 TUScope->AddDecl(D);
1405}
1406
1407bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1408 bool AllowInlineNamespace) {
1409 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1410}
1411
1412Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1413 DeclContext *TargetDC = DC->getPrimaryContext();
1414 do {
1415 if (DeclContext *ScopeDC = S->getEntity())
1416 if (ScopeDC->getPrimaryContext() == TargetDC)
1417 return S;
1418 } while ((S = S->getParent()));
1419
1420 return nullptr;
1421}
1422
1423static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1424 DeclContext*,
1425 ASTContext&);
1426
1427/// Filters out lookup results that don't fall within the given scope
1428/// as determined by isDeclInScope.
1429void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1430 bool ConsiderLinkage,
1431 bool AllowInlineNamespace) {
1432 LookupResult::Filter F = R.makeFilter();
1433 while (F.hasNext()) {
1434 NamedDecl *D = F.next();
1435
1436 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1437 continue;
1438
1439 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1440 continue;
1441
1442 F.erase();
1443 }
1444
1445 F.done();
1446}
1447
1448static bool isUsingDecl(NamedDecl *D) {
1449 return isa<UsingShadowDecl>(D) ||
1450 isa<UnresolvedUsingTypenameDecl>(D) ||
1451 isa<UnresolvedUsingValueDecl>(D);
1452}
1453
1454/// Removes using shadow declarations from the lookup results.
1455static void RemoveUsingDecls(LookupResult &R) {
1456 LookupResult::Filter F = R.makeFilter();
1457 while (F.hasNext())
1458 if (isUsingDecl(F.next()))
1459 F.erase();
1460
1461 F.done();
1462}
1463
1464/// \brief Check for this common pattern:
1465/// @code
1466/// class S {
1467/// S(const S&); // DO NOT IMPLEMENT
1468/// void operator=(const S&); // DO NOT IMPLEMENT
1469/// };
1470/// @endcode
1471static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1472 // FIXME: Should check for private access too but access is set after we get
1473 // the decl here.
1474 if (D->doesThisDeclarationHaveABody())
1475 return false;
1476
1477 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1478 return CD->isCopyConstructor();
1479 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1480 return Method->isCopyAssignmentOperator();
1481 return false;
1482}
1483
1484// We need this to handle
1485//
1486// typedef struct {
1487// void *foo() { return 0; }
1488// } A;
1489//
1490// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1491// for example. If 'A', foo will have external linkage. If we have '*A',
1492// foo will have no linkage. Since we can't know until we get to the end
1493// of the typedef, this function finds out if D might have non-external linkage.
1494// Callers should verify at the end of the TU if it D has external linkage or
1495// not.
1496bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1497 const DeclContext *DC = D->getDeclContext();
1498 while (!DC->isTranslationUnit()) {
1499 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1500 if (!RD->hasNameForLinkage())
1501 return true;
1502 }
1503 DC = DC->getParent();
1504 }
1505
1506 return !D->isExternallyVisible();
1507}
1508
1509// FIXME: This needs to be refactored; some other isInMainFile users want
1510// these semantics.
1511static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1512 if (S.TUKind != TU_Complete)
1513 return false;
1514 return S.SourceMgr.isInMainFile(Loc);
1515}
1516
1517bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1518 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1518, __PRETTY_FUNCTION__))
;
1519
1520 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1521 return false;
1522
1523 // Ignore all entities declared within templates, and out-of-line definitions
1524 // of members of class templates.
1525 if (D->getDeclContext()->isDependentContext() ||
1526 D->getLexicalDeclContext()->isDependentContext())
1527 return false;
1528
1529 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1530 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1531 return false;
1532 // A non-out-of-line declaration of a member specialization was implicitly
1533 // instantiated; it's the out-of-line declaration that we're interested in.
1534 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1535 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1536 return false;
1537
1538 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1539 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1540 return false;
1541 } else {
1542 // 'static inline' functions are defined in headers; don't warn.
1543 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1544 return false;
1545 }
1546
1547 if (FD->doesThisDeclarationHaveABody() &&
1548 Context.DeclMustBeEmitted(FD))
1549 return false;
1550 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1551 // Constants and utility variables are defined in headers with internal
1552 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1553 // like "inline".)
1554 if (!isMainFileLoc(*this, VD->getLocation()))
1555 return false;
1556
1557 if (Context.DeclMustBeEmitted(VD))
1558 return false;
1559
1560 if (VD->isStaticDataMember() &&
1561 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1562 return false;
1563 if (VD->isStaticDataMember() &&
1564 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1565 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1566 return false;
1567
1568 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1569 return false;
1570 } else {
1571 return false;
1572 }
1573
1574 // Only warn for unused decls internal to the translation unit.
1575 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1576 // for inline functions defined in the main source file, for instance.
1577 return mightHaveNonExternalLinkage(D);
1578}
1579
1580void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1581 if (!D)
1582 return;
1583
1584 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1585 const FunctionDecl *First = FD->getFirstDecl();
1586 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1587 return; // First should already be in the vector.
1588 }
1589
1590 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1591 const VarDecl *First = VD->getFirstDecl();
1592 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1593 return; // First should already be in the vector.
1594 }
1595
1596 if (ShouldWarnIfUnusedFileScopedDecl(D))
1597 UnusedFileScopedDecls.push_back(D);
1598}
1599
1600static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1601 if (D->isInvalidDecl())
1602 return false;
1603
1604 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1605 D->hasAttr<ObjCPreciseLifetimeAttr>())
1606 return false;
1607
1608 if (isa<LabelDecl>(D))
1609 return true;
1610
1611 // Except for labels, we only care about unused decls that are local to
1612 // functions.
1613 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1614 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1615 // For dependent types, the diagnostic is deferred.
1616 WithinFunction =
1617 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1618 if (!WithinFunction)
1619 return false;
1620
1621 if (isa<TypedefNameDecl>(D))
1622 return true;
1623
1624 // White-list anything that isn't a local variable.
1625 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1626 return false;
1627
1628 // Types of valid local variables should be complete, so this should succeed.
1629 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1630
1631 // White-list anything with an __attribute__((unused)) type.
1632 const auto *Ty = VD->getType().getTypePtr();
1633
1634 // Only look at the outermost level of typedef.
1635 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1636 if (TT->getDecl()->hasAttr<UnusedAttr>())
1637 return false;
1638 }
1639
1640 // If we failed to complete the type for some reason, or if the type is
1641 // dependent, don't diagnose the variable.
1642 if (Ty->isIncompleteType() || Ty->isDependentType())
1643 return false;
1644
1645 // Look at the element type to ensure that the warning behaviour is
1646 // consistent for both scalars and arrays.
1647 Ty = Ty->getBaseElementTypeUnsafe();
1648
1649 if (const TagType *TT = Ty->getAs<TagType>()) {
1650 const TagDecl *Tag = TT->getDecl();
1651 if (Tag->hasAttr<UnusedAttr>())
1652 return false;
1653
1654 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1655 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1656 return false;
1657
1658 if (const Expr *Init = VD->getInit()) {
1659 if (const ExprWithCleanups *Cleanups =
1660 dyn_cast<ExprWithCleanups>(Init))
1661 Init = Cleanups->getSubExpr();
1662 const CXXConstructExpr *Construct =
1663 dyn_cast<CXXConstructExpr>(Init);
1664 if (Construct && !Construct->isElidable()) {
1665 CXXConstructorDecl *CD = Construct->getConstructor();
1666 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1667 return false;
1668 }
1669 }
1670 }
1671 }
1672
1673 // TODO: __attribute__((unused)) templates?
1674 }
1675
1676 return true;
1677}
1678
1679static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1680 FixItHint &Hint) {
1681 if (isa<LabelDecl>(D)) {
1682 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1683 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1684 if (AfterColon.isInvalid())
1685 return;
1686 Hint = FixItHint::CreateRemoval(CharSourceRange::
1687 getCharRange(D->getLocStart(), AfterColon));
1688 }
1689}
1690
1691void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1692 if (D->getTypeForDecl()->isDependentType())
1693 return;
1694
1695 for (auto *TmpD : D->decls()) {
1696 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1697 DiagnoseUnusedDecl(T);
1698 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1699 DiagnoseUnusedNestedTypedefs(R);
1700 }
1701}
1702
1703/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1704/// unless they are marked attr(unused).
1705void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1706 if (!ShouldDiagnoseUnusedDecl(D))
1707 return;
1708
1709 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1710 // typedefs can be referenced later on, so the diagnostics are emitted
1711 // at end-of-translation-unit.
1712 UnusedLocalTypedefNameCandidates.insert(TD);
1713 return;
1714 }
1715
1716 FixItHint Hint;
1717 GenerateFixForUnusedDecl(D, Context, Hint);
1718
1719 unsigned DiagID;
1720 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1721 DiagID = diag::warn_unused_exception_param;
1722 else if (isa<LabelDecl>(D))
1723 DiagID = diag::warn_unused_label;
1724 else
1725 DiagID = diag::warn_unused_variable;
1726
1727 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1728}
1729
1730static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1731 // Verify that we have no forward references left. If so, there was a goto
1732 // or address of a label taken, but no definition of it. Label fwd
1733 // definitions are indicated with a null substmt which is also not a resolved
1734 // MS inline assembly label name.
1735 bool Diagnose = false;
1736 if (L->isMSAsmLabel())
1737 Diagnose = !L->isResolvedMSAsmLabel();
1738 else
1739 Diagnose = L->getStmt() == nullptr;
1740 if (Diagnose)
1741 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1742}
1743
1744void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1745 S->mergeNRVOIntoParent();
1746
1747 if (S->decl_empty()) return;
1748 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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1749, __PRETTY_FUNCTION__))
1749 "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!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1749, __PRETTY_FUNCTION__))
;
1750
1751 for (auto *TmpD : S->decls()) {
1752 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??\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1752, __PRETTY_FUNCTION__))
;
1753
1754 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?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1754, __PRETTY_FUNCTION__))
;
1755 NamedDecl *D = cast<NamedDecl>(TmpD);
1756
1757 if (!D->getDeclName()) continue;
1758
1759 // Diagnose unused variables in this scope.
1760 if (!S->hasUnrecoverableErrorOccurred()) {
1761 DiagnoseUnusedDecl(D);
1762 if (const auto *RD = dyn_cast<RecordDecl>(D))
1763 DiagnoseUnusedNestedTypedefs(RD);
1764 }
1765
1766 // If this was a forward reference to a label, verify it was defined.
1767 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1768 CheckPoppedLabel(LD, *this);
1769
1770 // Remove this name from our lexical scope, and warn on it if we haven't
1771 // already.
1772 IdResolver.RemoveDecl(D);
1773 auto ShadowI = ShadowingDecls.find(D);
1774 if (ShadowI != ShadowingDecls.end()) {
1775 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1776 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1777 << D << FD << FD->getParent();
1778 Diag(FD->getLocation(), diag::note_previous_declaration);
1779 }
1780 ShadowingDecls.erase(ShadowI);
1781 }
1782 }
1783}
1784
1785/// \brief Look for an Objective-C class in the translation unit.
1786///
1787/// \param Id The name of the Objective-C class we're looking for. If
1788/// typo-correction fixes this name, the Id will be updated
1789/// to the fixed name.
1790///
1791/// \param IdLoc The location of the name in the translation unit.
1792///
1793/// \param DoTypoCorrection If true, this routine will attempt typo correction
1794/// if there is no class with the given name.
1795///
1796/// \returns The declaration of the named Objective-C class, or NULL if the
1797/// class could not be found.
1798ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1799 SourceLocation IdLoc,
1800 bool DoTypoCorrection) {
1801 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1802 // creation from this context.
1803 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1804
1805 if (!IDecl && DoTypoCorrection) {
1806 // Perform typo correction at the given location, but only if we
1807 // find an Objective-C class name.
1808 if (TypoCorrection C = CorrectTypo(
1809 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1810 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1811 CTK_ErrorRecovery)) {
1812 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1813 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1814 Id = IDecl->getIdentifier();
1815 }
1816 }
1817 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1818 // This routine must always return a class definition, if any.
1819 if (Def && Def->getDefinition())
1820 Def = Def->getDefinition();
1821 return Def;
1822}
1823
1824/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1825/// from S, where a non-field would be declared. This routine copes
1826/// with the difference between C and C++ scoping rules in structs and
1827/// unions. For example, the following code is well-formed in C but
1828/// ill-formed in C++:
1829/// @code
1830/// struct S6 {
1831/// enum { BAR } e;
1832/// };
1833///
1834/// void test_S6() {
1835/// struct S6 a;
1836/// a.e = BAR;
1837/// }
1838/// @endcode
1839/// For the declaration of BAR, this routine will return a different
1840/// scope. The scope S will be the scope of the unnamed enumeration
1841/// within S6. In C++, this routine will return the scope associated
1842/// with S6, because the enumeration's scope is a transparent
1843/// context but structures can contain non-field names. In C, this
1844/// routine will return the translation unit scope, since the
1845/// enumeration's scope is a transparent context and structures cannot
1846/// contain non-field names.
1847Scope *Sema::getNonFieldDeclScope(Scope *S) {
1848 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1849 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1850 (S->isClassScope() && !getLangOpts().CPlusPlus))
1851 S = S->getParent();
1852 return S;
1853}
1854
1855/// \brief Looks up the declaration of "struct objc_super" and
1856/// saves it for later use in building builtin declaration of
1857/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1858/// pre-existing declaration exists no action takes place.
1859static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1860 IdentifierInfo *II) {
1861 if (!II->isStr("objc_msgSendSuper"))
1862 return;
1863 ASTContext &Context = ThisSema.Context;
1864
1865 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1866 SourceLocation(), Sema::LookupTagName);
1867 ThisSema.LookupName(Result, S);
1868 if (Result.getResultKind() == LookupResult::Found)
1869 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1870 Context.setObjCSuperType(Context.getTagDeclType(TD));
1871}
1872
1873static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1874 switch (Error) {
1875 case ASTContext::GE_None:
1876 return "";
1877 case ASTContext::GE_Missing_stdio:
1878 return "stdio.h";
1879 case ASTContext::GE_Missing_setjmp:
1880 return "setjmp.h";
1881 case ASTContext::GE_Missing_ucontext:
1882 return "ucontext.h";
1883 }
1884 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 1884)
;
1885}
1886
1887/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1888/// file scope. lazily create a decl for it. ForRedeclaration is true
1889/// if we're creating this built-in in anticipation of redeclaring the
1890/// built-in.
1891NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1892 Scope *S, bool ForRedeclaration,
1893 SourceLocation Loc) {
1894 LookupPredefedObjCSuperType(*this, S, II);
1895
1896 ASTContext::GetBuiltinTypeError Error;
1897 QualType R = Context.GetBuiltinType(ID, Error);
1898 if (Error) {
1899 if (ForRedeclaration)
1900 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1901 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1902 return nullptr;
1903 }
1904
1905 if (!ForRedeclaration &&
1906 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1907 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1908 Diag(Loc, diag::ext_implicit_lib_function_decl)
1909 << Context.BuiltinInfo.getName(ID) << R;
1910 if (Context.BuiltinInfo.getHeaderName(ID) &&
1911 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1912 Diag(Loc, diag::note_include_header_or_declare)
1913 << Context.BuiltinInfo.getHeaderName(ID)
1914 << Context.BuiltinInfo.getName(ID);
1915 }
1916
1917 if (R.isNull())
1918 return nullptr;
1919
1920 DeclContext *Parent = Context.getTranslationUnitDecl();
1921 if (getLangOpts().CPlusPlus) {
1922 LinkageSpecDecl *CLinkageDecl =
1923 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1924 LinkageSpecDecl::lang_c, false);
1925 CLinkageDecl->setImplicit();
1926 Parent->addDecl(CLinkageDecl);
1927 Parent = CLinkageDecl;
1928 }
1929
1930 FunctionDecl *New = FunctionDecl::Create(Context,
1931 Parent,
1932 Loc, Loc, II, R, /*TInfo=*/nullptr,
1933 SC_Extern,
1934 false,
1935 R->isFunctionProtoType());
1936 New->setImplicit();
1937
1938 // Create Decl objects for each parameter, adding them to the
1939 // FunctionDecl.
1940 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1941 SmallVector<ParmVarDecl*, 16> Params;
1942 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1943 ParmVarDecl *parm =
1944 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1945 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1946 SC_None, nullptr);
1947 parm->setScopeInfo(0, i);
1948 Params.push_back(parm);
1949 }
1950 New->setParams(Params);
1951 }
1952
1953 AddKnownFunctionAttributes(New);
1954 RegisterLocallyScopedExternCDecl(New, S);
1955
1956 // TUScope is the translation-unit scope to insert this function into.
1957 // FIXME: This is hideous. We need to teach PushOnScopeChains to
1958 // relate Scopes to DeclContexts, and probably eliminate CurContext
1959 // entirely, but we're not there yet.
1960 DeclContext *SavedContext = CurContext;
1961 CurContext = Parent;
1962 PushOnScopeChains(New, TUScope);
1963 CurContext = SavedContext;
1964 return New;
1965}
1966
1967/// Typedef declarations don't have linkage, but they still denote the same
1968/// entity if their types are the same.
1969/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1970/// isSameEntity.
1971static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1972 TypedefNameDecl *Decl,
1973 LookupResult &Previous) {
1974 // This is only interesting when modules are enabled.
1975 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1976 return;
1977
1978 // Empty sets are uninteresting.
1979 if (Previous.empty())
1980 return;
1981
1982 LookupResult::Filter Filter = Previous.makeFilter();
1983 while (Filter.hasNext()) {
1984 NamedDecl *Old = Filter.next();
1985
1986 // Non-hidden declarations are never ignored.
1987 if (S.isVisible(Old))
1988 continue;
1989
1990 // Declarations of the same entity are not ignored, even if they have
1991 // different linkages.
1992 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1993 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1994 Decl->getUnderlyingType()))
1995 continue;
1996
1997 // If both declarations give a tag declaration a typedef name for linkage
1998 // purposes, then they declare the same entity.
1999 if (S.getLangOpts().CPlusPlus &&
2000 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2001 Decl->getAnonDeclWithTypedefName())
2002 continue;
2003 }
2004
2005 Filter.erase();
2006 }
2007
2008 Filter.done();
2009}
2010
2011bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2012 QualType OldType;
2013 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2014 OldType = OldTypedef->getUnderlyingType();
2015 else
2016 OldType = Context.getTypeDeclType(Old);
2017 QualType NewType = New->getUnderlyingType();
2018
2019 if (NewType->isVariablyModifiedType()) {
2020 // Must not redefine a typedef with a variably-modified type.
2021 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2022 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2023 << Kind << NewType;
2024 if (Old->getLocation().isValid())
2025 notePreviousDefinition(Old, New->getLocation());
2026 New->setInvalidDecl();
2027 return true;
2028 }
2029
2030 if (OldType != NewType &&
2031 !OldType->isDependentType() &&
2032 !NewType->isDependentType() &&
2033 !Context.hasSameType(OldType, NewType)) {
2034 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2035 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2036 << Kind << NewType << OldType;
2037 if (Old->getLocation().isValid())
2038 notePreviousDefinition(Old, New->getLocation());
2039 New->setInvalidDecl();
2040 return true;
2041 }
2042 return false;
2043}
2044
2045/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2046/// same name and scope as a previous declaration 'Old'. Figure out
2047/// how to resolve this situation, merging decls or emitting
2048/// diagnostics as appropriate. If there was an error, set New to be invalid.
2049///
2050void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2051 LookupResult &OldDecls) {
2052 // If the new decl is known invalid already, don't bother doing any
2053 // merging checks.
2054 if (New->isInvalidDecl()) return;
2055
2056 // Allow multiple definitions for ObjC built-in typedefs.
2057 // FIXME: Verify the underlying types are equivalent!
2058 if (getLangOpts().ObjC1) {
2059 const IdentifierInfo *TypeID = New->getIdentifier();
2060 switch (TypeID->getLength()) {
2061 default: break;
2062 case 2:
2063 {
2064 if (!TypeID->isStr("id"))
2065 break;
2066 QualType T = New->getUnderlyingType();
2067 if (!T->isPointerType())
2068 break;
2069 if (!T->isVoidPointerType()) {
2070 QualType PT = T->getAs<PointerType>()->getPointeeType();
2071 if (!PT->isStructureType())
2072 break;
2073 }
2074 Context.setObjCIdRedefinitionType(T);
2075 // Install the built-in type for 'id', ignoring the current definition.
2076 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2077 return;
2078 }
2079 case 5:
2080 if (!TypeID->isStr("Class"))
2081 break;
2082 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2083 // Install the built-in type for 'Class', ignoring the current definition.
2084 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2085 return;
2086 case 3:
2087 if (!TypeID->isStr("SEL"))
2088 break;
2089 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2090 // Install the built-in type for 'SEL', ignoring the current definition.
2091 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2092 return;
2093 }
2094 // Fall through - the typedef name was not a builtin type.
2095 }
2096
2097 // Verify the old decl was also a type.
2098 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2099 if (!Old) {
2100 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2101 << New->getDeclName();
2102
2103 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2104 if (OldD->getLocation().isValid())
2105 notePreviousDefinition(OldD, New->getLocation());
2106
2107 return New->setInvalidDecl();
2108 }
2109
2110 // If the old declaration is invalid, just give up here.
2111 if (Old->isInvalidDecl())
2112 return New->setInvalidDecl();
2113
2114 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2115 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2116 auto *NewTag = New->getAnonDeclWithTypedefName();
2117 NamedDecl *Hidden = nullptr;
2118 if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2119 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2120 !hasVisibleDefinition(OldTag, &Hidden)) {
2121 // There is a definition of this tag, but it is not visible. Use it
2122 // instead of our tag.
2123 New->setTypeForDecl(OldTD->getTypeForDecl());
2124 if (OldTD->isModed())
2125 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2126 OldTD->getUnderlyingType());
2127 else
2128 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2129
2130 // Make the old tag definition visible.
2131 makeMergedDefinitionVisible(Hidden);
2132
2133 // If this was an unscoped enumeration, yank all of its enumerators
2134 // out of the scope.
2135 if (isa<EnumDecl>(NewTag)) {
2136 Scope *EnumScope = getNonFieldDeclScope(S);
2137 for (auto *D : NewTag->decls()) {
2138 auto *ED = cast<EnumConstantDecl>(D);
2139 assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0
) : __assert_fail ("EnumScope->isDeclScope(ED)", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 2139, __PRETTY_FUNCTION__))
;
2140 EnumScope->RemoveDecl(ED);
2141 IdResolver.RemoveDecl(ED);
2142 ED->getLexicalDeclContext()->removeDecl(ED);
2143 }
2144 }
2145 }
2146 }
2147
2148 // If the typedef types are not identical, reject them in all languages and
2149 // with any extensions enabled.
2150 if (isIncompatibleTypedef(Old, New))
2151 return;
2152
2153 // The types match. Link up the redeclaration chain and merge attributes if
2154 // the old declaration was a typedef.
2155 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2156 New->setPreviousDecl(Typedef);
2157 mergeDeclAttributes(New, Old);
2158 }
2159
2160 if (getLangOpts().MicrosoftExt)
2161 return;
2162
2163 if (getLangOpts().CPlusPlus) {
2164 // C++ [dcl.typedef]p2:
2165 // In a given non-class scope, a typedef specifier can be used to
2166 // redefine the name of any type declared in that scope to refer
2167 // to the type to which it already refers.
2168 if (!isa<CXXRecordDecl>(CurContext))
2169 return;
2170
2171 // C++0x [dcl.typedef]p4:
2172 // In a given class scope, a typedef specifier can be used to redefine
2173 // any class-name declared in that scope that is not also a typedef-name
2174 // to refer to the type to which it already refers.
2175 //
2176 // This wording came in via DR424, which was a correction to the
2177 // wording in DR56, which accidentally banned code like:
2178 //
2179 // struct S {
2180 // typedef struct A { } A;
2181 // };
2182 //
2183 // in the C++03 standard. We implement the C++0x semantics, which
2184 // allow the above but disallow
2185 //
2186 // struct S {
2187 // typedef int I;
2188 // typedef int I;
2189 // };
2190 //
2191 // since that was the intent of DR56.
2192 if (!isa<TypedefNameDecl>(Old))
2193 return;
2194
2195 Diag(New->getLocation(), diag::err_redefinition)
2196 << New->getDeclName();
2197 notePreviousDefinition(Old, New->getLocation());
2198 return New->setInvalidDecl();
2199 }
2200
2201 // Modules always permit redefinition of typedefs, as does C11.
2202 if (getLangOpts().Modules || getLangOpts().C11)
2203 return;
2204
2205 // If we have a redefinition of a typedef in C, emit a warning. This warning
2206 // is normally mapped to an error, but can be controlled with
2207 // -Wtypedef-redefinition. If either the original or the redefinition is
2208 // in a system header, don't emit this for compatibility with GCC.
2209 if (getDiagnostics().getSuppressSystemWarnings() &&
2210 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2211 (Old->isImplicit() ||
2212 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2213 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2214 return;
2215
2216 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2217 << New->getDeclName();
2218 notePreviousDefinition(Old, New->getLocation());
2219}
2220
2221/// DeclhasAttr - returns true if decl Declaration already has the target
2222/// attribute.
2223static bool DeclHasAttr(const Decl *D, const Attr *A) {
2224 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2225 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2226 for (const auto *i : D->attrs())
2227 if (i->getKind() == A->getKind()) {
2228 if (Ann) {
2229 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2230 return true;
2231 continue;
2232 }
2233 // FIXME: Don't hardcode this check
2234 if (OA && isa<OwnershipAttr>(i))
2235 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2236 return true;
2237 }
2238
2239 return false;
2240}
2241
2242static bool isAttributeTargetADefinition(Decl *D) {
2243 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2244 return VD->isThisDeclarationADefinition();
2245 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2246 return TD->isCompleteDefinition() || TD->isBeingDefined();
2247 return true;
2248}
2249
2250/// Merge alignment attributes from \p Old to \p New, taking into account the
2251/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2252///
2253/// \return \c true if any attributes were added to \p New.
2254static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2255 // Look for alignas attributes on Old, and pick out whichever attribute
2256 // specifies the strictest alignment requirement.
2257 AlignedAttr *OldAlignasAttr = nullptr;
2258 AlignedAttr *OldStrictestAlignAttr = nullptr;
2259 unsigned OldAlign = 0;
2260 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2261 // FIXME: We have no way of representing inherited dependent alignments
2262 // in a case like:
2263 // template<int A, int B> struct alignas(A) X;
2264 // template<int A, int B> struct alignas(B) X {};
2265 // For now, we just ignore any alignas attributes which are not on the
2266 // definition in such a case.
2267 if (I->isAlignmentDependent())
2268 return false;
2269
2270 if (I->isAlignas())
2271 OldAlignasAttr = I;
2272
2273 unsigned Align = I->getAlignment(S.Context);
2274 if (Align > OldAlign) {
2275 OldAlign = Align;
2276 OldStrictestAlignAttr = I;
2277 }
2278 }
2279
2280 // Look for alignas attributes on New.
2281 AlignedAttr *NewAlignasAttr = nullptr;
2282 unsigned NewAlign = 0;
2283 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2284 if (I->isAlignmentDependent())
2285 return false;
2286
2287 if (I->isAlignas())
2288 NewAlignasAttr = I;
2289
2290 unsigned Align = I->getAlignment(S.Context);
2291 if (Align > NewAlign)
2292 NewAlign = Align;
2293 }
2294
2295 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2296 // Both declarations have 'alignas' attributes. We require them to match.
2297 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2298 // fall short. (If two declarations both have alignas, they must both match
2299 // every definition, and so must match each other if there is a definition.)
2300
2301 // If either declaration only contains 'alignas(0)' specifiers, then it
2302 // specifies the natural alignment for the type.
2303 if (OldAlign == 0 || NewAlign == 0) {
2304 QualType Ty;
2305 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2306 Ty = VD->getType();
2307 else
2308 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2309
2310 if (OldAlign == 0)
2311 OldAlign = S.Context.getTypeAlign(Ty);
2312 if (NewAlign == 0)
2313 NewAlign = S.Context.getTypeAlign(Ty);
2314 }
2315
2316 if (OldAlign != NewAlign) {
2317 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2318 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2319 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2320 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2321 }
2322 }
2323
2324 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2325 // C++11 [dcl.align]p6:
2326 // if any declaration of an entity has an alignment-specifier,
2327 // every defining declaration of that entity shall specify an
2328 // equivalent alignment.
2329 // C11 6.7.5/7:
2330 // If the definition of an object does not have an alignment
2331 // specifier, any other declaration of that object shall also
2332 // have no alignment specifier.
2333 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2334 << OldAlignasAttr;
2335 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2336 << OldAlignasAttr;
2337 }
2338
2339 bool AnyAdded = false;
2340
2341 // Ensure we have an attribute representing the strictest alignment.
2342 if (OldAlign > NewAlign) {
2343 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2344 Clone->setInherited(true);
2345 New->addAttr(Clone);
2346 AnyAdded = true;
2347 }
2348
2349 // Ensure we have an alignas attribute if the old declaration had one.
2350 if (OldAlignasAttr && !NewAlignasAttr &&
2351 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2352 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2353 Clone->setInherited(true);
2354 New->addAttr(Clone);
2355 AnyAdded = true;
2356 }
2357
2358 return AnyAdded;
2359}
2360
2361static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2362 const InheritableAttr *Attr,
2363 Sema::AvailabilityMergeKind AMK) {
2364 // This function copies an attribute Attr from a previous declaration to the
2365 // new declaration D if the new declaration doesn't itself have that attribute
2366 // yet or if that attribute allows duplicates.
2367 // If you're adding a new attribute that requires logic different from
2368 // "use explicit attribute on decl if present, else use attribute from
2369 // previous decl", for example if the attribute needs to be consistent
2370 // between redeclarations, you need to call a custom merge function here.
2371 InheritableAttr *NewAttr = nullptr;
2372 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2373 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2374 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2375 AA->isImplicit(), AA->getIntroduced(),
2376 AA->getDeprecated(),
2377 AA->getObsoleted(), AA->getUnavailable(),
2378 AA->getMessage(), AA->getStrict(),
2379 AA->getReplacement(), AMK,
2380 AttrSpellingListIndex);
2381 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2382 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2383 AttrSpellingListIndex);
2384 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2385 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2386 AttrSpellingListIndex);
2387 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2388 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2389 AttrSpellingListIndex);
2390 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2391 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2392 AttrSpellingListIndex);
2393 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2394 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2395 FA->getFormatIdx(), FA->getFirstArg(),
2396 AttrSpellingListIndex);
2397 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2398 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2399 AttrSpellingListIndex);
2400 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2401 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2402 AttrSpellingListIndex,
2403 IA->getSemanticSpelling());
2404 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2405 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2406 &S.Context.Idents.get(AA->getSpelling()),
2407 AttrSpellingListIndex);
2408 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2409 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2410 isa<CUDAGlobalAttr>(Attr))) {
2411 // CUDA target attributes are part of function signature for
2412 // overloading purposes and must not be merged.
2413 return false;
2414 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2415 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2416 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2417 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2418 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2419 NewAttr = S.mergeInternalLinkageAttr(
2420 D, InternalLinkageA->getRange(),
2421 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2422 AttrSpellingListIndex);
2423 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2424 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2425 &S.Context.Idents.get(CommonA->getSpelling()),
2426 AttrSpellingListIndex);
2427 else if (isa<AlignedAttr>(Attr))
2428 // AlignedAttrs are handled separately, because we need to handle all
2429 // such attributes on a declaration at the same time.
2430 NewAttr = nullptr;
2431 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2432 (AMK == Sema::AMK_Override ||
2433 AMK == Sema::AMK_ProtocolImplementation))
2434 NewAttr = nullptr;
2435 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2436 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2437 UA->getGuid());
2438 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2439 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2440
2441 if (NewAttr) {
2442 NewAttr->setInherited(true);
2443 D->addAttr(NewAttr);
2444 if (isa<MSInheritanceAttr>(NewAttr))
2445 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2446 return true;
2447 }
2448
2449 return false;
2450}
2451
2452static const NamedDecl *getDefinition(const Decl *D) {
2453 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2454 return TD->getDefinition();
2455 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2456 const VarDecl *Def = VD->getDefinition();
2457 if (Def)
2458 return Def;
2459 return VD->getActingDefinition();
2460 }
2461 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2462 return FD->getDefinition();
2463 return nullptr;
2464}
2465
2466static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2467 for (const auto *Attribute : D->attrs())
2468 if (Attribute->getKind() == Kind)
2469 return true;
2470 return false;
2471}
2472
2473/// checkNewAttributesAfterDef - If we already have a definition, check that
2474/// there are no new attributes in this declaration.
2475static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2476 if (!New->hasAttrs())
2477 return;
2478
2479 const NamedDecl *Def = getDefinition(Old);
2480 if (!Def || Def == New)
2481 return;
2482
2483 AttrVec &NewAttributes = New->getAttrs();
2484 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2485 const Attr *NewAttribute = NewAttributes[I];
2486
2487 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2488 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2489 Sema::SkipBodyInfo SkipBody;
2490 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2491
2492 // If we're skipping this definition, drop the "alias" attribute.
2493 if (SkipBody.ShouldSkip) {
2494 NewAttributes.erase(NewAttributes.begin() + I);
2495 --E;
2496 continue;
2497 }
2498 } else {
2499 VarDecl *VD = cast<VarDecl>(New);
2500 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2501 VarDecl::TentativeDefinition
2502 ? diag::err_alias_after_tentative
2503 : diag::err_redefinition;
2504 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2505 if (Diag == diag::err_redefinition)
2506 S.notePreviousDefinition(Def, VD->getLocation());
2507 else
2508 S.Diag(Def->getLocation(), diag::note_previous_definition);
2509 VD->setInvalidDecl();
2510 }
2511 ++I;
2512 continue;
2513 }
2514
2515 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2516 // Tentative definitions are only interesting for the alias check above.
2517 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2518 ++I;
2519 continue;
2520 }
2521 }
2522
2523 if (hasAttribute(Def, NewAttribute->getKind())) {
2524 ++I;
2525 continue; // regular attr merging will take care of validating this.
2526 }
2527
2528 if (isa<C11NoReturnAttr>(NewAttribute)) {
2529 // C's _Noreturn is allowed to be added to a function after it is defined.
2530 ++I;
2531 continue;
2532 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2533 if (AA->isAlignas()) {
2534 // C++11 [dcl.align]p6:
2535 // if any declaration of an entity has an alignment-specifier,
2536 // every defining declaration of that entity shall specify an
2537 // equivalent alignment.
2538 // C11 6.7.5/7:
2539 // If the definition of an object does not have an alignment
2540 // specifier, any other declaration of that object shall also
2541 // have no alignment specifier.
2542 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2543 << AA;
2544 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2545 << AA;
2546 NewAttributes.erase(NewAttributes.begin() + I);
2547 --E;
2548 continue;
2549 }
2550 }
2551
2552 S.Diag(NewAttribute->getLocation(),
2553 diag::warn_attribute_precede_definition);
2554 S.Diag(Def->getLocation(), diag::note_previous_definition);
2555 NewAttributes.erase(NewAttributes.begin() + I);
2556 --E;
2557 }
2558}
2559
2560/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2561void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2562 AvailabilityMergeKind AMK) {
2563 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2564 UsedAttr *NewAttr = OldAttr->clone(Context);
2565 NewAttr->setInherited(true);
2566 New->addAttr(NewAttr);
2567 }
2568
2569 if (!Old->hasAttrs() && !New->hasAttrs())
2570 return;
2571
2572 // Attributes declared post-definition are currently ignored.
2573 checkNewAttributesAfterDef(*this, New, Old);
2574
2575 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2576 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2577 if (OldA->getLabel() != NewA->getLabel()) {
2578 // This redeclaration changes __asm__ label.
2579 Diag(New->getLocation(), diag::err_different_asm_label);
2580 Diag(OldA->getLocation(), diag::note_previous_declaration);
2581 }
2582 } else if (Old->isUsed()) {
2583 // This redeclaration adds an __asm__ label to a declaration that has
2584 // already been ODR-used.
2585 Diag(New->getLocation(), diag::err_late_asm_label_name)
2586 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2587 }
2588 }
2589
2590 // Re-declaration cannot add abi_tag's.
2591 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2592 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2593 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2594 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2595 NewTag) == OldAbiTagAttr->tags_end()) {
2596 Diag(NewAbiTagAttr->getLocation(),
2597 diag::err_new_abi_tag_on_redeclaration)
2598 << NewTag;
2599 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2600 }
2601 }
2602 } else {
2603 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2604 Diag(Old->getLocation(), diag::note_previous_declaration);
2605 }
2606 }
2607
2608 if (!Old->hasAttrs())
2609 return;
2610
2611 bool foundAny = New->hasAttrs();
2612
2613 // Ensure that any moving of objects within the allocated map is done before
2614 // we process them.
2615 if (!foundAny) New->setAttrs(AttrVec());
2616
2617 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2618 // Ignore deprecated/unavailable/availability attributes if requested.
2619 AvailabilityMergeKind LocalAMK = AMK_None;
2620 if (isa<DeprecatedAttr>(I) ||
2621 isa<UnavailableAttr>(I) ||
2622 isa<AvailabilityAttr>(I)) {
2623 switch (AMK) {
2624 case AMK_None:
2625 continue;
2626
2627 case AMK_Redeclaration:
2628 case AMK_Override:
2629 case AMK_ProtocolImplementation:
2630 LocalAMK = AMK;
2631 break;
2632 }
2633 }
2634
2635 // Already handled.
2636 if (isa<UsedAttr>(I))
2637 continue;
2638
2639 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2640 foundAny = true;
2641 }
2642
2643 if (mergeAlignedAttrs(*this, New, Old))
2644 foundAny = true;
2645
2646 if (!foundAny) New->dropAttrs();
2647}
2648
2649/// mergeParamDeclAttributes - Copy attributes from the old parameter
2650/// to the new one.
2651static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2652 const ParmVarDecl *oldDecl,
2653 Sema &S) {
2654 // C++11 [dcl.attr.depend]p2:
2655 // The first declaration of a function shall specify the
2656 // carries_dependency attribute for its declarator-id if any declaration
2657 // of the function specifies the carries_dependency attribute.
2658 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2659 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2660 S.Diag(CDA->getLocation(),
2661 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2662 // Find the first declaration of the parameter.
2663 // FIXME: Should we build redeclaration chains for function parameters?
2664 const FunctionDecl *FirstFD =
2665 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2666 const ParmVarDecl *FirstVD =
2667 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2668 S.Diag(FirstVD->getLocation(),
2669 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2670 }
2671
2672 if (!oldDecl->hasAttrs())
2673 return;
2674
2675 bool foundAny = newDecl->hasAttrs();
2676
2677 // Ensure that any moving of objects within the allocated map is
2678 // done before we process them.
2679 if (!foundAny) newDecl->setAttrs(AttrVec());
2680
2681 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2682 if (!DeclHasAttr(newDecl, I)) {
2683 InheritableAttr *newAttr =
2684 cast<InheritableParamAttr>(I->clone(S.Context));
2685 newAttr->setInherited(true);
2686 newDecl->addAttr(newAttr);
2687 foundAny = true;
2688 }
2689 }
2690
2691 if (!foundAny) newDecl->dropAttrs();
2692}
2693
2694static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2695 const ParmVarDecl *OldParam,
2696 Sema &S) {
2697 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2698 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2699 if (*Oldnullability != *Newnullability) {
2700 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2701 << DiagNullabilityKind(
2702 *Newnullability,
2703 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2704 != 0))
2705 << DiagNullabilityKind(
2706 *Oldnullability,
2707 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2708 != 0));
2709 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2710 }
2711 } else {
2712 QualType NewT = NewParam->getType();
2713 NewT = S.Context.getAttributedType(
2714 AttributedType::getNullabilityAttrKind(*Oldnullability),
2715 NewT, NewT);
2716 NewParam->setType(NewT);
2717 }
2718 }
2719}
2720
2721namespace {
2722
2723/// Used in MergeFunctionDecl to keep track of function parameters in
2724/// C.
2725struct GNUCompatibleParamWarning {
2726 ParmVarDecl *OldParm;
2727 ParmVarDecl *NewParm;
2728 QualType PromotedType;
2729};
2730
2731} // end anonymous namespace
2732
2733/// getSpecialMember - get the special member enum for a method.
2734Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2735 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2736 if (Ctor->isDefaultConstructor())
2737 return Sema::CXXDefaultConstructor;
2738
2739 if (Ctor->isCopyConstructor())
2740 return Sema::CXXCopyConstructor;
2741
2742 if (Ctor->isMoveConstructor())
2743 return Sema::CXXMoveConstructor;
2744 } else if (isa<CXXDestructorDecl>(MD)) {
2745 return Sema::CXXDestructor;
2746 } else if (MD->isCopyAssignmentOperator()) {
2747 return Sema::CXXCopyAssignment;
2748 } else if (MD->isMoveAssignmentOperator()) {
2749 return Sema::CXXMoveAssignment;
2750 }
2751
2752 return Sema::CXXInvalid;
2753}
2754
2755// Determine whether the previous declaration was a definition, implicit
2756// declaration, or a declaration.
2757template <typename T>
2758static std::pair<diag::kind, SourceLocation>
2759getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2760 diag::kind PrevDiag;
2761 SourceLocation OldLocation = Old->getLocation();
2762 if (Old->isThisDeclarationADefinition())
2763 PrevDiag = diag::note_previous_definition;
2764 else if (Old->isImplicit()) {
2765 PrevDiag = diag::note_previous_implicit_declaration;
2766 if (OldLocation.isInvalid())
2767 OldLocation = New->getLocation();
2768 } else
2769 PrevDiag = diag::note_previous_declaration;
2770 return std::make_pair(PrevDiag, OldLocation);
2771}
2772
2773/// canRedefineFunction - checks if a function can be redefined. Currently,
2774/// only extern inline functions can be redefined, and even then only in
2775/// GNU89 mode.
2776static bool canRedefineFunction(const FunctionDecl *FD,
2777 const LangOptions& LangOpts) {
2778 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2779 !LangOpts.CPlusPlus &&
2780 FD->isInlineSpecified() &&
2781 FD->getStorageClass() == SC_Extern);
2782}
2783
2784const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2785 const AttributedType *AT = T->getAs<AttributedType>();
2786 while (AT && !AT->isCallingConv())
2787 AT = AT->getModifiedType()->getAs<AttributedType>();
2788 return AT;
2789}
2790
2791template <typename T>
2792static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2793 const DeclContext *DC = Old->getDeclContext();
2794 if (DC->isRecord())
2795 return false;
2796
2797 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2798 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2799 return true;
2800 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2801 return true;
2802 return false;
2803}
2804
2805template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2806static bool isExternC(VarTemplateDecl *) { return false; }
2807
2808/// \brief Check whether a redeclaration of an entity introduced by a
2809/// using-declaration is valid, given that we know it's not an overload
2810/// (nor a hidden tag declaration).
2811template<typename ExpectedDecl>
2812static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2813 ExpectedDecl *New) {
2814 // C++11 [basic.scope.declarative]p4:
2815 // Given a set of declarations in a single declarative region, each of
2816 // which specifies the same unqualified name,
2817 // -- they shall all refer to the same entity, or all refer to functions
2818 // and function templates; or
2819 // -- exactly one declaration shall declare a class name or enumeration
2820 // name that is not a typedef name and the other declarations shall all
2821 // refer to the same variable or enumerator, or all refer to functions
2822 // and function templates; in this case the class name or enumeration
2823 // name is hidden (3.3.10).
2824
2825 // C++11 [namespace.udecl]p14:
2826 // If a function declaration in namespace scope or block scope has the
2827 // same name and the same parameter-type-list as a function introduced
2828 // by a using-declaration, and the declarations do not declare the same
2829 // function, the program is ill-formed.
2830
2831 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2832 if (Old &&
2833 !Old->getDeclContext()->getRedeclContext()->Equals(
2834 New->getDeclContext()->getRedeclContext()) &&
2835 !(isExternC(Old) && isExternC(New)))
2836 Old = nullptr;
2837
2838 if (!Old) {
2839 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2840 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2841 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2842 return true;
2843 }
2844 return false;
2845}
2846
2847static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2848 const FunctionDecl *B) {
2849 assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast
<void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 2849, __PRETTY_FUNCTION__))
;
2850
2851 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2852 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2853 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2854 if (AttrA == AttrB)
2855 return true;
2856 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2857 };
2858
2859 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2860}
2861
2862/// MergeFunctionDecl - We just parsed a function 'New' from
2863/// declarator D which has the same name and scope as a previous
2864/// declaration 'Old'. Figure out how to resolve this situation,
2865/// merging decls or emitting diagnostics as appropriate.
2866///
2867/// In C++, New and Old must be declarations that are not
2868/// overloaded. Use IsOverload to determine whether New and Old are
2869/// overloaded, and to select the Old declaration that New should be
2870/// merged with.
2871///
2872/// Returns true if there was an error, false otherwise.
2873bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2874 Scope *S, bool MergeTypeWithOld) {
2875 // Verify the old decl was also a function.
2876 FunctionDecl *Old = OldD->getAsFunction();
2877 if (!Old) {
2878 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2879 if (New->getFriendObjectKind()) {
2880 Diag(New->getLocation(), diag::err_using_decl_friend);
2881 Diag(Shadow->getTargetDecl()->getLocation(),
2882 diag::note_using_decl_target);
2883 Diag(Shadow->getUsingDecl()->getLocation(),
2884 diag::note_using_decl) << 0;
2885 return true;
2886 }
2887
2888 // Check whether the two declarations might declare the same function.
2889 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2890 return true;
2891 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2892 } else {
2893 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2894 << New->getDeclName();
2895 notePreviousDefinition(OldD, New->getLocation());
2896 return true;
2897 }
2898 }
2899
2900 // If the old declaration is invalid, just give up here.
2901 if (Old->isInvalidDecl())
2902 return true;
2903
2904 diag::kind PrevDiag;
2905 SourceLocation OldLocation;
2906 std::tie(PrevDiag, OldLocation) =
2907 getNoteDiagForInvalidRedeclaration(Old, New);
2908
2909 // Don't complain about this if we're in GNU89 mode and the old function
2910 // is an extern inline function.
2911 // Don't complain about specializations. They are not supposed to have
2912 // storage classes.
2913 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2914 New->getStorageClass() == SC_Static &&
2915 Old->hasExternalFormalLinkage() &&
2916 !New->getTemplateSpecializationInfo() &&
2917 !canRedefineFunction(Old, getLangOpts())) {
2918 if (getLangOpts().MicrosoftExt) {
2919 Diag(New->getLocation(), diag::ext_static_non_static) << New;
2920 Diag(OldLocation, PrevDiag);
2921 } else {
2922 Diag(New->getLocation(), diag::err_static_non_static) << New;
2923 Diag(OldLocation, PrevDiag);
2924 return true;
2925 }
2926 }
2927
2928 if (New->hasAttr<InternalLinkageAttr>() &&
2929 !Old->hasAttr<InternalLinkageAttr>()) {
2930 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2931 << New->getDeclName();
2932 notePreviousDefinition(Old, New->getLocation());
2933 New->dropAttr<InternalLinkageAttr>();
2934 }
2935
2936 // If a function is first declared with a calling convention, but is later
2937 // declared or defined without one, all following decls assume the calling
2938 // convention of the first.
2939 //
2940 // It's OK if a function is first declared without a calling convention,
2941 // but is later declared or defined with the default calling convention.
2942 //
2943 // To test if either decl has an explicit calling convention, we look for
2944 // AttributedType sugar nodes on the type as written. If they are missing or
2945 // were canonicalized away, we assume the calling convention was implicit.
2946 //
2947 // Note also that we DO NOT return at this point, because we still have
2948 // other tests to run.
2949 QualType OldQType = Context.getCanonicalType(Old->getType());
2950 QualType NewQType = Context.getCanonicalType(New->getType());
2951 const FunctionType *OldType = cast<FunctionType>(OldQType);
2952 const FunctionType *NewType = cast<FunctionType>(NewQType);
2953 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2954 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2955 bool RequiresAdjustment = false;
2956
2957 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2958 FunctionDecl *First = Old->getFirstDecl();
2959 const FunctionType *FT =
2960 First->getType().getCanonicalType()->castAs<FunctionType>();
2961 FunctionType::ExtInfo FI = FT->getExtInfo();
2962 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2963 if (!NewCCExplicit) {
2964 // Inherit the CC from the previous declaration if it was specified
2965 // there but not here.
2966 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2967 RequiresAdjustment = true;
2968 } else {
2969 // Calling conventions aren't compatible, so complain.
2970 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2971 Diag(New->getLocation(), diag::err_cconv_change)
2972 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2973 << !FirstCCExplicit
2974 << (!FirstCCExplicit ? "" :
2975 FunctionType::getNameForCallConv(FI.getCC()));
2976
2977 // Put the note on the first decl, since it is the one that matters.
2978 Diag(First->getLocation(), diag::note_previous_declaration);
2979 return true;
2980 }
2981 }
2982
2983 // FIXME: diagnose the other way around?
2984 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2985 NewTypeInfo = NewTypeInfo.withNoReturn(true);
2986 RequiresAdjustment = true;
2987 }
2988
2989 // Merge regparm attribute.
2990 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2991 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2992 if (NewTypeInfo.getHasRegParm()) {
2993 Diag(New->getLocation(), diag::err_regparm_mismatch)
2994 << NewType->getRegParmType()
2995 << OldType->getRegParmType();
2996 Diag(OldLocation, diag::note_previous_declaration);
2997 return true;
2998 }
2999
3000 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3001 RequiresAdjustment = true;
3002 }
3003
3004 // Merge ns_returns_retained attribute.
3005 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3006 if (NewTypeInfo.getProducesResult()) {
3007 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3008 << "'ns_returns_retained'";
3009 Diag(OldLocation, diag::note_previous_declaration);
3010 return true;
3011 }
3012
3013 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3014 RequiresAdjustment = true;
3015 }
3016
3017 if (OldTypeInfo.getNoCallerSavedRegs() !=
3018 NewTypeInfo.getNoCallerSavedRegs()) {
3019 if (NewTypeInfo.getNoCallerSavedRegs()) {
3020 AnyX86NoCallerSavedRegistersAttr *Attr =
3021 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3022 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3023 Diag(OldLocation, diag::note_previous_declaration);
3024 return true;
3025 }
3026
3027 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3028 RequiresAdjustment = true;
3029 }
3030
3031 if (RequiresAdjustment) {
3032 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3033 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3034 New->setType(QualType(AdjustedType, 0));
3035 NewQType = Context.getCanonicalType(New->getType());
3036 NewType = cast<FunctionType>(NewQType);
3037 }
3038
3039 // If this redeclaration makes the function inline, we may need to add it to
3040 // UndefinedButUsed.
3041 if (!Old->isInlined() && New->isInlined() &&
3042 !New->hasAttr<GNUInlineAttr>() &&
3043 !getLangOpts().GNUInline &&
3044 Old->isUsed(false) &&
3045 !Old->isDefined() && !New->isThisDeclarationADefinition())
3046 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3047 SourceLocation()));
3048
3049 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3050 // about it.
3051 if (New->hasAttr<GNUInlineAttr>() &&
3052 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3053 UndefinedButUsed.erase(Old->getCanonicalDecl());
3054 }
3055
3056 // If pass_object_size params don't match up perfectly, this isn't a valid
3057 // redeclaration.
3058 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3059 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3060 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3061 << New->getDeclName();
3062 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3063 return true;
3064 }
3065
3066 if (getLangOpts().CPlusPlus) {
3067 // C++1z [over.load]p2
3068 // Certain function declarations cannot be overloaded:
3069 // -- Function declarations that differ only in the return type,
3070 // the exception specification, or both cannot be overloaded.
3071
3072 // Check the exception specifications match. This may recompute the type of
3073 // both Old and New if it resolved exception specifications, so grab the
3074 // types again after this. Because this updates the type, we do this before
3075 // any of the other checks below, which may update the "de facto" NewQType
3076 // but do not necessarily update the type of New.
3077 if (CheckEquivalentExceptionSpec(Old, New))
3078 return true;
3079 OldQType = Context.getCanonicalType(Old->getType());
3080 NewQType = Context.getCanonicalType(New->getType());
3081
3082 // Go back to the type source info to compare the declared return types,
3083 // per C++1y [dcl.type.auto]p13:
3084 // Redeclarations or specializations of a function or function template
3085 // with a declared return type that uses a placeholder type shall also
3086 // use that placeholder, not a deduced type.
3087 QualType OldDeclaredReturnType =
3088 (Old->getTypeSourceInfo()
3089 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3090 : OldType)->getReturnType();
3091 QualType NewDeclaredReturnType =
3092 (New->getTypeSourceInfo()
3093 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3094 : NewType)->getReturnType();
3095 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3096 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3097 New->isLocalExternDecl())) {
3098 QualType ResQT;
3099 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3100 OldDeclaredReturnType->isObjCObjectPointerType())
3101 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3102 if (ResQT.isNull()) {
3103 if (New->isCXXClassMember() && New->isOutOfLine())
3104 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3105 << New << New->getReturnTypeSourceRange();
3106 else
3107 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3108 << New->getReturnTypeSourceRange();
3109 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3110 << Old->getReturnTypeSourceRange();
3111 return true;
3112 }
3113 else
3114 NewQType = ResQT;
3115 }
3116
3117 QualType OldReturnType = OldType->getReturnType();
3118 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3119 if (OldReturnType != NewReturnType) {
3120 // If this function has a deduced return type and has already been
3121 // defined, copy the deduced value from the old declaration.
3122 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3123 if (OldAT && OldAT->isDeduced()) {
3124 New->setType(
3125 SubstAutoType(New->getType(),
3126 OldAT->isDependentType() ? Context.DependentTy
3127 : OldAT->getDeducedType()));
3128 NewQType = Context.getCanonicalType(
3129 SubstAutoType(NewQType,
3130 OldAT->isDependentType() ? Context.DependentTy
3131 : OldAT->getDeducedType()));
3132 }
3133 }
3134
3135 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3136 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3137 if (OldMethod && NewMethod) {
3138 // Preserve triviality.
3139 NewMethod->setTrivial(OldMethod->isTrivial());
3140
3141 // MSVC allows explicit template specialization at class scope:
3142 // 2 CXXMethodDecls referring to the same function will be injected.
3143 // We don't want a redeclaration error.
3144 bool IsClassScopeExplicitSpecialization =
3145 OldMethod->isFunctionTemplateSpecialization() &&
3146 NewMethod->isFunctionTemplateSpecialization();
3147 bool isFriend = NewMethod->getFriendObjectKind();
3148
3149 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3150 !IsClassScopeExplicitSpecialization) {
3151 // -- Member function declarations with the same name and the
3152 // same parameter types cannot be overloaded if any of them
3153 // is a static member function declaration.
3154 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3155 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3156 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3157 return true;
3158 }
3159
3160 // C++ [class.mem]p1:
3161 // [...] A member shall not be declared twice in the
3162 // member-specification, except that a nested class or member
3163 // class template can be declared and then later defined.
3164 if (!inTemplateInstantiation()) {
3165 unsigned NewDiag;
3166 if (isa<CXXConstructorDecl>(OldMethod))
3167 NewDiag = diag::err_constructor_redeclared;
3168 else if (isa<CXXDestructorDecl>(NewMethod))
3169 NewDiag = diag::err_destructor_redeclared;
3170 else if (isa<CXXConversionDecl>(NewMethod))
3171 NewDiag = diag::err_conv_function_redeclared;
3172 else
3173 NewDiag = diag::err_member_redeclared;
3174
3175 Diag(New->getLocation(), NewDiag);
3176 } else {
3177 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3178 << New << New->getType();
3179 }
3180 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3181 return true;
3182
3183 // Complain if this is an explicit declaration of a special
3184 // member that was initially declared implicitly.
3185 //
3186 // As an exception, it's okay to befriend such methods in order
3187 // to permit the implicit constructor/destructor/operator calls.
3188 } else if (OldMethod->isImplicit()) {
3189 if (isFriend) {
3190 NewMethod->setImplicit();
3191 } else {
3192 Diag(NewMethod->getLocation(),
3193 diag::err_definition_of_implicitly_declared_member)
3194 << New << getSpecialMember(OldMethod);
3195 return true;
3196 }
3197 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3198 Diag(NewMethod->getLocation(),
3199 diag::err_definition_of_explicitly_defaulted_member)
3200 << getSpecialMember(OldMethod);
3201 return true;
3202 }
3203 }
3204
3205 // C++11 [dcl.attr.noreturn]p1:
3206 // The first declaration of a function shall specify the noreturn
3207 // attribute if any declaration of that function specifies the noreturn
3208 // attribute.
3209 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3210 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3211 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3212 Diag(Old->getFirstDecl()->getLocation(),
3213 diag::note_noreturn_missing_first_decl);
3214 }
3215
3216 // C++11 [dcl.attr.depend]p2:
3217 // The first declaration of a function shall specify the
3218 // carries_dependency attribute for its declarator-id if any declaration
3219 // of the function specifies the carries_dependency attribute.
3220 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3221 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3222 Diag(CDA->getLocation(),
3223 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3224 Diag(Old->getFirstDecl()->getLocation(),
3225 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3226 }
3227
3228 // (C++98 8.3.5p3):
3229 // All declarations for a function shall agree exactly in both the
3230 // return type and the parameter-type-list.
3231 // We also want to respect all the extended bits except noreturn.
3232
3233 // noreturn should now match unless the old type info didn't have it.
3234 QualType OldQTypeForComparison = OldQType;
3235 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3236 auto *OldType = OldQType->castAs<FunctionProtoType>();
3237 const FunctionType *OldTypeForComparison
3238 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3239 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3240 assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void>
(0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 3240, __PRETTY_FUNCTION__))
;
3241 }
3242
3243 if (haveIncompatibleLanguageLinkages(Old, New)) {
3244 // As a special case, retain the language linkage from previous
3245 // declarations of a friend function as an extension.
3246 //
3247 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3248 // and is useful because there's otherwise no way to specify language
3249 // linkage within class scope.
3250 //
3251 // Check cautiously as the friend object kind isn't yet complete.
3252 if (New->getFriendObjectKind() != Decl::FOK_None) {
3253 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3254 Diag(OldLocation, PrevDiag);
3255 } else {
3256 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3257 Diag(OldLocation, PrevDiag);
3258 return true;
3259 }
3260 }
3261
3262 if (OldQTypeForComparison == NewQType)
3263 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3264
3265 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3266 New->isLocalExternDecl()) {
3267 // It's OK if we couldn't merge types for a local function declaraton
3268 // if either the old or new type is dependent. We'll merge the types
3269 // when we instantiate the function.
3270 return false;
3271 }
3272
3273 // Fall through for conflicting redeclarations and redefinitions.
3274 }
3275
3276 // C: Function types need to be compatible, not identical. This handles
3277 // duplicate function decls like "void f(int); void f(enum X);" properly.
3278 if (!getLangOpts().CPlusPlus &&
3279 Context.typesAreCompatible(OldQType, NewQType)) {
3280 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3281 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3282 const FunctionProtoType *OldProto = nullptr;
3283 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3284 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3285 // The old declaration provided a function prototype, but the
3286 // new declaration does not. Merge in the prototype.
3287 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 3287, __PRETTY_FUNCTION__))
;
3288 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3289 NewQType =
3290 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3291 OldProto->getExtProtoInfo());
3292 New->setType(NewQType);
3293 New->setHasInheritedPrototype();
3294
3295 // Synthesize parameters with the same types.
3296 SmallVector<ParmVarDecl*, 16> Params;
3297 for (const auto &ParamType : OldProto->param_types()) {
3298 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3299 SourceLocation(), nullptr,
3300 ParamType, /*TInfo=*/nullptr,
3301 SC_None, nullptr);
3302 Param->setScopeInfo(0, Params.size());
3303 Param->setImplicit();
3304 Params.push_back(Param);
3305 }
3306
3307 New->setParams(Params);
3308 }
3309
3310 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3311 }
3312
3313 // GNU C permits a K&R definition to follow a prototype declaration
3314 // if the declared types of the parameters in the K&R definition
3315 // match the types in the prototype declaration, even when the
3316 // promoted types of the parameters from the K&R definition differ
3317 // from the types in the prototype. GCC then keeps the types from
3318 // the prototype.
3319 //
3320 // If a variadic prototype is followed by a non-variadic K&R definition,
3321 // the K&R definition becomes variadic. This is sort of an edge case, but
3322 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3323 // C99 6.9.1p8.
3324 if (!getLangOpts().CPlusPlus &&
3325 Old->hasPrototype() && !New->hasPrototype() &&
3326 New->getType()->getAs<FunctionProtoType>() &&
3327 Old->getNumParams() == New->getNumParams()) {
3328 SmallVector<QualType, 16> ArgTypes;
3329 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3330 const FunctionProtoType *OldProto
3331 = Old->getType()->getAs<FunctionProtoType>();
3332 const FunctionProtoType *NewProto
3333 = New->getType()->getAs<FunctionProtoType>();
3334
3335 // Determine whether this is the GNU C extension.
3336 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3337 NewProto->getReturnType());
3338 bool LooseCompatible = !MergedReturn.isNull();
3339 for (unsigned Idx = 0, End = Old->getNumParams();
3340 LooseCompatible && Idx != End; ++Idx) {
3341 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3342 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3343 if (Context.typesAreCompatible(OldParm->getType(),
3344 NewProto->getParamType(Idx))) {
3345 ArgTypes.push_back(NewParm->getType());
3346 } else if (Context.typesAreCompatible(OldParm->getType(),
3347 NewParm->getType(),
3348 /*CompareUnqualified=*/true)) {
3349 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3350 NewProto->getParamType(Idx) };
3351 Warnings.push_back(Warn);
3352 ArgTypes.push_back(NewParm->getType());
3353 } else
3354 LooseCompatible = false;
3355 }
3356
3357 if (LooseCompatible) {
3358 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3359 Diag(Warnings[Warn].NewParm->getLocation(),
3360 diag::ext_param_promoted_not_compatible_with_prototype)
3361 << Warnings[Warn].PromotedType
3362 << Warnings[Warn].OldParm->getType();
3363 if (Warnings[Warn].OldParm->getLocation().isValid())
3364 Diag(Warnings[Warn].OldParm->getLocation(),
3365 diag::note_previous_declaration);
3366 }
3367
3368 if (MergeTypeWithOld)
3369 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3370 OldProto->getExtProtoInfo()));
3371 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3372 }
3373
3374 // Fall through to diagnose conflicting types.
3375 }
3376
3377 // A function that has already been declared has been redeclared or
3378 // defined with a different type; show an appropriate diagnostic.
3379
3380 // If the previous declaration was an implicitly-generated builtin
3381 // declaration, then at the very least we should use a specialized note.
3382 unsigned BuiltinID;
3383 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3384 // If it's actually a library-defined builtin function like 'malloc'
3385 // or 'printf', just warn about the incompatible redeclaration.
3386 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3387 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3388 Diag(OldLocation, diag::note_previous_builtin_declaration)
3389 << Old << Old->getType();
3390
3391 // If this is a global redeclaration, just forget hereafter
3392 // about the "builtin-ness" of the function.
3393 //
3394 // Doing this for local extern declarations is problematic. If
3395 // the builtin declaration remains visible, a second invalid
3396 // local declaration will produce a hard error; if it doesn't
3397 // remain visible, a single bogus local redeclaration (which is
3398 // actually only a warning) could break all the downstream code.
3399 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3400 New->getIdentifier()->revertBuiltin();
3401
3402 return false;
3403 }
3404
3405 PrevDiag = diag::note_previous_builtin_declaration;
3406 }
3407
3408 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3409 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3410 return true;
3411}
3412
3413/// \brief Completes the merge of two function declarations that are
3414/// known to be compatible.
3415///
3416/// This routine handles the merging of attributes and other
3417/// properties of function declarations from the old declaration to
3418/// the new declaration, once we know that New is in fact a
3419/// redeclaration of Old.
3420///
3421/// \returns false
3422bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3423 Scope *S, bool MergeTypeWithOld) {
3424 // Merge the attributes
3425 mergeDeclAttributes(New, Old);
3426
3427 // Merge "pure" flag.
3428 if (Old->isPure())
3429 New->setPure();
3430
3431 // Merge "used" flag.
3432 if (Old->getMostRecentDecl()->isUsed(false))
3433 New->setIsUsed();
3434
3435 // Merge attributes from the parameters. These can mismatch with K&R
3436 // declarations.
3437 if (New->getNumParams() == Old->getNumParams())
3438 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3439 ParmVarDecl *NewParam = New->getParamDecl(i);
3440 ParmVarDecl *OldParam = Old->getParamDecl(i);
3441 mergeParamDeclAttributes(NewParam, OldParam, *this);
3442 mergeParamDeclTypes(NewParam, OldParam, *this);
3443 }
3444
3445 if (getLangOpts().CPlusPlus)
3446 return MergeCXXFunctionDecl(New, Old, S);
3447
3448 // Merge the function types so the we get the composite types for the return
3449 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3450 // was visible.
3451 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3452 if (!Merged.isNull() && MergeTypeWithOld)
3453 New->setType(Merged);
3454
3455 return false;
3456}
3457
3458void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3459 ObjCMethodDecl *oldMethod) {
3460 // Merge the attributes, including deprecated/unavailable
3461 AvailabilityMergeKind MergeKind =
3462 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3463 ? AMK_ProtocolImplementation
3464 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3465 : AMK_Override;
3466
3467 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3468
3469 // Merge attributes from the parameters.
3470 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3471 oe = oldMethod->param_end();
3472 for (ObjCMethodDecl::param_iterator
3473 ni = newMethod->param_begin(), ne = newMethod->param_end();
3474 ni != ne && oi != oe; ++ni, ++oi)
3475 mergeParamDeclAttributes(*ni, *oi, *this);
3476
3477 CheckObjCMethodOverride(newMethod, oldMethod);
3478}
3479
3480static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3481 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())"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 3481, __PRETTY_FUNCTION__))
;
3482
3483 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3484 ? diag::err_redefinition_different_type
3485 : diag::err_redeclaration_different_type)
3486 << New->getDeclName() << New->getType() << Old->getType();
3487
3488 diag::kind PrevDiag;
3489 SourceLocation OldLocation;
3490 std::tie(PrevDiag, OldLocation)
3491 = getNoteDiagForInvalidRedeclaration(Old, New);
3492 S.Diag(OldLocation, PrevDiag);
3493 New->setInvalidDecl();
3494}
3495
3496/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3497/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3498/// emitting diagnostics as appropriate.
3499///
3500/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3501/// to here in AddInitializerToDecl. We can't check them before the initializer
3502/// is attached.
3503void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3504 bool MergeTypeWithOld) {
3505 if (New->isInvalidDecl() || Old->isInvalidDecl())
3506 return;
3507
3508 QualType MergedT;
3509 if (getLangOpts().CPlusPlus) {
3510 if (New->getType()->isUndeducedType()) {
3511 // We don't know what the new type is until the initializer is attached.
3512 return;
3513 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3514 // These could still be something that needs exception specs checked.
3515 return MergeVarDeclExceptionSpecs(New, Old);
3516 }
3517 // C++ [basic.link]p10:
3518 // [...] the types specified by all declarations referring to a given
3519 // object or function shall be identical, except that declarations for an
3520 // array object can specify array types that differ by the presence or
3521 // absence of a major array bound (8.3.4).
3522 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3523 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3524 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3525
3526 // We are merging a variable declaration New into Old. If it has an array
3527 // bound, and that bound differs from Old's bound, we should diagnose the
3528 // mismatch.
3529 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3530 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3531 PrevVD = PrevVD->getPreviousDecl()) {
3532 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3533 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3534 continue;
3535
3536 if (!Context.hasSameType(NewArray, PrevVDTy))
3537 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3538 }
3539 }
3540
3541 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3542 if (Context.hasSameType(OldArray->getElementType(),
3543 NewArray->getElementType()))
3544 MergedT = New->getType();
3545 }
3546 // FIXME: Check visibility. New is hidden but has a complete type. If New
3547 // has no array bound, it should not inherit one from Old, if Old is not
3548 // visible.
3549 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3550 if (Context.hasSameType(OldArray->getElementType(),
3551 NewArray->getElementType()))
3552 MergedT = Old->getType();
3553 }
3554 }
3555 else if (New->getType()->isObjCObjectPointerType() &&
3556 Old->getType()->isObjCObjectPointerType()) {
3557 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3558 Old->getType());
3559 }
3560 } else {
3561 // C 6.2.7p2:
3562 // All declarations that refer to the same object or function shall have
3563 // compatible type.
3564 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3565 }
3566 if (MergedT.isNull()) {
3567 // It's OK if we couldn't merge types if either type is dependent, for a
3568 // block-scope variable. In other cases (static data members of class
3569 // templates, variable templates, ...), we require the types to be
3570 // equivalent.
3571 // FIXME: The C++ standard doesn't say anything about this.
3572 if ((New->getType()->isDependentType() ||
3573 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3574 // If the old type was dependent, we can't merge with it, so the new type
3575 // becomes dependent for now. We'll reproduce the original type when we
3576 // instantiate the TypeSourceInfo for the variable.
3577 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3578 New->setType(Context.DependentTy);
3579 return;
3580 }
3581 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3582 }
3583
3584 // Don't actually update the type on the new declaration if the old
3585 // declaration was an extern declaration in a different scope.
3586 if (MergeTypeWithOld)
3587 New->setType(MergedT);
3588}
3589
3590static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3591 LookupResult &Previous) {
3592 // C11 6.2.7p4:
3593 // For an identifier with internal or external linkage declared
3594 // in a scope in which a prior declaration of that identifier is
3595 // visible, if the prior declaration specifies internal or
3596 // external linkage, the type of the identifier at the later
3597 // declaration becomes the composite type.
3598 //
3599 // If the variable isn't visible, we do not merge with its type.
3600 if (Previous.isShadowed())
3601 return false;
3602
3603 if (S.getLangOpts().CPlusPlus) {
3604 // C++11 [dcl.array]p3:
3605 // If there is a preceding declaration of the entity in the same
3606 // scope in which the bound was specified, an omitted array bound
3607 // is taken to be the same as in that earlier declaration.
3608 return NewVD->isPreviousDeclInSameBlockScope() ||
3609 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3610 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3611 } else {
3612 // If the old declaration was function-local, don't merge with its
3613 // type unless we're in the same function.
3614 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3615 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3616 }
3617}
3618
3619/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3620/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3621/// situation, merging decls or emitting diagnostics as appropriate.
3622///
3623/// Tentative definition rules (C99 6.9.2p2) are checked by
3624/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3625/// definitions here, since the initializer hasn't been attached.
3626///
3627void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3628 // If the new decl is already invalid, don't do any other checking.
3629 if (New->isInvalidDecl())
3630 return;
3631
3632 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3633 return;
3634
3635 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3636
3637 // Verify the old decl was also a variable or variable template.
3638 VarDecl *Old = nullptr;
3639 VarTemplateDecl *OldTemplate = nullptr;
3640 if (Previous.isSingleResult()) {
3641 if (NewTemplate) {
3642 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3643 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3644
3645 if (auto *Shadow =
3646 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3647 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3648 return New->setInvalidDecl();
3649 } else {
3650 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3651
3652 if (auto *Shadow =
3653 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3654 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3655 return New->setInvalidDecl();
3656 }
3657 }
3658 if (!Old) {
3659 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3660 << New->getDeclName();
3661 notePreviousDefinition(Previous.getRepresentativeDecl(),
3662 New->getLocation());
3663 return New->setInvalidDecl();
3664 }
3665
3666 // Ensure the template parameters are compatible.
3667 if (NewTemplate &&
3668 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3669 OldTemplate->getTemplateParameters(),
3670 /*Complain=*/true, TPL_TemplateMatch))
3671 return New->setInvalidDecl();
3672
3673 // C++ [class.mem]p1:
3674 // A member shall not be declared twice in the member-specification [...]
3675 //
3676 // Here, we need only consider static data members.
3677 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3678 Diag(New->getLocation(), diag::err_duplicate_member)
3679 << New->getIdentifier();
3680 Diag(Old->getLocation(), diag::note_previous_declaration);
3681 New->setInvalidDecl();
3682 }
3683
3684 mergeDeclAttributes(New, Old);
3685 // Warn if an already-declared variable is made a weak_import in a subsequent
3686 // declaration
3687 if (New->hasAttr<WeakImportAttr>() &&
3688 Old->getStorageClass() == SC_None &&
3689 !Old->hasAttr<WeakImportAttr>()) {
3690 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3691 notePreviousDefinition(Old, New->getLocation());
3692 // Remove weak_import attribute on new declaration.
3693 New->dropAttr<WeakImportAttr>();
3694 }
3695
3696 if (New->hasAttr<InternalLinkageAttr>() &&
3697 !Old->hasAttr<InternalLinkageAttr>()) {
3698 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3699 << New->getDeclName();
3700 notePreviousDefinition(Old, New->getLocation());
3701 New->dropAttr<InternalLinkageAttr>();
3702 }
3703
3704 // Merge the types.
3705 VarDecl *MostRecent = Old->getMostRecentDecl();
3706 if (MostRecent != Old) {
3707 MergeVarDeclTypes(New, MostRecent,
3708 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3709 if (New->isInvalidDecl())
3710 return;
3711 }
3712
3713 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3714 if (New->isInvalidDecl())
3715 return;
3716
3717 diag::kind PrevDiag;
3718 SourceLocation OldLocation;
3719 std::tie(PrevDiag, OldLocation) =
3720 getNoteDiagForInvalidRedeclaration(Old, New);
3721
3722 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3723 if (New->getStorageClass() == SC_Static &&
3724 !New->isStaticDataMember() &&
3725 Old->hasExternalFormalLinkage()) {
3726 if (getLangOpts().MicrosoftExt) {
3727 Diag(New->getLocation(), diag::ext_static_non_static)
3728 << New->getDeclName();
3729 Diag(OldLocation, PrevDiag);
3730 } else {
3731 Diag(New->getLocation(), diag::err_static_non_static)
3732 << New->getDeclName();
3733 Diag(OldLocation, PrevDiag);
3734 return New->setInvalidDecl();
3735 }
3736 }
3737 // C99 6.2.2p4:
3738 // For an identifier declared with the storage-class specifier
3739 // extern in a scope in which a prior declaration of that
3740 // identifier is visible,23) if the prior declaration specifies
3741 // internal or external linkage, the linkage of the identifier at
3742 // the later declaration is the same as the linkage specified at
3743 // the prior declaration. If no prior declaration is visible, or
3744 // if the prior declaration specifies no linkage, then the
3745 // identifier has external linkage.
3746 if (New->hasExternalStorage() && Old->hasLinkage())
3747 /* Okay */;
3748 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3749 !New->isStaticDataMember() &&
3750 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3751 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3752 Diag(OldLocation, PrevDiag);
3753 return New->setInvalidDecl();
3754 }
3755
3756 // Check if extern is followed by non-extern and vice-versa.
3757 if (New->hasExternalStorage() &&
3758 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3759 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3760 Diag(OldLocation, PrevDiag);
3761 return New->setInvalidDecl();
3762 }
3763 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3764 !New->hasExternalStorage()) {
3765 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3766 Diag(OldLocation, PrevDiag);
3767 return New->setInvalidDecl();
3768 }
3769
3770 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3771
3772 // FIXME: The test for external storage here seems wrong? We still
3773 // need to check for mismatches.
3774 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3775 // Don't complain about out-of-line definitions of static members.
3776 !(Old->getLexicalDeclContext()->isRecord() &&
3777 !New->getLexicalDeclContext()->isRecord())) {
3778 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3779 Diag(OldLocation, PrevDiag);
3780 return New->setInvalidDecl();
3781 }
3782
3783 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3784 if (VarDecl *Def = Old->getDefinition()) {
3785 // C++1z [dcl.fcn.spec]p4:
3786 // If the definition of a variable appears in a translation unit before
3787 // its first declaration as inline, the program is ill-formed.
3788 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3789 Diag(Def->getLocation(), diag::note_previous_definition);
3790 }
3791 }
3792
3793 // If this redeclaration makes the function inline, we may need to add it to
3794 // UndefinedButUsed.
3795 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3796 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3797 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3798 SourceLocation()));
3799
3800 if (New->getTLSKind() != Old->getTLSKind()) {
3801 if (!Old->getTLSKind()) {
3802 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3803 Diag(OldLocation, PrevDiag);
3804 } else if (!New->getTLSKind()) {
3805 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3806 Diag(OldLocation, PrevDiag);
3807 } else {
3808 // Do not allow redeclaration to change the variable between requiring
3809 // static and dynamic initialization.
3810 // FIXME: GCC allows this, but uses the TLS keyword on the first
3811 // declaration to determine the kind. Do we need to be compatible here?
3812 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3813 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3814 Diag(OldLocation, PrevDiag);
3815 }
3816 }
3817
3818 // C++ doesn't have tentative definitions, so go right ahead and check here.
3819 if (getLangOpts().CPlusPlus &&
3820 New->isThisDeclarationADefinition() == VarDecl::Definition) {
3821 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3822 Old->getCanonicalDecl()->isConstexpr()) {
3823 // This definition won't be a definition any more once it's been merged.
3824 Diag(New->getLocation(),
3825 diag::warn_deprecated_redundant_constexpr_static_def);
3826 } else if (VarDecl *Def = Old->getDefinition()) {
3827 if (checkVarDeclRedefinition(Def, New))
3828 return;
3829 }
3830 }
3831
3832 if (haveIncompatibleLanguageLinkages(Old, New)) {
3833 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3834 Diag(OldLocation, PrevDiag);
3835 New->setInvalidDecl();
3836 return;
3837 }
3838
3839 // Merge "used" flag.
3840 if (Old->getMostRecentDecl()->isUsed(false))
3841 New->setIsUsed();
3842
3843 // Keep a chain of previous declarations.
3844 New->setPreviousDecl(Old);
3845 if (NewTemplate)
3846 NewTemplate->setPreviousDecl(OldTemplate);
3847
3848 // Inherit access appropriately.
3849 New->setAccess(Old->getAccess());
3850 if (NewTemplate)
3851 NewTemplate->setAccess(New->getAccess());
3852
3853 if (Old->isInline())
3854 New->setImplicitlyInline();
3855}
3856
3857void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
3858 SourceManager &SrcMgr = getSourceManager();
3859 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
3860 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
3861 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
3862 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
3863 auto &HSI = PP.getHeaderSearchInfo();
3864 StringRef HdrFilename =
3865 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
3866
3867 auto noteFromModuleOrInclude = [&](Module *Mod,
3868 SourceLocation IncLoc) -> bool {
3869 // Redefinition errors with modules are common with non modular mapped
3870 // headers, example: a non-modular header H in module A that also gets
3871 // included directly in a TU. Pointing twice to the same header/definition
3872 // is confusing, try to get better diagnostics when modules is on.
3873 if (IncLoc.isValid()) {
3874 if (Mod) {
3875 Diag(IncLoc, diag::note_redefinition_modules_same_file)
3876 << HdrFilename.str() << Mod->getFullModuleName();
3877 if (!Mod->DefinitionLoc.isInvalid())
3878 Diag(Mod->DefinitionLoc, diag::note_defined_here)
3879 << Mod->getFullModuleName();
3880 } else {
3881 Diag(IncLoc, diag::note_redefinition_include_same_file)
3882 << HdrFilename.str();
3883 }
3884 return true;
3885 }
3886
3887 return false;
3888 };
3889
3890 // Is it the same file and same offset? Provide more information on why
3891 // this leads to a redefinition error.
3892 bool EmittedDiag = false;
3893 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
3894 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
3895 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
3896 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
3897 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
3898
3899 // If the header has no guards, emit a note suggesting one.
3900 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
3901 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
3902
3903 if (EmittedDiag)
3904 return;
3905 }
3906
3907 // Redefinition coming from different files or couldn't do better above.
3908 Diag(Old->getLocation(), diag::note_previous_definition);
3909}
3910
3911/// We've just determined that \p Old and \p New both appear to be definitions
3912/// of the same variable. Either diagnose or fix the problem.
3913bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3914 if (!hasVisibleDefinition(Old) &&
3915 (New->getFormalLinkage() == InternalLinkage ||
3916 New->isInline() ||
3917 New->getDescribedVarTemplate() ||
3918 New->getNumTemplateParameterLists() ||
3919 New->getDeclContext()->isDependentContext())) {
3920 // The previous definition is hidden, and multiple definitions are
3921 // permitted (in separate TUs). Demote this to a declaration.
3922 New->demoteThisDefinitionToDeclaration();
3923
3924 // Make the canonical definition visible.
3925 if (auto *OldTD = Old->getDescribedVarTemplate())
3926 makeMergedDefinitionVisible(OldTD);
3927 makeMergedDefinitionVisible(Old);
3928 return false;
3929 } else {
3930 Diag(New->getLocation(), diag::err_redefinition) << New;
3931 notePreviousDefinition(Old, New->getLocation());
3932 New->setInvalidDecl();
3933 return true;
3934 }
3935}
3936
3937/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3938/// no declarator (e.g. "struct foo;") is parsed.
3939Decl *
3940Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3941 RecordDecl *&AnonRecord) {
3942 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3943 AnonRecord);
3944}
3945
3946// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3947// disambiguate entities defined in different scopes.
3948// While the VS2015 ABI fixes potential miscompiles, it is also breaks
3949// compatibility.
3950// We will pick our mangling number depending on which version of MSVC is being
3951// targeted.
3952static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3953 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3954 ? S->getMSCurManglingNumber()
3955 : S->getMSLastManglingNumber();
3956}
3957
3958void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3959 if (!Context.getLangOpts().CPlusPlus)
3960 return;
3961
3962 if (isa<CXXRecordDecl>(Tag->getParent())) {
3963 // If this tag is the direct child of a class, number it if
3964 // it is anonymous.
3965 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3966 return;
3967 MangleNumberingContext &MCtx =
3968 Context.getManglingNumberContext(Tag->getParent());
3969 Context.setManglingNumber(
3970 Tag, MCtx.getManglingNumber(
3971 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3972 return;
3973 }
3974
3975 // If this tag isn't a direct child of a class, number it if it is local.
3976 Decl *ManglingContextDecl;
3977 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3978 Tag->getDeclContext(), ManglingContextDecl)) {
3979 Context.setManglingNumber(
3980 Tag, MCtx->getManglingNumber(
3981 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3982 }
3983}
3984
3985void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3986 TypedefNameDecl *NewTD) {
3987 if (TagFromDeclSpec->isInvalidDecl())
3988 return;
3989
3990 // Do nothing if the tag already has a name for linkage purposes.
3991 if (TagFromDeclSpec->hasNameForLinkage())
3992 return;
3993
3994 // A well-formed anonymous tag must always be a TUK_Definition.
3995 assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast
<void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 3995, __PRETTY_FUNCTION__))
;
3996
3997 // The type must match the tag exactly; no qualifiers allowed.
3998 if (!Context.hasSameType(NewTD->getUnderlyingType(),
3999 Context.getTagDeclType(TagFromDeclSpec))) {
4000 if (getLangOpts().CPlusPlus)
4001 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4002 return;
4003 }
4004
4005 // If we've already computed linkage for the anonymous tag, then
4006 // adding a typedef name for the anonymous decl can change that
4007 // linkage, which might be a serious problem. Diagnose this as
4008 // unsupported and ignore the typedef name. TODO: we should
4009 // pursue this as a language defect and establish a formal rule
4010 // for how to handle it.
4011 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4012 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4013
4014 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4015 tagLoc = getLocForEndOfToken(tagLoc);
4016
4017 llvm::SmallString<40> textToInsert;
4018 textToInsert += ' ';
4019 textToInsert += NewTD->getIdentifier()->getName();
4020 Diag(tagLoc, diag::note_typedef_changes_linkage)
4021 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4022 return;
4023 }
4024
4025 // Otherwise, set this is the anon-decl typedef for the tag.
4026 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4027}
4028
4029static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4030 switch (T) {
4031 case DeclSpec::TST_class:
4032 return 0;
4033 case DeclSpec::TST_struct:
4034 return 1;
4035 case DeclSpec::TST_interface:
4036 return 2;
4037 case DeclSpec::TST_union:
4038 return 3;
4039 case DeclSpec::TST_enum:
4040 return 4;
4041 default:
4042 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4042)
;
4043 }
4044}
4045
4046/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4047/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4048/// parameters to cope with template friend declarations.
4049Decl *
4050Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4051 MultiTemplateParamsArg TemplateParams,
4052 bool IsExplicitInstantiation,
4053 RecordDecl *&AnonRecord) {
4054 Decl *TagD = nullptr;
4055 TagDecl *Tag = nullptr;
4056 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4057 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4058 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4059 DS.getTypeSpecType() == DeclSpec::TST_union ||
4060 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4061 TagD = DS.getRepAsDecl();
4062
4063 if (!TagD) // We probably had an error
4064 return nullptr;
4065
4066 // Note that the above type specs guarantee that the
4067 // type rep is a Decl, whereas in many of the others
4068 // it's a Type.
4069 if (isa<TagDecl>(TagD))
4070 Tag = cast<TagDecl>(TagD);
4071 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4072 Tag = CTD->getTemplatedDecl();
4073 }
4074
4075 if (Tag) {
4076 handleTagNumbering(Tag, S);
4077 Tag->setFreeStanding();
4078 if (Tag->isInvalidDecl())
4079 return Tag;
4080 }
4081
4082 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4083 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4084 // or incomplete types shall not be restrict-qualified."
4085 if (TypeQuals & DeclSpec::TQ_restrict)
4086 Diag(DS.getRestrictSpecLoc(),
4087 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4088 << DS.getSourceRange();
4089 }
4090
4091 if (DS.isInlineSpecified())
4092 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4093 << getLangOpts().CPlusPlus1z;
4094
4095 if (DS.isConstexprSpecified()) {
4096 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4097 // and definitions of functions and variables.
4098 if (Tag)
4099 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4100 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4101 else
4102 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4103 // Don't emit warnings after this error.
4104 return TagD;
4105 }
4106
4107 if (DS.isConceptSpecified()) {
4108 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
4109 // either a function concept and its definition or a variable concept and
4110 // its initializer.
4111 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
4112 return TagD;
4113 }
4114
4115 DiagnoseFunctionSpecifiers(DS);
4116
4117 if (DS.isFriendSpecified()) {
4118 // If we're dealing with a decl but not a TagDecl, assume that
4119 // whatever routines created it handled the friendship aspect.
4120 if (TagD && !Tag)
4121 return nullptr;
4122 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4123 }
4124
4125 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4126 bool IsExplicitSpecialization =
4127 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4128 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4129 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4130 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4131 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4132 // nested-name-specifier unless it is an explicit instantiation
4133 // or an explicit specialization.
4134 //
4135 // FIXME: We allow class template partial specializations here too, per the
4136 // obvious intent of DR1819.
4137 //
4138 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4139 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4140 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4141 return nullptr;
4142 }
4143
4144 // Track whether this decl-specifier declares anything.
4145 bool DeclaresAnything = true;
4146
4147 // Handle anonymous struct definitions.
4148 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4149 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4150 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4151 if (getLangOpts().CPlusPlus ||
4152 Record->getDeclContext()->isRecord()) {
4153 // If CurContext is a DeclContext that can contain statements,
4154 // RecursiveASTVisitor won't visit the decls that
4155 // BuildAnonymousStructOrUnion() will put into CurContext.
4156 // Also store them here so that they can be part of the
4157 // DeclStmt that gets created in this case.
4158 // FIXME: Also return the IndirectFieldDecls created by
4159 // BuildAnonymousStructOr union, for the same reason?
4160 if (CurContext->isFunctionOrMethod())
4161 AnonRecord = Record;
4162 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4163 Context.getPrintingPolicy());
4164 }
4165
4166 DeclaresAnything = false;
4167 }
4168 }
4169
4170 // C11 6.7.2.1p2:
4171 // A struct-declaration that does not declare an anonymous structure or
4172 // anonymous union shall contain a struct-declarator-list.
4173 //
4174 // This rule also existed in C89 and C99; the grammar for struct-declaration
4175 // did not permit a struct-declaration without a struct-declarator-list.
4176 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4177 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4178 // Check for Microsoft C extension: anonymous struct/union member.
4179 // Handle 2 kinds of anonymous struct/union:
4180 // struct STRUCT;
4181 // union UNION;
4182 // and
4183 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4184 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4185 if ((Tag && Tag->getDeclName()) ||
4186 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4187 RecordDecl *Record = nullptr;
4188 if (Tag)
4189 Record = dyn_cast<RecordDecl>(Tag);
4190 else if (const RecordType *RT =
4191 DS.getRepAsType().get()->getAsStructureType())
4192 Record = RT->getDecl();
4193 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4194 Record = UT->getDecl();
4195
4196 if (Record && getLangOpts().MicrosoftExt) {
4197 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4198 << Record->isUnion() << DS.getSourceRange();
4199 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4200 }
4201
4202 DeclaresAnything = false;
4203 }
4204 }
4205
4206 // Skip all the checks below if we have a type error.
4207 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4208 (TagD && TagD->isInvalidDecl()))
4209 return TagD;
4210
4211 if (getLangOpts().CPlusPlus &&
4212 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4213 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4214 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4215 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4216 DeclaresAnything = false;
4217
4218 if (!DS.isMissingDeclaratorOk()) {
4219 // Customize diagnostic for a typedef missing a name.
4220 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4221 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4222 << DS.getSourceRange();
4223 else
4224 DeclaresAnything = false;
4225 }
4226
4227 if (DS.isModulePrivateSpecified() &&
4228 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4229 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4230 << Tag->getTagKind()
4231 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4232
4233 ActOnDocumentableDecl(TagD);
4234
4235 // C 6.7/2:
4236 // A declaration [...] shall declare at least a declarator [...], a tag,
4237 // or the members of an enumeration.
4238 // C++ [dcl.dcl]p3:
4239 // [If there are no declarators], and except for the declaration of an
4240 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4241 // names into the program, or shall redeclare a name introduced by a
4242 // previous declaration.
4243 if (!DeclaresAnything) {
4244 // In C, we allow this as a (popular) extension / bug. Don't bother
4245 // producing further diagnostics for redundant qualifiers after this.
4246 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4247 return TagD;
4248 }
4249
4250 // C++ [dcl.stc]p1:
4251 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4252 // init-declarator-list of the declaration shall not be empty.
4253 // C++ [dcl.fct.spec]p1:
4254 // If a cv-qualifier appears in a decl-specifier-seq, the
4255 // init-declarator-list of the declaration shall not be empty.
4256 //
4257 // Spurious qualifiers here appear to be valid in C.
4258 unsigned DiagID = diag::warn_standalone_specifier;
4259 if (getLangOpts().CPlusPlus)
4260 DiagID = diag::ext_standalone_specifier;
4261
4262 // Note that a linkage-specification sets a storage class, but
4263 // 'extern "C" struct foo;' is actually valid and not theoretically
4264 // useless.
4265 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4266 if (SCS == DeclSpec::SCS_mutable)
4267 // Since mutable is not a viable storage class specifier in C, there is
4268 // no reason to treat it as an extension. Instead, diagnose as an error.
4269 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4270 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4271 Diag(DS.getStorageClassSpecLoc(), DiagID)
4272 << DeclSpec::getSpecifierName(SCS);
4273 }
4274
4275 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4276 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4277 << DeclSpec::getSpecifierName(TSCS);
4278 if (DS.getTypeQualifiers()) {
4279 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4280 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4281 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4282 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4283 // Restrict is covered above.
4284 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4285 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4286 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4287 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4288 }
4289
4290 // Warn about ignored type attributes, for example:
4291 // __attribute__((aligned)) struct A;
4292 // Attributes should be placed after tag to apply to type declaration.
4293 if (!DS.getAttributes().empty()) {
4294 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4295 if (TypeSpecType == DeclSpec::TST_class ||
4296 TypeSpecType == DeclSpec::TST_struct ||
4297 TypeSpecType == DeclSpec::TST_interface ||
4298 TypeSpecType == DeclSpec::TST_union ||
4299 TypeSpecType == DeclSpec::TST_enum) {
4300 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4301 attrs = attrs->getNext())
4302 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4303 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4304 }
4305 }
4306
4307 return TagD;
4308}
4309
4310/// We are trying to inject an anonymous member into the given scope;
4311/// check if there's an existing declaration that can't be overloaded.
4312///
4313/// \return true if this is a forbidden redeclaration
4314static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4315 Scope *S,
4316 DeclContext *Owner,
4317 DeclarationName Name,
4318 SourceLocation NameLoc,
4319 bool IsUnion) {
4320 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4321 Sema::ForRedeclaration);
4322 if (!SemaRef.LookupName(R, S)) return false;
4323
4324 // Pick a representative declaration.
4325 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4326 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4326, __PRETTY_FUNCTION__))
;
4327
4328 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4329 return false;
4330
4331 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4332 << IsUnion << Name;
4333 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4334
4335 return true;
4336}
4337
4338/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4339/// anonymous struct or union AnonRecord into the owning context Owner
4340/// and scope S. This routine will be invoked just after we realize
4341/// that an unnamed union or struct is actually an anonymous union or
4342/// struct, e.g.,
4343///
4344/// @code
4345/// union {
4346/// int i;
4347/// float f;
4348/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4349/// // f into the surrounding scope.x
4350/// @endcode
4351///
4352/// This routine is recursive, injecting the names of nested anonymous
4353/// structs/unions into the owning context and scope as well.
4354static bool
4355InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4356 RecordDecl *AnonRecord, AccessSpecifier AS,
4357 SmallVectorImpl<NamedDecl *> &Chaining) {
4358 bool Invalid = false;
4359
4360 // Look every FieldDecl and IndirectFieldDecl with a name.
4361 for (auto *D : AnonRecord->decls()) {
4362 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4363 cast<NamedDecl>(D)->getDeclName()) {
4364 ValueDecl *VD = cast<ValueDecl>(D);
4365 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4366 VD->getLocation(),
4367 AnonRecord->isUnion())) {
4368 // C++ [class.union]p2:
4369 // The names of the members of an anonymous union shall be
4370 // distinct from the names of any other entity in the
4371 // scope in which the anonymous union is declared.
4372 Invalid = true;
4373 } else {
4374 // C++ [class.union]p2:
4375 // For the purpose of name lookup, after the anonymous union
4376 // definition, the members of the anonymous union are
4377 // considered to have been defined in the scope in which the
4378 // anonymous union is declared.
4379 unsigned OldChainingSize = Chaining.size();
4380 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4381 Chaining.append(IF->chain_begin(), IF->chain_end());
4382 else
4383 Chaining.push_back(VD);
4384
4385 assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail
("Chaining.size() >= 2", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4385, __PRETTY_FUNCTION__))
;
4386 NamedDecl **NamedChain =
4387 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4388 for (unsigned i = 0; i < Chaining.size(); i++)
4389 NamedChain[i] = Chaining[i];
4390
4391 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4392 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4393 VD->getType(), {NamedChain, Chaining.size()});
4394
4395 for (const auto *Attr : VD->attrs())
4396 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4397
4398 IndirectField->setAccess(AS);
4399 IndirectField->setImplicit();
4400 SemaRef.PushOnScopeChains(IndirectField, S);
4401
4402 // That includes picking up the appropriate access specifier.
4403 if (AS != AS_none) IndirectField->setAccess(AS);
4404
4405 Chaining.resize(OldChainingSize);
4406 }
4407 }
4408 }
4409
4410 return Invalid;
4411}
4412
4413/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4414/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4415/// illegal input values are mapped to SC_None.
4416static StorageClass
4417StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4418 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4419 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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4420, __PRETTY_FUNCTION__))
4420 "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.\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4420, __PRETTY_FUNCTION__))
;
4421 switch (StorageClassSpec) {
4422 case DeclSpec::SCS_unspecified: return SC_None;
4423 case DeclSpec::SCS_extern:
4424 if (DS.isExternInLinkageSpec())
4425 return SC_None;
4426 return SC_Extern;
4427 case DeclSpec::SCS_static: return SC_Static;
4428 case DeclSpec::SCS_auto: return SC_Auto;
4429 case DeclSpec::SCS_register: return SC_Register;
4430 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4431 // Illegal SCSs map to None: error reporting is up to the caller.
4432 case DeclSpec::SCS_mutable: // Fall through.
4433 case DeclSpec::SCS_typedef: return SC_None;
4434 }
4435 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4435)
;
4436}
4437
4438static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4439 assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Record->hasInClassInitializer()", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4439, __PRETTY_FUNCTION__))
;
4440
4441 for (const auto *I : Record->decls()) {
4442 const auto *FD = dyn_cast<FieldDecl>(I);
4443 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4444 FD = IFD->getAnonField();
4445 if (FD && FD->hasInClassInitializer())
4446 return FD->getLocation();
4447 }
4448
4449 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4449)
;
4450}
4451
4452static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4453 SourceLocation DefaultInitLoc) {
4454 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4455 return;
4456
4457 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4458 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4459}
4460
4461static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4462 CXXRecordDecl *AnonUnion) {
4463 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4464 return;
4465
4466 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4467}
4468
4469/// BuildAnonymousStructOrUnion - Handle the declaration of an
4470/// anonymous structure or union. Anonymous unions are a C++ feature
4471/// (C++ [class.union]) and a C11 feature; anonymous structures
4472/// are a C11 feature and GNU C++ extension.
4473Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4474 AccessSpecifier AS,
4475 RecordDecl *Record,
4476 const PrintingPolicy &Policy) {
4477 DeclContext *Owner = Record->getDeclContext();
4478
4479 // Diagnose whether this anonymous struct/union is an extension.
4480 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4481 Diag(Record->getLocation(), diag::ext_anonymous_union);
4482 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4483 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4484 else if (!Record->isUnion() && !getLangOpts().C11)
4485 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4486
4487 // C and C++ require different kinds of checks for anonymous
4488 // structs/unions.
4489 bool Invalid = false;
4490 if (getLangOpts().CPlusPlus) {
4491 const char *PrevSpec = nullptr;
4492 unsigned DiagID;
4493 if (Record->isUnion()) {
4494 // C++ [class.union]p6:
4495 // Anonymous unions declared in a named namespace or in the
4496 // global namespace shall be declared static.
4497 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4498 (isa<TranslationUnitDecl>(Owner) ||
4499 (isa<NamespaceDecl>(Owner) &&
4500 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4501 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4502 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4503
4504 // Recover by adding 'static'.
4505 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4506 PrevSpec, DiagID, Policy);
4507 }
4508 // C++ [class.union]p6:
4509 // A storage class is not allowed in a declaration of an
4510 // anonymous union in a class scope.
4511 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4512 isa<RecordDecl>(Owner)) {
4513 Diag(DS.getStorageClassSpecLoc(),
4514 diag::err_anonymous_union_with_storage_spec)
4515 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4516
4517 // Recover by removing the storage specifier.
4518 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4519 SourceLocation(),
4520 PrevSpec, DiagID, Context.getPrintingPolicy());
4521 }
4522 }
4523
4524 // Ignore const/volatile/restrict qualifiers.
4525 if (DS.getTypeQualifiers()) {
4526 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4527 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4528 << Record->isUnion() << "const"
4529 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4530 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4531 Diag(DS.getVolatileSpecLoc(),
4532 diag::ext_anonymous_struct_union_qualified)
4533 << Record->isUnion() << "volatile"
4534 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4535 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4536 Diag(DS.getRestrictSpecLoc(),
4537 diag::ext_anonymous_struct_union_qualified)
4538 << Record->isUnion() << "restrict"
4539 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4540 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4541 Diag(DS.getAtomicSpecLoc(),
4542 diag::ext_anonymous_struct_union_qualified)
4543 << Record->isUnion() << "_Atomic"
4544 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4545 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4546 Diag(DS.getUnalignedSpecLoc(),
4547 diag::ext_anonymous_struct_union_qualified)
4548 << Record->isUnion() << "__unaligned"
4549 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4550
4551 DS.ClearTypeQualifiers();
4552 }
4553
4554 // C++ [class.union]p2:
4555 // The member-specification of an anonymous union shall only
4556 // define non-static data members. [Note: nested types and
4557 // functions cannot be declared within an anonymous union. ]
4558 for (auto *Mem : Record->decls()) {
4559 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4560 // C++ [class.union]p3:
4561 // An anonymous union shall not have private or protected
4562 // members (clause 11).
4563 assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0
) : __assert_fail ("FD->getAccess() != AS_none", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4563, __PRETTY_FUNCTION__))
;
4564 if (FD->getAccess() != AS_public) {
4565 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4566 << Record->isUnion() << (FD->getAccess() == AS_protected);
4567 Invalid = true;
4568 }
4569
4570 // C++ [class.union]p1
4571 // An object of a class with a non-trivial constructor, a non-trivial
4572 // copy constructor, a non-trivial destructor, or a non-trivial copy
4573 // assignment operator cannot be a member of a union, nor can an
4574 // array of such objects.
4575 if (CheckNontrivialField(FD))
4576 Invalid = true;
4577 } else if (Mem->isImplicit()) {
4578 // Any implicit members are fine.
4579 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4580 // This is a type that showed up in an
4581 // elaborated-type-specifier inside the anonymous struct or
4582 // union, but which actually declares a type outside of the
4583 // anonymous struct or union. It's okay.
4584 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4585 if (!MemRecord->isAnonymousStructOrUnion() &&
4586 MemRecord->getDeclName()) {
4587 // Visual C++ allows type definition in anonymous struct or union.
4588 if (getLangOpts().MicrosoftExt)
4589 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4590 << Record->isUnion();
4591 else {
4592 // This is a nested type declaration.
4593 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4594 << Record->isUnion();
4595 Invalid = true;
4596 }
4597 } else {
4598 // This is an anonymous type definition within another anonymous type.
4599 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4600 // not part of standard C++.
4601 Diag(MemRecord->getLocation(),
4602 diag::ext_anonymous_record_with_anonymous_type)
4603 << Record->isUnion();
4604 }
4605 } else if (isa<AccessSpecDecl>(Mem)) {
4606 // Any access specifier is fine.
4607 } else if (isa<StaticAssertDecl>(Mem)) {
4608 // In C++1z, static_assert declarations are also fine.
4609 } else {
4610 // We have something that isn't a non-static data
4611 // member. Complain about it.
4612 unsigned DK = diag::err_anonymous_record_bad_member;
4613 if (isa<TypeDecl>(Mem))
4614 DK = diag::err_anonymous_record_with_type;
4615 else if (isa<FunctionDecl>(Mem))
4616 DK = diag::err_anonymous_record_with_function;
4617 else if (isa<VarDecl>(Mem))
4618 DK = diag::err_anonymous_record_with_static;
4619
4620 // Visual C++ allows type definition in anonymous struct or union.
4621 if (getLangOpts().MicrosoftExt &&
4622 DK == diag::err_anonymous_record_with_type)
4623 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4624 << Record->isUnion();
4625 else {
4626 Diag(Mem->getLocation(), DK) << Record->isUnion();
4627 Invalid = true;
4628 }
4629 }
4630 }
4631
4632 // C++11 [class.union]p8 (DR1460):
4633 // At most one variant member of a union may have a
4634 // brace-or-equal-initializer.
4635 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4636 Owner->isRecord())
4637 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4638 cast<CXXRecordDecl>(Record));
4639 }
4640
4641 if (!Record->isUnion() && !Owner->isRecord()) {
4642 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4643 << getLangOpts().CPlusPlus;
4644 Invalid = true;
4645 }
4646
4647 // Mock up a declarator.
4648 Declarator Dc(DS, Declarator::MemberContext);
4649 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4650 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4650, __PRETTY_FUNCTION__))
;
4651
4652 // Create a declaration for this anonymous struct/union.
4653 NamedDecl *Anon = nullptr;
4654 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4655 Anon = FieldDecl::Create(Context, OwningClass,
4656 DS.getLocStart(),
4657 Record->getLocation(),
4658 /*IdentifierInfo=*/nullptr,
4659 Context.getTypeDeclType(Record),
4660 TInfo,
4661 /*BitWidth=*/nullptr, /*Mutable=*/false,
4662 /*InitStyle=*/ICIS_NoInit);
4663 Anon->setAccess(AS);
4664 if (getLangOpts().CPlusPlus)
4665 FieldCollector->Add(cast<FieldDecl>(Anon));
4666 } else {
4667 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4668 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4669 if (SCSpec == DeclSpec::SCS_mutable) {
4670 // mutable can only appear on non-static class members, so it's always
4671 // an error here
4672 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4673 Invalid = true;
4674 SC = SC_None;
4675 }
4676
4677 Anon = VarDecl::Create(Context, Owner,
4678 DS.getLocStart(),
4679 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4680 Context.getTypeDeclType(Record),
4681 TInfo, SC);
4682
4683 // Default-initialize the implicit variable. This initialization will be
4684 // trivial in almost all cases, except if a union member has an in-class
4685 // initializer:
4686 // union { int n = 0; };
4687 ActOnUninitializedDecl(Anon);
4688 }
4689 Anon->setImplicit();
4690
4691 // Mark this as an anonymous struct/union type.
4692 Record->setAnonymousStructOrUnion(true);
4693
4694 // Add the anonymous struct/union object to the current
4695 // context. We'll be referencing this object when we refer to one of
4696 // its members.
4697 Owner->addDecl(Anon);
4698
4699 // Inject the members of the anonymous struct/union into the owning
4700 // context and into the identifier resolver chain for name lookup
4701 // purposes.
4702 SmallVector<NamedDecl*, 2> Chain;
4703 Chain.push_back(Anon);
4704
4705 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4706 Invalid = true;
4707
4708 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4709 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4710 Decl *ManglingContextDecl;
4711 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4712 NewVD->getDeclContext(), ManglingContextDecl)) {
4713 Context.setManglingNumber(
4714 NewVD, MCtx->getManglingNumber(
4715 NewVD, getMSManglingNumber(getLangOpts(), S)));
4716 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4717 }
4718 }
4719 }
4720
4721 if (Invalid)
4722 Anon->setInvalidDecl();
4723
4724 return Anon;
4725}
4726
4727/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4728/// Microsoft C anonymous structure.
4729/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4730/// Example:
4731///
4732/// struct A { int a; };
4733/// struct B { struct A; int b; };
4734///
4735/// void foo() {
4736/// B var;
4737/// var.a = 3;
4738/// }
4739///
4740Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4741 RecordDecl *Record) {
4742 assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void
> (0) : __assert_fail ("Record && \"expected a record!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4742, __PRETTY_FUNCTION__))
;
4743
4744 // Mock up a declarator.
4745 Declarator Dc(DS, Declarator::TypeNameContext);
4746 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4747 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\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4747, __PRETTY_FUNCTION__))
;
4748
4749 auto *ParentDecl = cast<RecordDecl>(CurContext);
4750 QualType RecTy = Context.getTypeDeclType(Record);
4751
4752 // Create a declaration for this anonymous struct.
4753 NamedDecl *Anon = FieldDecl::Create(Context,
4754 ParentDecl,
4755 DS.getLocStart(),
4756 DS.getLocStart(),
4757 /*IdentifierInfo=*/nullptr,
4758 RecTy,
4759 TInfo,
4760 /*BitWidth=*/nullptr, /*Mutable=*/false,
4761 /*InitStyle=*/ICIS_NoInit);
4762 Anon->setImplicit();
4763
4764 // Add the anonymous struct object to the current context.
4765 CurContext->addDecl(Anon);
4766
4767 // Inject the members of the anonymous struct into the current
4768 // context and into the identifier resolver chain for name lookup
4769 // purposes.
4770 SmallVector<NamedDecl*, 2> Chain;
4771 Chain.push_back(Anon);
4772
4773 RecordDecl *RecordDef = Record->getDefinition();
4774 if (RequireCompleteType(Anon->getLocation(), RecTy,
4775 diag::err_field_incomplete) ||
4776 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4777 AS_none, Chain)) {
4778 Anon->setInvalidDecl();
4779 ParentDecl->setInvalidDecl();
4780 }
4781
4782 return Anon;
4783}
4784
4785/// GetNameForDeclarator - Determine the full declaration name for the
4786/// given Declarator.
4787DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4788 return GetNameFromUnqualifiedId(D.getName());
4789}
4790
4791/// \brief Retrieves the declaration name from a parsed unqualified-id.
4792DeclarationNameInfo
4793Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4794 DeclarationNameInfo NameInfo;
4795 NameInfo.setLoc(Name.StartLocation);
4796
4797 switch (Name.getKind()) {
4798
4799 case UnqualifiedId::IK_ImplicitSelfParam:
4800 case UnqualifiedId::IK_Identifier:
4801 NameInfo.setName(Name.Identifier);
4802 NameInfo.setLoc(Name.StartLocation);
4803 return NameInfo;
4804
4805 case UnqualifiedId::IK_DeductionGuideName: {
4806 // C++ [temp.deduct.guide]p3:
4807 // The simple-template-id shall name a class template specialization.
4808 // The template-name shall be the same identifier as the template-name
4809 // of the simple-template-id.
4810 // These together intend to imply that the template-name shall name a
4811 // class template.
4812 // FIXME: template<typename T> struct X {};
4813 // template<typename T> using Y = X<T>;
4814 // Y(int) -> Y<int>;
4815 // satisfies these rules but does not name a class template.
4816 TemplateName TN = Name.TemplateName.get().get();
4817 auto *Template = TN.getAsTemplateDecl();
4818 if (!Template || !isa<ClassTemplateDecl>(Template)) {
4819 Diag(Name.StartLocation,
4820 diag::err_deduction_guide_name_not_class_template)
4821 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4822 if (Template)
4823 Diag(Template->getLocation(), diag::note_template_decl_here);
4824 return DeclarationNameInfo();
4825 }
4826
4827 NameInfo.setName(
4828 Context.DeclarationNames.getCXXDeductionGuideName(Template));
4829 NameInfo.setLoc(Name.StartLocation);
4830 return NameInfo;
4831 }
4832
4833 case UnqualifiedId::IK_OperatorFunctionId:
4834 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4835 Name.OperatorFunctionId.Operator));
4836 NameInfo.setLoc(Name.StartLocation);
4837 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4838 = Name.OperatorFunctionId.SymbolLocations[0];
4839 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4840 = Name.EndLocation.getRawEncoding();
4841 return NameInfo;
4842
4843 case UnqualifiedId::IK_LiteralOperatorId:
4844 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4845 Name.Identifier));
4846 NameInfo.setLoc(Name.StartLocation);
4847 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4848 return NameInfo;
4849
4850 case UnqualifiedId::IK_ConversionFunctionId: {
4851 TypeSourceInfo *TInfo;
4852 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4853 if (Ty.isNull())
4854 return DeclarationNameInfo();
4855 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4856 Context.getCanonicalType(Ty)));
4857 NameInfo.setLoc(Name.StartLocation);
4858 NameInfo.setNamedTypeInfo(TInfo);
4859 return NameInfo;
4860 }
4861
4862 case UnqualifiedId::IK_ConstructorName: {
4863 TypeSourceInfo *TInfo;
4864 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4865 if (Ty.isNull())
4866 return DeclarationNameInfo();
4867 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4868 Context.getCanonicalType(Ty)));
4869 NameInfo.setLoc(Name.StartLocation);
4870 NameInfo.setNamedTypeInfo(TInfo);
4871 return NameInfo;
4872 }
4873
4874 case UnqualifiedId::IK_ConstructorTemplateId: {
4875 // In well-formed code, we can only have a constructor
4876 // template-id that refers to the current context, so go there
4877 // to find the actual type being constructed.
4878 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4879 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4880 return DeclarationNameInfo();
4881
4882 // Determine the type of the class being constructed.
4883 QualType CurClassType = Context.getTypeDeclType(CurClass);
4884
4885 // FIXME: Check two things: that the template-id names the same type as
4886 // CurClassType, and that the template-id does not occur when the name
4887 // was qualified.
4888
4889 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4890 Context.getCanonicalType(CurClassType)));
4891 NameInfo.setLoc(Name.StartLocation);
4892 // FIXME: should we retrieve TypeSourceInfo?
4893 NameInfo.setNamedTypeInfo(nullptr);
4894 return NameInfo;
4895 }
4896
4897 case UnqualifiedId::IK_DestructorName: {
4898 TypeSourceInfo *TInfo;
4899 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4900 if (Ty.isNull())
4901 return DeclarationNameInfo();
4902 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4903 Context.getCanonicalType(Ty)));
4904 NameInfo.setLoc(Name.StartLocation);
4905 NameInfo.setNamedTypeInfo(TInfo);
4906 return NameInfo;
4907 }
4908
4909 case UnqualifiedId::IK_TemplateId: {
4910 TemplateName TName = Name.TemplateId->Template.get();
4911 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4912 return Context.getNameForTemplate(TName, TNameLoc);
4913 }
4914
4915 } // switch (Name.getKind())
4916
4917 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 4917)
;
4918}
4919
4920static QualType getCoreType(QualType Ty) {
4921 do {
4922 if (Ty->isPointerType() || Ty->isReferenceType())
4923 Ty = Ty->getPointeeType();
4924 else if (Ty->isArrayType())
4925 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4926 else
4927 return Ty.withoutLocalFastQualifiers();
4928 } while (true);
4929}
4930
4931/// hasSimilarParameters - Determine whether the C++ functions Declaration
4932/// and Definition have "nearly" matching parameters. This heuristic is
4933/// used to improve diagnostics in the case where an out-of-line function
4934/// definition doesn't match any declaration within the class or namespace.
4935/// Also sets Params to the list of indices to the parameters that differ
4936/// between the declaration and the definition. If hasSimilarParameters
4937/// returns true and Params is empty, then all of the parameters match.
4938static bool hasSimilarParameters(ASTContext &Context,
4939 FunctionDecl *Declaration,
4940 FunctionDecl *Definition,
4941 SmallVectorImpl<unsigned> &Params) {
4942 Params.clear();
4943 if (Declaration->param_size() != Definition->param_size())
4944 return false;
4945 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4946 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4947 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4948
4949 // The parameter types are identical
4950 if (Context.hasSameType(DefParamTy, DeclParamTy))
4951 continue;
4952
4953 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4954 QualType DefParamBaseTy = getCoreType(DefParamTy);
4955 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4956 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4957
4958 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4959 (DeclTyName && DeclTyName == DefTyName))
4960 Params.push_back(Idx);
4961 else // The two parameters aren't even close
4962 return false;
4963 }
4964
4965 return true;
4966}
4967
4968/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4969/// declarator needs to be rebuilt in the current instantiation.
4970/// Any bits of declarator which appear before the name are valid for
4971/// consideration here. That's specifically the type in the decl spec
4972/// and the base type in any member-pointer chunks.
4973static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4974 DeclarationName Name) {
4975 // The types we specifically need to rebuild are:
4976 // - typenames, typeofs, and decltypes
4977 // - types which will become injected class names
4978 // Of course, we also need to rebuild any type referencing such a
4979 // type. It's safest to just say "dependent", but we call out a
4980 // few cases here.
4981
4982 DeclSpec &DS = D.getMutableDeclSpec();
4983 switch (DS.getTypeSpecType()) {
4984 case DeclSpec::TST_typename:
4985 case DeclSpec::TST_typeofType:
4986 case DeclSpec::TST_underlyingType:
4987 case DeclSpec::TST_atomic: {
4988 // Grab the type from the parser.
4989 TypeSourceInfo *TSI = nullptr;
4990 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4991 if (T.isNull() || !T->isDependentType()) break;
4992
4993 // Make sure there's a type source info. This isn't really much
4994 // of a waste; most dependent types should have type source info
4995 // attached already.
4996 if (!TSI)
4997 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4998
4999 // Rebuild the type in the current instantiation.
5000 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5001 if (!TSI) return true;
5002
5003 // Store the new type back in the decl spec.
5004 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5005 DS.UpdateTypeRep(LocType);
5006 break;
5007 }
5008
5009 case DeclSpec::TST_decltype:
5010 case DeclSpec::TST_typeofExpr: {
5011 Expr *E = DS.getRepAsExpr();
5012 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5013 if (Result.isInvalid()) return true;
5014 DS.UpdateExprRep(Result.get());
5015 break;
5016 }
5017
5018 default:
5019 // Nothing to do for these decl specs.
5020 break;
5021 }
5022
5023 // It doesn't matter what order we do this in.
5024 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5025 DeclaratorChunk &Chunk = D.getTypeObject(I);
5026
5027 // The only type information in the declarator which can come
5028 // before the declaration name is the base type of a member
5029 // pointer.
5030 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5031 continue;
5032
5033 // Rebuild the scope specifier in-place.
5034 CXXScopeSpec &SS = Chunk.Mem.Scope();
5035 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5036 return true;
5037 }
5038
5039 return false;
5040}
5041
5042Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5043 D.setFunctionDefinitionKind(FDK_Declaration);
5044 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5045
5046 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5047 Dcl && Dcl->getDeclContext()->isFileContext())
5048 Dcl->setTopLevelDeclInObjCContainer();
5049
5050 if (getLangOpts().OpenCL)
5051 setCurrentOpenCLExtensionForDecl(Dcl);
5052
5053 return Dcl;
5054}
5055
5056/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5057/// If T is the name of a class, then each of the following shall have a
5058/// name different from T:
5059/// - every static data member of class T;
5060/// - every member function of class T
5061/// - every member of class T that is itself a type;
5062/// \returns true if the declaration name violates these rules.
5063bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5064 DeclarationNameInfo NameInfo) {
5065 DeclarationName Name = NameInfo.getName();
5066
5067 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5068 while (Record && Record->isAnonymousStructOrUnion())
5069 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5070 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5071 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5072 return true;
5073 }
5074
5075 return false;
5076}
5077
5078/// \brief Diagnose a declaration whose declarator-id has the given
5079/// nested-name-specifier.
5080///
5081/// \param SS The nested-name-specifier of the declarator-id.
5082///
5083/// \param DC The declaration context to which the nested-name-specifier
5084/// resolves.
5085///
5086/// \param Name The name of the entity being declared.
5087///
5088/// \param Loc The location of the name of the entity being declared.
5089///
5090/// \returns true if we cannot safely recover from this error, false otherwise.
5091bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5092 DeclarationName Name,
5093 SourceLocation Loc) {
5094 DeclContext *Cur = CurContext;
5095 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5096 Cur = Cur->getParent();
5097
5098 // If the user provided a superfluous scope specifier that refers back to the
5099 // class in which the entity is already declared, diagnose and ignore it.
5100 //
5101 // class X {
5102 // void X::f();
5103 // };
5104 //
5105 // Note, it was once ill-formed to give redundant qualification in all
5106 // contexts, but that rule was removed by DR482.
5107 if (Cur->Equals(DC)) {
5108 if (Cur->isRecord()) {
5109 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5110 : diag::err_member_extra_qualification)
5111 << Name << FixItHint::CreateRemoval(SS.getRange());
5112 SS.clear();
5113 } else {
5114 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5115 }
5116 return false;
5117 }
5118
5119 // Check whether the qualifying scope encloses the scope of the original
5120 // declaration.
5121 if (!Cur->Encloses(DC)) {
5122 if (Cur->isRecord())
5123 Diag(Loc, diag::err_member_qualification)
5124 << Name << SS.getRange();
5125 else if (isa<TranslationUnitDecl>(DC))
5126 Diag(Loc, diag::err_invalid_declarator_global_scope)
5127 << Name << SS.getRange();
5128 else if (isa<FunctionDecl>(Cur))
5129 Diag(Loc, diag::err_invalid_declarator_in_function)
5130 << Name << SS.getRange();
5131 else if (isa<BlockDecl>(Cur))
5132 Diag(Loc, diag::err_invalid_declarator_in_block)
5133 << Name << SS.getRange();
5134 else
5135 Diag(Loc, diag::err_invalid_declarator_scope)
5136 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5137
5138 return true;
5139 }
5140
5141 if (Cur->isRecord()) {
5142 // Cannot qualify members within a class.
5143 Diag(Loc, diag::err_member_qualification)
5144 << Name << SS.getRange();
5145 SS.clear();
5146
5147 // C++ constructors and destructors with incorrect scopes can break
5148 // our AST invariants by having the wrong underlying types. If
5149 // that's the case, then drop this declaration entirely.
5150 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5151 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5152 !Context.hasSameType(Name.getCXXNameType(),
5153 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5154 return true;
5155
5156 return false;
5157 }
5158
5159 // C++11 [dcl.meaning]p1:
5160 // [...] "The nested-name-specifier of the qualified declarator-id shall
5161 // not begin with a decltype-specifer"
5162 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5163 while (SpecLoc.getPrefix())
5164 SpecLoc = SpecLoc.getPrefix();
5165 if (dyn_cast_or_null<DecltypeType>(
5166 SpecLoc.getNestedNameSpecifier()->getAsType()))
5167 Diag(Loc, diag::err_decltype_in_declarator)
5168 << SpecLoc.getTypeLoc().getSourceRange();
5169
5170 return false;
5171}
5172
5173NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5174 MultiTemplateParamsArg TemplateParamLists) {
5175 // TODO: consider using NameInfo for diagnostic.
5176 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5177 DeclarationName Name = NameInfo.getName();
5178
5179 // All of these full declarators require an identifier. If it doesn't have
5180 // one, the ParsedFreeStandingDeclSpec action should be used.
5181 if (D.isDecompositionDeclarator()) {
5182 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5183 } else if (!Name) {
5184 if (!D.isInvalidType()) // Reject this if we think it is valid.
5185 Diag(D.getDeclSpec().getLocStart(),
5186 diag::err_declarator_need_ident)
5187 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5188 return nullptr;
5189 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5190 return nullptr;
5191
5192 // The scope passed in may not be a decl scope. Zip up the scope tree until
5193 // we find one that is.
5194 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5195 (S->getFlags() & Scope::TemplateParamScope) != 0)
5196 S = S->getParent();
5197
5198 DeclContext *DC = CurContext;
5199 if (D.getCXXScopeSpec().isInvalid())
5200 D.setInvalidType();
5201 else if (D.getCXXScopeSpec().isSet()) {
5202 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5203 UPPC_DeclarationQualifier))
5204 return nullptr;
5205
5206 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5207 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5208 if (!DC || isa<EnumDecl>(DC)) {
5209 // If we could not compute the declaration context, it's because the
5210 // declaration context is dependent but does not refer to a class,
5211 // class template, or class template partial specialization. Complain
5212 // and return early, to avoid the coming semantic disaster.
5213 Diag(D.getIdentifierLoc(),
5214 diag::err_template_qualified_declarator_no_match)
5215 << D.getCXXScopeSpec().getScopeRep()
5216 << D.getCXXScopeSpec().getRange();
5217 return nullptr;
5218 }
5219 bool IsDependentContext = DC->isDependentContext();
5220
5221 if (!IsDependentContext &&
5222 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5223 return nullptr;
5224
5225 // If a class is incomplete, do not parse entities inside it.
5226 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5227 Diag(D.getIdentifierLoc(),
5228 diag::err_member_def_undefined_record)
5229 << Name << DC << D.getCXXScopeSpec().getRange();
5230 return nullptr;
5231 }
5232 if (!D.getDeclSpec().isFriendSpecified()) {
5233 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5234 Name, D.getIdentifierLoc())) {
5235 if (DC->isRecord())
5236 return nullptr;
5237
5238 D.setInvalidType();
5239 }
5240 }
5241
5242 // Check whether we need to rebuild the type of the given
5243 // declaration in the current instantiation.
5244 if (EnteringContext && IsDependentContext &&
5245 TemplateParamLists.size() != 0) {
5246 ContextRAII SavedContext(*this, DC);
5247 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5248 D.setInvalidType();
5249 }
5250 }
5251
5252 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5253 QualType R = TInfo->getType();
5254
5255 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5256 // If this is a typedef, we'll end up spewing multiple diagnostics.
5257 // Just return early; it's safer. If this is a function, let the
5258 // "constructor cannot have a return type" diagnostic handle it.
5259 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5260 return nullptr;
5261
5262 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5263 UPPC_DeclarationType))
5264 D.setInvalidType();
5265
5266 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5267 ForRedeclaration);
5268
5269 // See if this is a redefinition of a variable in the same scope.
5270 if (!D.getCXXScopeSpec().isSet()) {
5271 bool IsLinkageLookup = false;
5272 bool CreateBuiltins = false;
5273
5274 // If the declaration we're planning to build will be a function
5275 // or object with linkage, then look for another declaration with
5276 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5277 //
5278 // If the declaration we're planning to build will be declared with
5279 // external linkage in the translation unit, create any builtin with
5280 // the same name.
5281 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5282 /* Do nothing*/;
5283 else if (CurContext->isFunctionOrMethod() &&
5284 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5285 R->isFunctionType())) {
5286 IsLinkageLookup = true;
5287 CreateBuiltins =
5288 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5289 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5290 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5291 CreateBuiltins = true;
5292
5293 if (IsLinkageLookup)
5294 Previous.clear(LookupRedeclarationWithLinkage);
5295
5296 LookupName(Previous, S, CreateBuiltins);
5297 } else { // Something like "int foo::x;"
5298 LookupQualifiedName(Previous, DC);
5299
5300 // C++ [dcl.meaning]p1:
5301 // When the declarator-id is qualified, the declaration shall refer to a
5302 // previously declared member of the class or namespace to which the
5303 // qualifier refers (or, in the case of a namespace, of an element of the
5304 // inline namespace set of that namespace (7.3.1)) or to a specialization
5305 // thereof; [...]
5306 //
5307 // Note that we already checked the context above, and that we do not have
5308 // enough information to make sure that Previous contains the declaration
5309 // we want to match. For example, given:
5310 //
5311 // class X {
5312 // void f();
5313 // void f(float);
5314 // };
5315 //
5316 // void X::f(int) { } // ill-formed
5317 //
5318 // In this case, Previous will point to the overload set
5319 // containing the two f's declared in X, but neither of them
5320 // matches.
5321
5322 // C++ [dcl.meaning]p1:
5323 // [...] the member shall not merely have been introduced by a
5324 // using-declaration in the scope of the class or namespace nominated by
5325 // the nested-name-specifier of the declarator-id.
5326 RemoveUsingDecls(Previous);
5327 }
5328
5329 if (Previous.isSingleResult() &&
5330 Previous.getFoundDecl()->isTemplateParameter()) {
5331 // Maybe we will complain about the shadowed template parameter.
5332 if (!D.isInvalidType())
5333 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5334 Previous.getFoundDecl());
5335
5336 // Just pretend that we didn't see the previous declaration.
5337 Previous.clear();
5338 }
5339
5340 // In C++, the previous declaration we find might be a tag type
5341 // (class or enum). In this case, the new declaration will hide the
5342 // tag type. Note that this does does not apply if we're declaring a
5343 // typedef (C++ [dcl.typedef]p4).
5344 if (Previous.isSingleTagDecl() &&
5345 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5346 Previous.clear();
5347
5348 // Check that there are no default arguments other than in the parameters
5349 // of a function declaration (C++ only).
5350 if (getLangOpts().CPlusPlus)
5351 CheckExtraCXXDefaultArguments(D);
5352
5353 if (D.getDeclSpec().isConceptSpecified()) {
5354 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5355 // applied only to the definition of a function template or variable
5356 // template, declared in namespace scope
5357 if (!TemplateParamLists.size()) {
5358 Diag(D.getDeclSpec().getConceptSpecLoc(),
5359 diag:: err_concept_wrong_decl_kind);
5360 return nullptr;
5361 }
5362
5363 if (!DC->getRedeclContext()->isFileContext()) {
5364 Diag(D.getIdentifierLoc(),
5365 diag::err_concept_decls_may_only_appear_in_namespace_scope);
5366 return nullptr;
5367 }
5368 }
5369
5370 NamedDecl *New;
5371
5372 bool AddToScope = true;
5373 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5374 if (TemplateParamLists.size()) {
5375 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5376 return nullptr;
5377 }
5378
5379 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5380 } else if (R->isFunctionType()) {
5381 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5382 TemplateParamLists,
5383 AddToScope);
5384 } else {
5385 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5386 AddToScope);
5387 }
5388
5389 if (!New)
5390 return nullptr;
5391
5392 // If this has an identifier and is not a function template specialization,
5393 // add it to the scope stack.
5394 if (New->getDeclName() && AddToScope) {
5395 // Only make a locally-scoped extern declaration visible if it is the first
5396 // declaration of this entity. Qualified lookup for such an entity should
5397 // only find this declaration if there is no visible declaration of it.
5398 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5399 PushOnScopeChains(New, S, AddToContext);
5400 if (!AddToContext)
5401 CurContext->addHiddenDecl(New);
5402 }
5403
5404 if (isInOpenMPDeclareTargetContext())
5405 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5406
5407 return New;
5408}
5409
5410/// Helper method to turn variable array types into constant array
5411/// types in certain situations which would otherwise be errors (for
5412/// GCC compatibility).
5413static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5414 ASTContext &Context,
5415 bool &SizeIsNegative,
5416 llvm::APSInt &Oversized) {
5417 // This method tries to turn a variable array into a constant
5418 // array even when the size isn't an ICE. This is necessary
5419 // for compatibility with code that depends on gcc's buggy
5420 // constant expression folding, like struct {char x[(int)(char*)2];}
5421 SizeIsNegative = false;
5422 Oversized = 0;
5423
5424 if (T->isDependentType())
5425 return QualType();
5426
5427 QualifierCollector Qs;
5428 const Type *Ty = Qs.strip(T);
5429
5430 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5431 QualType Pointee = PTy->getPointeeType();
5432 QualType FixedType =
5433 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5434 Oversized);
5435 if (FixedType.isNull()) return FixedType;
5436 FixedType = Context.getPointerType(FixedType);
5437 return Qs.apply(Context, FixedType);
5438 }
5439 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5440 QualType Inner = PTy->getInnerType();
5441 QualType FixedType =
5442 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5443 Oversized);
5444 if (FixedType.isNull()) return FixedType;
5445 FixedType = Context.getParenType(FixedType);
5446 return Qs.apply(Context, FixedType);
5447 }
5448
5449 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5450 if (!VLATy)
5451 return QualType();
5452 // FIXME: We should probably handle this case
5453 if (VLATy->getElementType()->isVariablyModifiedType())
5454 return QualType();
5455
5456 llvm::APSInt Res;
5457 if (!VLATy->getSizeExpr() ||
5458 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5459 return QualType();
5460
5461 // Check whether the array size is negative.
5462 if (Res.isSigned() && Res.isNegative()) {
5463 SizeIsNegative = true;
5464 return QualType();
5465 }
5466
5467 // Check whether the array is too large to be addressed.
5468 unsigned ActiveSizeBits
5469 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5470 Res);
5471 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5472 Oversized = Res;
5473 return QualType();
5474 }
5475
5476 return Context.getConstantArrayType(VLATy->getElementType(),
5477 Res, ArrayType::Normal, 0);
5478}
5479
5480static void
5481FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5482 SrcTL = SrcTL.getUnqualifiedLoc();
5483 DstTL = DstTL.getUnqualifiedLoc();
5484 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5485 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5486 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5487 DstPTL.getPointeeLoc());
5488 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5489 return;
5490 }
5491 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5492 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5493 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5494 DstPTL.getInnerLoc());
5495 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5496 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5497 return;
5498 }
5499 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5500 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5501 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5502 TypeLoc DstElemTL = DstATL.getElementLoc();
5503 DstElemTL.initializeFullCopy(SrcElemTL);
5504 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5505 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5506 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5507}
5508
5509/// Helper method to turn variable array types into constant array
5510/// types in certain situations which would otherwise be errors (for
5511/// GCC compatibility).
5512static TypeSourceInfo*
5513TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5514 ASTContext &Context,
5515 bool &SizeIsNegative,
5516 llvm::APSInt &Oversized) {
5517 QualType FixedTy
5518 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5519 SizeIsNegative, Oversized);
5520 if (FixedTy.isNull())
5521 return nullptr;
5522 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5523 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5524 FixedTInfo->getTypeLoc());
5525 return FixedTInfo;
5526}
5527
5528/// \brief Register the given locally-scoped extern "C" declaration so
5529/// that it can be found later for redeclarations. We include any extern "C"
5530/// declaration that is not visible in the translation unit here, not just
5531/// function-scope declarations.
5532void
5533Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5534 if (!getLangOpts().CPlusPlus &&
5535 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5536 // Don't need to track declarations in the TU in C.
5537 return;
5538
5539 // Note that we have a locally-scoped external with this name.
5540 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5541}
5542
5543NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5544 // FIXME: We can have multiple results via __attribute__((overloadable)).
5545 auto Result = Context.getExternCContextDecl()->lookup(Name);
5546 return Result.empty() ? nullptr : *Result.begin();
5547}
5548
5549/// \brief Diagnose function specifiers on a declaration of an identifier that
5550/// does not identify a function.
5551void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5552 // FIXME: We should probably indicate the identifier in question to avoid
5553 // confusion for constructs like "virtual int a(), b;"
5554 if (DS.isVirtualSpecified())
5555 Diag(DS.getVirtualSpecLoc(),
5556 diag::err_virtual_non_function);
5557
5558 if (DS.isExplicitSpecified())
5559 Diag(DS.getExplicitSpecLoc(),
5560 diag::err_explicit_non_function);
5561
5562 if (DS.isNoreturnSpecified())
5563 Diag(DS.getNoreturnSpecLoc(),
5564 diag::err_noreturn_non_function);
5565}
5566
5567NamedDecl*
5568Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5569 TypeSourceInfo *TInfo, LookupResult &Previous) {
5570 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5571 if (D.getCXXScopeSpec().isSet()) {
5572 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5573 << D.getCXXScopeSpec().getRange();
5574 D.setInvalidType();
5575 // Pretend we didn't see the scope specifier.
5576 DC = CurContext;
5577 Previous.clear();
5578 }
5579
5580 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5581
5582 if (D.getDeclSpec().isInlineSpecified())
5583 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5584 << getLangOpts().CPlusPlus1z;
5585 if (D.getDeclSpec().isConstexprSpecified())
5586 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5587 << 1;
5588 if (D.getDeclSpec().isConceptSpecified())
5589 Diag(D.getDeclSpec().getConceptSpecLoc(),
5590 diag::err_concept_wrong_decl_kind);
5591
5592 if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5593 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName)
5594 Diag(D.getName().StartLocation,
5595 diag::err_deduction_guide_invalid_specifier)
5596 << "typedef";
5597 else
5598 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5599 << D.getName().getSourceRange();
5600 return nullptr;
5601 }
5602
5603 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5604 if (!NewTD) return nullptr;
5605
5606 // Handle attributes prior to checking for duplicates in MergeVarDecl
5607 ProcessDeclAttributes(S, NewTD, D);
5608
5609 CheckTypedefForVariablyModifiedType(S, NewTD);
5610
5611 bool Redeclaration = D.isRedeclaration();
5612 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5613 D.setRedeclaration(Redeclaration);
5614 return ND;
5615}
5616
5617void
5618Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5619 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5620 // then it shall have block scope.
5621 // Note that variably modified types must be fixed before merging the decl so
5622 // that redeclarations will match.
5623 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5624 QualType T = TInfo->getType();
5625 if (T->isVariablyModifiedType()) {
5626 getCurFunction()->setHasBranchProtectedScope();
5627
5628 if (S->getFnParent() == nullptr) {
5629 bool SizeIsNegative;
5630 llvm::APSInt Oversized;
5631 TypeSourceInfo *FixedTInfo =
5632 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5633 SizeIsNegative,
5634 Oversized);
5635 if (FixedTInfo) {
5636 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5637 NewTD->setTypeSourceInfo(FixedTInfo);
5638 } else {
5639 if (SizeIsNegative)
5640 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5641 else if (T->isVariableArrayType())
5642 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5643 else if (Oversized.getBoolValue())
5644 Diag(NewTD->getLocation(), diag::err_array_too_large)
5645 << Oversized.toString(10);
5646 else
5647 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5648 NewTD->setInvalidDecl();
5649 }
5650 }
5651 }
5652}
5653
5654/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5655/// declares a typedef-name, either using the 'typedef' type specifier or via
5656/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5657NamedDecl*
5658Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5659 LookupResult &Previous, bool &Redeclaration) {
5660
5661 // Find the shadowed declaration before filtering for scope.
5662 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5663
5664 // Merge the decl with the existing one if appropriate. If the decl is
5665 // in an outer scope, it isn't the same thing.
5666 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5667 /*AllowInlineNamespace*/false);
5668 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5669 if (!Previous.empty()) {
5670 Redeclaration = true;
5671 MergeTypedefNameDecl(S, NewTD, Previous);
5672 }
5673
5674 if (ShadowedDecl && !Redeclaration)
5675 CheckShadow(NewTD, ShadowedDecl, Previous);
5676
5677 // If this is the C FILE type, notify the AST context.
5678 if (IdentifierInfo *II = NewTD->getIdentifier())
5679 if (!NewTD->isInvalidDecl() &&
5680 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5681 if (II->isStr("FILE"))
5682 Context.setFILEDecl(NewTD);
5683 else if (II->isStr("jmp_buf"))
5684 Context.setjmp_bufDecl(NewTD);
5685 else if (II->isStr("sigjmp_buf"))
5686 Context.setsigjmp_bufDecl(NewTD);
5687 else if (II->isStr("ucontext_t"))
5688 Context.setucontext_tDecl(NewTD);
5689 }
5690
5691 return NewTD;
5692}
5693
5694/// \brief Determines whether the given declaration is an out-of-scope
5695/// previous declaration.
5696///
5697/// This routine should be invoked when name lookup has found a
5698/// previous declaration (PrevDecl) that is not in the scope where a
5699/// new declaration by the same name is being introduced. If the new
5700/// declaration occurs in a local scope, previous declarations with
5701/// linkage may still be considered previous declarations (C99
5702/// 6.2.2p4-5, C++ [basic.link]p6).
5703///
5704/// \param PrevDecl the previous declaration found by name
5705/// lookup
5706///
5707/// \param DC the context in which the new declaration is being
5708/// declared.
5709///
5710/// \returns true if PrevDecl is an out-of-scope previous declaration
5711/// for a new delcaration with the same name.
5712static bool
5713isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5714 ASTContext &Context) {
5715 if (!PrevDecl)
5716 return false;
5717
5718 if (!PrevDecl->hasLinkage())
5719 return false;
5720
5721 if (Context.getLangOpts().CPlusPlus) {
5722 // C++ [basic.link]p6:
5723 // If there is a visible declaration of an entity with linkage
5724 // having the same name and type, ignoring entities declared
5725 // outside the innermost enclosing namespace scope, the block
5726 // scope declaration declares that same entity and receives the
5727 // linkage of the previous declaration.
5728 DeclContext *OuterContext = DC->getRedeclContext();
5729 if (!OuterContext->isFunctionOrMethod())
5730 // This rule only applies to block-scope declarations.
5731 return false;
5732
5733 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5734 if (PrevOuterContext->isRecord())
5735 // We found a member function: ignore it.
5736 return false;
5737
5738 // Find the innermost enclosing namespace for the new and
5739 // previous declarations.
5740 OuterContext = OuterContext->getEnclosingNamespaceContext();
5741 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5742
5743 // The previous declaration is in a different namespace, so it
5744 // isn't the same function.
5745 if (!OuterContext->Equals(PrevOuterContext))
5746 return false;
5747 }
5748
5749 return true;
5750}
5751
5752static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5753 CXXScopeSpec &SS = D.getCXXScopeSpec();
5754 if (!SS.isSet()) return;
5755 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5756}
5757
5758bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5759 QualType type = decl->getType();
5760 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5761 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5762 // Various kinds of declaration aren't allowed to be __autoreleasing.
5763 unsigned kind = -1U;
5764 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5765 if (var->hasAttr<BlocksAttr>())
5766 kind = 0; // __block
5767 else if (!var->hasLocalStorage())
5768 kind = 1; // global
5769 } else if (isa<ObjCIvarDecl>(decl)) {
5770 kind = 3; // ivar
5771 } else if (isa<FieldDecl>(decl)) {
5772 kind = 2; // field
5773 }
5774
5775 if (kind != -1U) {
5776 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5777 << kind;
5778 }
5779 } else if (lifetime == Qualifiers::OCL_None) {
5780 // Try to infer lifetime.
5781 if (!type->isObjCLifetimeType())
5782 return false;
5783
5784 lifetime = type->getObjCARCImplicitLifetime();
5785 type = Context.getLifetimeQualifiedType(type, lifetime);
5786 decl->setType(type);
5787 }
5788
5789 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5790 // Thread-local variables cannot have lifetime.
5791 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5792 var->getTLSKind()) {
5793 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5794 << var->getType();
5795 return true;
5796 }
5797 }
5798
5799 return false;
5800}
5801
5802static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5803 // Ensure that an auto decl is deduced otherwise the checks below might cache
5804 // the wrong linkage.
5805 assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast
<void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 5805, __PRETTY_FUNCTION__))
;
5806
5807 // 'weak' only applies to declarations with external linkage.
5808 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5809 if (!ND.isExternallyVisible()) {
5810 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5811 ND.dropAttr<WeakAttr>();
5812 }
5813 }
5814 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5815 if (ND.isExternallyVisible()) {
5816 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5817 ND.dropAttr<WeakRefAttr>();
5818 ND.dropAttr<AliasAttr>();
5819 }
5820 }
5821
5822 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5823 if (VD->hasInit()) {
5824 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5825 assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 5826, __PRETTY_FUNCTION__))
5826 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible
() && "Broken AliasAttr handled late!") ? static_cast
<void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 5826, __PRETTY_FUNCTION__))
;
5827 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5828 VD->dropAttr<AliasAttr>();
5829 }
5830 }
5831 }
5832
5833 // 'selectany' only applies to externally visible variable declarations.
5834 // It does not apply to functions.
5835 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5836 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5837 S.Diag(Attr->getLocation(),
5838 diag::err_attribute_selectany_non_extern_data);
5839 ND.dropAttr<SelectAnyAttr>();
5840 }
5841 }
5842
5843 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5844 // dll attributes require external linkage. Static locals may have external
5845 // linkage but still cannot be explicitly imported or exported.
5846 auto *VD = dyn_cast<VarDecl>(&ND);
5847 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5848 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5849 << &ND << Attr;
5850 ND.setInvalidDecl();
5851 }
5852 }
5853
5854 // Virtual functions cannot be marked as 'notail'.
5855 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5856 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5857 if (MD->isVirtual()) {
5858 S.Diag(ND.getLocation(),
5859 diag::err_invalid_attribute_on_virtual_function)
5860 << Attr;
5861 ND.dropAttr<NotTailCalledAttr>();
5862 }
5863}
5864
5865static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5866 NamedDecl *NewDecl,
5867 bool IsSpecialization,
5868 bool IsDefinition) {
5869 if (OldDecl->isInvalidDecl())
5870 return;
5871
5872 bool IsTemplate = false;
5873 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5874 OldDecl = OldTD->getTemplatedDecl();
5875 IsTemplate = true;
5876 if (!IsSpecialization)
5877 IsDefinition = false;
5878 }
5879 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
5880 NewDecl = NewTD->getTemplatedDecl();
5881 IsTemplate = true;
5882 }
5883
5884 if (!OldDecl || !NewDecl)
5885 return;
5886
5887 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5888 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5889 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5890 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5891
5892 // dllimport and dllexport are inheritable attributes so we have to exclude
5893 // inherited attribute instances.
5894 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5895 (NewExportAttr && !NewExportAttr->isInherited());
5896
5897 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5898 // the only exception being explicit specializations.
5899 // Implicitly generated declarations are also excluded for now because there
5900 // is no other way to switch these to use dllimport or dllexport.
5901 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5902
5903 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5904 // Allow with a warning for free functions and global variables.
5905 bool JustWarn = false;
5906 if (!OldDecl->isCXXClassMember()) {
5907 auto *VD = dyn_cast<VarDecl>(OldDecl);
5908 if (VD && !VD->getDescribedVarTemplate())
5909 JustWarn = true;
5910 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5911 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5912 JustWarn = true;
5913 }
5914
5915 // We cannot change a declaration that's been used because IR has already
5916 // been emitted. Dllimported functions will still work though (modulo
5917 // address equality) as they can use the thunk.
5918 if (OldDecl->isUsed())
5919 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5920 JustWarn = false;
5921
5922 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5923 : diag::err_attribute_dll_redeclaration;
5924 S.Diag(NewDecl->getLocation(), DiagID)
5925 << NewDecl
5926 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5927 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5928 if (!JustWarn) {
5929 NewDecl->setInvalidDecl();
5930 return;
5931 }
5932 }
5933
5934 // A redeclaration is not allowed to drop a dllimport attribute, the only
5935 // exceptions being inline function definitions (except for function
5936 // templates), local extern declarations, qualified friend declarations or
5937 // special MSVC extension: in the last case, the declaration is treated as if
5938 // it were marked dllexport.
5939 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5940 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5941 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5942 // Ignore static data because out-of-line definitions are diagnosed
5943 // separately.
5944 IsStaticDataMember = VD->isStaticDataMember();
5945 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5946 VarDecl::DeclarationOnly;
5947 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5948 IsInline = FD->isInlined();
5949 IsQualifiedFriend = FD->getQualifier() &&
5950 FD->getFriendObjectKind() == Decl::FOK_Declared;
5951 }
5952
5953 if (OldImportAttr && !HasNewAttr &&
5954 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
5955 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5956 if (IsMicrosoft && IsDefinition) {
5957 S.Diag(NewDecl->getLocation(),
5958 diag::warn_redeclaration_without_import_attribute)
5959 << NewDecl;
5960 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5961 NewDecl->dropAttr<DLLImportAttr>();
5962 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5963 NewImportAttr->getRange(), S.Context,
5964 NewImportAttr->getSpellingListIndex()));
5965 } else {
5966 S.Diag(NewDecl->getLocation(),
5967 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5968 << NewDecl << OldImportAttr;
5969 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5970 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5971 OldDecl->dropAttr<DLLImportAttr>();
5972 NewDecl->dropAttr<DLLImportAttr>();
5973 }
5974 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5975 // In MinGW, seeing a function declared inline drops the dllimport attribute.
5976 OldDecl->dropAttr<DLLImportAttr>();
5977 NewDecl->dropAttr<DLLImportAttr>();
5978 S.Diag(NewDecl->getLocation(),
5979 diag::warn_dllimport_dropped_from_inline_function)
5980 << NewDecl << OldImportAttr;
5981 }
5982}
5983
5984/// Given that we are within the definition of the given function,
5985/// will that definition behave like C99's 'inline', where the
5986/// definition is discarded except for optimization purposes?
5987static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5988 // Try to avoid calling GetGVALinkageForFunction.
5989
5990 // All cases of this require the 'inline' keyword.
5991 if (!FD->isInlined()) return false;
5992
5993 // This is only possible in C++ with the gnu_inline attribute.
5994 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5995 return false;
5996
5997 // Okay, go ahead and call the relatively-more-expensive function.
5998 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5999}
6000
6001/// Determine whether a variable is extern "C" prior to attaching
6002/// an initializer. We can't just call isExternC() here, because that
6003/// will also compute and cache whether the declaration is externally
6004/// visible, which might change when we attach the initializer.
6005///
6006/// This can only be used if the declaration is known to not be a
6007/// redeclaration of an internal linkage declaration.
6008///
6009/// For instance:
6010///
6011/// auto x = []{};
6012///
6013/// Attaching the initializer here makes this declaration not externally
6014/// visible, because its type has internal linkage.
6015///
6016/// FIXME: This is a hack.
6017template<typename T>
6018static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6019 if (S.getLangOpts().CPlusPlus) {
6020 // In C++, the overloadable attribute negates the effects of extern "C".
6021 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6022 return false;
6023
6024 // So do CUDA's host/device attributes.
6025 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6026 D->template hasAttr<CUDAHostAttr>()))
6027 return false;
6028 }
6029 return D->isExternC();
6030}
6031
6032static bool shouldConsiderLinkage(const VarDecl *VD) {
6033 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6034 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6035 return VD->hasExternalStorage();
6036 if (DC->isFileContext())
6037 return true;
6038 if (DC->isRecord())
6039 return false;
6040 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6040)
;
6041}
6042
6043static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6044 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6045 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6046 isa<OMPDeclareReductionDecl>(DC))
6047 return true;
6048 if (DC->isRecord())
6049 return false;
6050 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6050)
;
6051}
6052
6053static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6054 AttributeList::Kind Kind) {
6055 for (const AttributeList *L = AttrList; L; L = L->getNext())
6056 if (L->getKind() == Kind)
6057 return true;
6058 return false;
6059}
6060
6061static bool hasParsedAttr(Scope *S, const Declarator &PD,
6062 AttributeList::Kind Kind) {
6063 // Check decl attributes on the DeclSpec.
6064 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6065 return true;
6066
6067 // Walk the declarator structure, checking decl attributes that were in a type
6068 // position to the decl itself.
6069 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6070 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6071 return true;
6072 }
6073
6074 // Finally, check attributes on the decl itself.
6075 return hasParsedAttr(S, PD.getAttributes(), Kind);
6076}
6077
6078/// Adjust the \c DeclContext for a function or variable that might be a
6079/// function-local external declaration.
6080bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6081 if (!DC->isFunctionOrMethod())
6082 return false;
6083
6084 // If this is a local extern function or variable declared within a function
6085 // template, don't add it into the enclosing namespace scope until it is
6086 // instantiated; it might have a dependent type right now.
6087 if (DC->isDependentContext())
6088 return true;
6089
6090 // C++11 [basic.link]p7:
6091 // When a block scope declaration of an entity with linkage is not found to
6092 // refer to some other declaration, then that entity is a member of the
6093 // innermost enclosing namespace.
6094 //
6095 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6096 // semantically-enclosing namespace, not a lexically-enclosing one.
6097 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6098 DC = DC->getParent();
6099 return true;
6100}
6101
6102/// \brief Returns true if given declaration has external C language linkage.
6103static bool isDeclExternC(const Decl *D) {
6104 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6105 return FD->isExternC();
6106 if (const auto *VD = dyn_cast<VarDecl>(D))
6107 return VD->isExternC();
6108
6109 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6109)
;
6110}
6111
6112NamedDecl *Sema::ActOnVariableDeclarator(
6113 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6114 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6115 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6116 QualType R = TInfo->getType();
6117 DeclarationName Name = GetNameForDeclarator(D).getName();
6118
6119 IdentifierInfo *II = Name.getAsIdentifierInfo();
6120
6121 if (D.isDecompositionDeclarator()) {
6122 AddToScope = false;
6123 // Take the name of the first declarator as our name for diagnostic
6124 // purposes.
6125 auto &Decomp = D.getDecompositionDeclarator();
6126 if (!Decomp.bindings().empty()) {
6127 II = Decomp.bindings()[0].Name;
6128 Name = II;
6129 }
6130 } else if (!II) {
6131 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6132 return nullptr;
6133 }
6134
6135 if (getLangOpts().OpenCL) {
6136 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6137 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6138 // argument.
6139 if (R->isImageType() || R->isPipeType()) {
6140 Diag(D.getIdentifierLoc(),
6141 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6142 << R;
6143 D.setInvalidType();
6144 return nullptr;
6145 }
6146
6147 // OpenCL v1.2 s6.9.r:
6148 // The event type cannot be used to declare a program scope variable.
6149 // OpenCL v2.0 s6.9.q:
6150 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6151 if (NULL__null == S->getParent()) {
6152 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6153 Diag(D.getIdentifierLoc(),
6154 diag::err_invalid_type_for_program_scope_var) << R;
6155 D.setInvalidType();
6156 return nullptr;
6157 }
6158 }
6159
6160 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6161 QualType NR = R;
6162 while (NR->isPointerType()) {
6163 if (NR->isFunctionPointerType()) {
6164 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6165 D.setInvalidType();
6166 break;
6167 }
6168 NR = NR->getPointeeType();
6169 }
6170
6171 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6172 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6173 // half array type (unless the cl_khr_fp16 extension is enabled).
6174 if (Context.getBaseElementType(R)->isHalfType()) {
6175 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6176 D.setInvalidType();
6177 }
6178 }
6179
6180 if (R->isSamplerT()) {
6181 // OpenCL v1.2 s6.9.b p4:
6182 // The sampler type cannot be used with the __local and __global address
6183 // space qualifiers.
6184 if (R.getAddressSpace() == LangAS::opencl_local ||
6185 R.getAddressSpace() == LangAS::opencl_global) {
6186 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6187 }
6188
6189 // OpenCL v1.2 s6.12.14.1:
6190 // A global sampler must be declared with either the constant address
6191 // space qualifier or with the const qualifier.
6192 if (DC->isTranslationUnit() &&
6193 !(R.getAddressSpace() == LangAS::opencl_constant ||
6194 R.isConstQualified())) {
6195 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6196 D.setInvalidType();
6197 }
6198 }
6199
6200 // OpenCL v1.2 s6.9.r:
6201 // The event type cannot be used with the __local, __constant and __global
6202 // address space qualifiers.
6203 if (R->isEventT()) {
6204 if (R.getAddressSpace()) {
6205 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6206 D.setInvalidType();
6207 }
6208 }
6209 }
6210
6211 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6212 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6213
6214 // dllimport globals without explicit storage class are treated as extern. We
6215 // have to change the storage class this early to get the right DeclContext.
6216 if (SC == SC_None && !DC->isRecord() &&
6217 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6218 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6219 SC = SC_Extern;
6220
6221 DeclContext *OriginalDC = DC;
6222 bool IsLocalExternDecl = SC == SC_Extern &&
6223 adjustContextForLocalExternDecl(DC);
6224
6225 if (SCSpec == DeclSpec::SCS_mutable) {
6226 // mutable can only appear on non-static class members, so it's always
6227 // an error here
6228 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6229 D.setInvalidType();
6230 SC = SC_None;
6231 }
6232
6233 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6234 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6235 D.getDeclSpec().getStorageClassSpecLoc())) {
6236 // In C++11, the 'register' storage class specifier is deprecated.
6237 // Suppress the warning in system macros, it's used in macros in some
6238 // popular C system headers, such as in glibc's htonl() macro.
6239 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6240 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6241 : diag::warn_deprecated_register)
6242 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6243 }
6244
6245 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6246
6247 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6248 // C99 6.9p2: The storage-class specifiers auto and register shall not
6249 // appear in the declaration specifiers in an external declaration.
6250 // Global Register+Asm is a GNU extension we support.
6251 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6252 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6253 D.setInvalidType();
6254 }
6255 }
6256
6257 bool IsMemberSpecialization = false;
6258 bool IsVariableTemplateSpecialization = false;
6259 bool IsPartialSpecialization = false;
6260 bool IsVariableTemplate = false;
6261 VarDecl *NewVD = nullptr;
6262 VarTemplateDecl *NewTemplate = nullptr;
6263 TemplateParameterList *TemplateParams = nullptr;
6264 if (!getLangOpts().CPlusPlus) {
6265 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6266 D.getIdentifierLoc(), II,
6267 R, TInfo, SC);
6268
6269 if (R->getContainedDeducedType())
6270 ParsingInitForAutoVars.insert(NewVD);
6271
6272 if (D.isInvalidType())
6273 NewVD->setInvalidDecl();
6274 } else {
6275 bool Invalid = false;
6276
6277 if (DC->isRecord() && !CurContext->isRecord()) {
6278 // This is an out-of-line definition of a static data member.
6279 switch (SC) {
6280 case SC_None:
6281 break;
6282 case SC_Static:
6283 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6284 diag::err_static_out_of_line)
6285 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6286 break;
6287 case SC_Auto:
6288 case SC_Register:
6289 case SC_Extern:
6290 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6291 // to names of variables declared in a block or to function parameters.
6292 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6293 // of class members
6294
6295 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6296 diag::err_storage_class_for_static_member)
6297 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6298 break;
6299 case SC_PrivateExtern:
6300 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6300)
;
6301 }
6302 }
6303
6304 if (SC == SC_Static && CurContext->isRecord()) {
6305 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6306 if (RD->isLocalClass())
6307 Diag(D.getIdentifierLoc(),
6308 diag::err_static_data_member_not_allowed_in_local_class)
6309 << Name << RD->getDeclName();
6310
6311 // C++98 [class.union]p1: If a union contains a static data member,
6312 // the program is ill-formed. C++11 drops this restriction.
6313 if (RD->isUnion())
6314 Diag(D.getIdentifierLoc(),
6315 getLangOpts().CPlusPlus11
6316 ? diag::warn_cxx98_compat_static_data_member_in_union
6317 : diag::ext_static_data_member_in_union) << Name;
6318 // We conservatively disallow static data members in anonymous structs.
6319 else if (!RD->getDeclName())
6320 Diag(D.getIdentifierLoc(),
6321 diag::err_static_data_member_not_allowed_in_anon_struct)
6322 << Name << RD->isUnion();
6323 }
6324 }
6325
6326 // Match up the template parameter lists with the scope specifier, then
6327 // determine whether we have a template or a template specialization.
6328 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6329 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6330 D.getCXXScopeSpec(),
6331 D.getName().getKind() == UnqualifiedId::IK_TemplateId
6332 ? D.getName().TemplateId
6333 : nullptr,
6334 TemplateParamLists,
6335 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6336
6337 if (TemplateParams) {
6338 if (!TemplateParams->size() &&
6339 D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6340 // There is an extraneous 'template<>' for this variable. Complain
6341 // about it, but allow the declaration of the variable.
6342 Diag(TemplateParams->getTemplateLoc(),
6343 diag::err_template_variable_noparams)
6344 << II
6345 << SourceRange(TemplateParams->getTemplateLoc(),
6346 TemplateParams->getRAngleLoc());
6347 TemplateParams = nullptr;
6348 } else {
6349 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6350 // This is an explicit specialization or a partial specialization.
6351 // FIXME: Check that we can declare a specialization here.
6352 IsVariableTemplateSpecialization = true;
6353 IsPartialSpecialization = TemplateParams->size() > 0;
6354 } else { // if (TemplateParams->size() > 0)
6355 // This is a template declaration.
6356 IsVariableTemplate = true;
6357
6358 // Check that we can declare a template here.
6359 if (CheckTemplateDeclScope(S, TemplateParams))
6360 return nullptr;
6361
6362 // Only C++1y supports variable templates (N3651).
6363 Diag(D.getIdentifierLoc(),
6364 getLangOpts().CPlusPlus14
6365 ? diag::warn_cxx11_compat_variable_template
6366 : diag::ext_variable_template);
6367 }
6368 }
6369 } else {
6370 assert((((Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6372, __PRETTY_FUNCTION__))
6371 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6372, __PRETTY_FUNCTION__))
6372 "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId
) && "should have a 'template<>' for this decl"
) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6372, __PRETTY_FUNCTION__))
;
6373 }
6374
6375 if (IsVariableTemplateSpecialization) {
6376 SourceLocation TemplateKWLoc =
6377 TemplateParamLists.size() > 0
6378 ? TemplateParamLists[0]->getTemplateLoc()
6379 : SourceLocation();
6380 DeclResult Res = ActOnVarTemplateSpecialization(
6381 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6382 IsPartialSpecialization);
6383 if (Res.isInvalid())
6384 return nullptr;
6385 NewVD = cast<VarDecl>(Res.get());
6386 AddToScope = false;
6387 } else if (D.isDecompositionDeclarator()) {
6388 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6389 D.getIdentifierLoc(), R, TInfo, SC,
6390 Bindings);
6391 } else
6392 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6393 D.getIdentifierLoc(), II, R, TInfo, SC);
6394
6395 // If this is supposed to be a variable template, create it as such.
6396 if (IsVariableTemplate) {
6397 NewTemplate =
6398 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6399 TemplateParams, NewVD);
6400 NewVD->setDescribedVarTemplate(NewTemplate);
6401 }
6402
6403 // If this decl has an auto type in need of deduction, make a note of the
6404 // Decl so we can diagnose uses of it in its own initializer.
6405 if (R->getContainedDeducedType())
6406 ParsingInitForAutoVars.insert(NewVD);
6407
6408 if (D.isInvalidType() || Invalid) {
6409 NewVD->setInvalidDecl();
6410 if (NewTemplate)
6411 NewTemplate->setInvalidDecl();
6412 }
6413
6414 SetNestedNameSpecifier(NewVD, D);
6415
6416 // If we have any template parameter lists that don't directly belong to
6417 // the variable (matching the scope specifier), store them.
6418 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6419 if (TemplateParamLists.size() > VDTemplateParamLists)
6420 NewVD->setTemplateParameterListsInfo(
6421 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6422
6423 if (D.getDeclSpec().isConstexprSpecified()) {
6424 NewVD->setConstexpr(true);
6425 // C++1z [dcl.spec.constexpr]p1:
6426 // A static data member declared with the constexpr specifier is
6427 // implicitly an inline variable.
6428 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6429 NewVD->setImplicitlyInline();
6430 }
6431
6432 if (D.getDeclSpec().isConceptSpecified()) {
6433 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6434 VTD->setConcept();
6435
6436 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6437 // be declared with the thread_local, inline, friend, or constexpr
6438 // specifiers, [...]
6439 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6440 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6441 diag::err_concept_decl_invalid_specifiers)
6442 << 0 << 0;
6443 NewVD->setInvalidDecl(true);
6444 }
6445
6446 if (D.getDeclSpec().isConstexprSpecified()) {
6447 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6448 diag::err_concept_decl_invalid_specifiers)
6449 << 0 << 3;
6450 NewVD->setInvalidDecl(true);
6451 }
6452
6453 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6454 // applied only to the definition of a function template or variable
6455 // template, declared in namespace scope.
6456 if (IsVariableTemplateSpecialization) {
6457 Diag(D.getDeclSpec().getConceptSpecLoc(),
6458 diag::err_concept_specified_specialization)
6459 << (IsPartialSpecialization ? 2 : 1);
6460 }
6461
6462 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6463 // following restrictions:
6464 // - The declared type shall have the type bool.
6465 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6466 !NewVD->isInvalidDecl()) {
6467 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6468 NewVD->setInvalidDecl(true);
6469 }
6470 }
6471 }
6472
6473 if (D.getDeclSpec().isInlineSpecified()) {
6474 if (!getLangOpts().CPlusPlus) {
6475 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6476 << 0;
6477 } else if (CurContext->isFunctionOrMethod()) {
6478 // 'inline' is not allowed on block scope variable declaration.
6479 Diag(D.getDeclSpec().getInlineSpecLoc(),
6480 diag::err_inline_declaration_block_scope) << Name
6481 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6482 } else {
6483 Diag(D.getDeclSpec().getInlineSpecLoc(),
6484 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6485 : diag::ext_inline_variable);
6486 NewVD->setInlineSpecified();
6487 }
6488 }
6489
6490 // Set the lexical context. If the declarator has a C++ scope specifier, the
6491 // lexical context will be different from the semantic context.
6492 NewVD->setLexicalDeclContext(CurContext);
6493 if (NewTemplate)
6494 NewTemplate->setLexicalDeclContext(CurContext);
6495
6496 if (IsLocalExternDecl) {
6497 if (D.isDecompositionDeclarator())
6498 for (auto *B : Bindings)
6499 B->setLocalExternDecl();
6500 else
6501 NewVD->setLocalExternDecl();
6502 }
6503
6504 bool EmitTLSUnsupportedError = false;
6505 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6506 // C++11 [dcl.stc]p4:
6507 // When thread_local is applied to a variable of block scope the
6508 // storage-class-specifier static is implied if it does not appear
6509 // explicitly.
6510 // Core issue: 'static' is not implied if the variable is declared
6511 // 'extern'.
6512 if (NewVD->hasLocalStorage() &&
6513 (SCSpec != DeclSpec::SCS_unspecified ||
6514 TSCS != DeclSpec::TSCS_thread_local ||
6515 !DC->isFunctionOrMethod()))
6516 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6517 diag::err_thread_non_global)
6518 << DeclSpec::getSpecifierName(TSCS);
6519 else if (!Context.getTargetInfo().isTLSSupported()) {
6520 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6521 // Postpone error emission until we've collected attributes required to
6522 // figure out whether it's a host or device variable and whether the
6523 // error should be ignored.
6524 EmitTLSUnsupportedError = true;
6525 // We still need to mark the variable as TLS so it shows up in AST with
6526 // proper storage class for other tools to use even if we're not going
6527 // to emit any code for it.
6528 NewVD->setTSCSpec(TSCS);
6529 } else
6530 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6531 diag::err_thread_unsupported);
6532 } else
6533 NewVD->setTSCSpec(TSCS);
6534 }
6535
6536 // C99 6.7.4p3
6537 // An inline definition of a function with external linkage shall
6538 // not contain a definition of a modifiable object with static or
6539 // thread storage duration...
6540 // We only apply this when the function is required to be defined
6541 // elsewhere, i.e. when the function is not 'extern inline'. Note
6542 // that a local variable with thread storage duration still has to
6543 // be marked 'static'. Also note that it's possible to get these
6544 // semantics in C++ using __attribute__((gnu_inline)).
6545 if (SC == SC_Static && S->getFnParent() != nullptr &&
6546 !NewVD->getType().isConstQualified()) {
6547 FunctionDecl *CurFD = getCurFunctionDecl();
6548 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6549 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6550 diag::warn_static_local_in_extern_inline);
6551 MaybeSuggestAddingStaticToDecl(CurFD);
6552 }
6553 }
6554
6555 if (D.getDeclSpec().isModulePrivateSpecified()) {
6556 if (IsVariableTemplateSpecialization)
6557 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6558 << (IsPartialSpecialization ? 1 : 0)
6559 << FixItHint::CreateRemoval(
6560 D.getDeclSpec().getModulePrivateSpecLoc());
6561 else if (IsMemberSpecialization)
6562 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6563 << 2
6564 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6565 else if (NewVD->hasLocalStorage())
6566 Diag(NewVD->getLocation(), diag::err_module_private_local)
6567 << 0 << NewVD->getDeclName()
6568 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6569 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6570 else {
6571 NewVD->setModulePrivate();
6572 if (NewTemplate)
6573 NewTemplate->setModulePrivate();
6574 for (auto *B : Bindings)
6575 B->setModulePrivate();
6576 }
6577 }
6578
6579 // Handle attributes prior to checking for duplicates in MergeVarDecl
6580 ProcessDeclAttributes(S, NewVD, D);
6581
6582 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6583 if (EmitTLSUnsupportedError &&
6584 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6585 (getLangOpts().OpenMPIsDevice &&
6586 NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6587 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6588 diag::err_thread_unsupported);
6589 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6590 // storage [duration]."
6591 if (SC == SC_None && S->getFnParent() != nullptr &&
6592 (NewVD->hasAttr<CUDASharedAttr>() ||
6593 NewVD->hasAttr<CUDAConstantAttr>())) {
6594 NewVD->setStorageClass(SC_Static);
6595 }
6596 }
6597
6598 // Ensure that dllimport globals without explicit storage class are treated as
6599 // extern. The storage class is set above using parsed attributes. Now we can
6600 // check the VarDecl itself.
6601 assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6603, __PRETTY_FUNCTION__))
6602 NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6603, __PRETTY_FUNCTION__))
6603 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr
<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember
() || NewVD->getStorageClass() != SC_None) ? static_cast<
void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 6603, __PRETTY_FUNCTION__))
;
6604
6605 // In auto-retain/release, infer strong retension for variables of
6606 // retainable type.
6607 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6608 NewVD->setInvalidDecl();
6609
6610 // Handle GNU asm-label extension (encoded as an attribute).
6611 if (Expr *E = (Expr*)D.getAsmLabel()) {
6612 // The parser guarantees this is a string.
6613 StringLiteral *SE = cast<StringLiteral>(E);
6614 StringRef Label = SE->getString();
6615 if (S->getFnParent() != nullptr) {
6616 switch (SC) {
6617 case SC_None:
6618 case SC_Auto:
6619 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6620 break;
6621 case SC_Register:
6622 // Local Named register
6623 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6624 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6625 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6626 break;
6627 case SC_Static:
6628 case SC_Extern:
6629 case SC_PrivateExtern:
6630 break;
6631 }
6632 } else if (SC == SC_Register) {
6633 // Global Named register
6634 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6635 const auto &TI = Context.getTargetInfo();
6636 bool HasSizeMismatch;
6637
6638 if (!TI.isValidGCCRegisterName(Label))
6639 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6640 else if (!TI.validateGlobalRegisterVariable(Label,
6641 Context.getTypeSize(R),
6642 HasSizeMismatch))
6643 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6644 else if (HasSizeMismatch)
6645 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6646 }
6647
6648 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6649 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6650 NewVD->setInvalidDecl(true);
6651 }
6652 }
6653
6654 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6655 Context, Label, 0));
6656 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6657 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6658 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6659 if (I != ExtnameUndeclaredIdentifiers.end()) {
6660 if (isDeclExternC(NewVD)) {
6661 NewVD->addAttr(I->second);
6662 ExtnameUndeclaredIdentifiers.erase(I);
6663 } else
6664 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6665 << /*Variable*/1 << NewVD;
6666 }
6667 }
6668
6669 // Find the shadowed declaration before filtering for scope.
6670 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6671 ? getShadowedDeclaration(NewVD, Previous)
6672 : nullptr;
6673
6674 // Don't consider existing declarations that are in a different
6675 // scope and are out-of-semantic-context declarations (if the new
6676 // declaration has linkage).
6677 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6678 D.getCXXScopeSpec().isNotEmpty() ||
6679 IsMemberSpecialization ||
6680 IsVariableTemplateSpecialization);
6681
6682 // Check whether the previous declaration is in the same block scope. This
6683 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6684 if (getLangOpts().CPlusPlus &&
6685 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6686 NewVD->setPreviousDeclInSameBlockScope(
6687 Previous.isSingleResult() && !Previous.isShadowed() &&
6688 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6689
6690 if (!getLangOpts().CPlusPlus) {
6691 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6692 } else {
6693 // If this is an explicit specialization of a static data member, check it.
6694 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6695 CheckMemberSpecialization(NewVD, Previous))
6696 NewVD->setInvalidDecl();
6697
6698 // Merge the decl with the existing one if appropriate.
6699 if (!Previous.empty()) {
6700 if (Previous.isSingleResult() &&
6701 isa<FieldDecl>(Previous.getFoundDecl()) &&
6702 D.getCXXScopeSpec().isSet()) {
6703 // The user tried to define a non-static data member
6704 // out-of-line (C++ [dcl.meaning]p1).
6705 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6706 << D.getCXXScopeSpec().getRange();
6707 Previous.clear();
6708 NewVD->setInvalidDecl();
6709 }
6710 } else if (D.getCXXScopeSpec().isSet()) {
6711 // No previous declaration in the qualifying scope.
6712 Diag(D.getIdentifierLoc(), diag::err_no_member)
6713 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6714 << D.getCXXScopeSpec().getRange();
6715 NewVD->setInvalidDecl();
6716 }
6717
6718 if (!IsVariableTemplateSpecialization)
6719 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6720
6721 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6722 // an explicit specialization (14.8.3) or a partial specialization of a
6723 // concept definition.
6724 if (IsVariableTemplateSpecialization &&
6725 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6726 Previous.isSingleResult()) {
6727 NamedDecl *PreviousDecl = Previous.getFoundDecl();
6728 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6729 if (VarTmpl->isConcept()) {
6730 Diag(NewVD->getLocation(), diag::err_concept_specialized)
6731 << 1 /*variable*/
6732 << (IsPartialSpecialization ? 2 /*partially specialized*/
6733 : 1 /*explicitly specialized*/);
6734 Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6735 NewVD->setInvalidDecl();
6736 }
6737 }
6738 }
6739
6740 if (NewTemplate) {
6741 VarTemplateDecl *PrevVarTemplate =
6742 NewVD->getPreviousDecl()
6743 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6744 : nullptr;
6745
6746 // Check the template parameter list of this declaration, possibly
6747 // merging in the template parameter list from the previous variable
6748 // template declaration.
6749 if (CheckTemplateParameterList(
6750 TemplateParams,
6751 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6752 : nullptr,
6753 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6754 DC->isDependentContext())
6755 ? TPC_ClassTemplateMember
6756 : TPC_VarTemplate))
6757 NewVD->setInvalidDecl();
6758
6759 // If we are providing an explicit specialization of a static variable
6760 // template, make a note of that.
6761 if (PrevVarTemplate &&
6762 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6763 PrevVarTemplate->setMemberSpecialization();
6764 }
6765 }
6766
6767 // Diagnose shadowed variables iff this isn't a redeclaration.
6768 if (ShadowedDecl && !D.isRedeclaration())
6769 CheckShadow(NewVD, ShadowedDecl, Previous);
6770
6771 ProcessPragmaWeak(S, NewVD);
6772
6773 // If this is the first declaration of an extern C variable, update
6774 // the map of such variables.
6775 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6776 isIncompleteDeclExternC(*this, NewVD))
6777 RegisterLocallyScopedExternCDecl(NewVD, S);
6778
6779 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6780 Decl *ManglingContextDecl;
6781 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6782 NewVD->getDeclContext(), ManglingContextDecl)) {
6783 Context.setManglingNumber(
6784 NewVD, MCtx->getManglingNumber(
6785 NewVD, getMSManglingNumber(getLangOpts(), S)));
6786 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6787 }
6788 }
6789
6790 // Special handling of variable named 'main'.
6791 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6792 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6793 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6794
6795 // C++ [basic.start.main]p3
6796 // A program that declares a variable main at global scope is ill-formed.
6797 if (getLangOpts().CPlusPlus)
6798 Diag(D.getLocStart(), diag::err_main_global_variable);
6799
6800 // In C, and external-linkage variable named main results in undefined
6801 // behavior.
6802 else if (NewVD->hasExternalFormalLinkage())
6803 Diag(D.getLocStart(), diag::warn_main_redefined);
6804 }
6805
6806 if (D.isRedeclaration() && !Previous.empty()) {
6807 checkDLLAttributeRedeclaration(
6808 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6809 IsMemberSpecialization, D.isFunctionDefinition());
6810 }
6811
6812 if (NewTemplate) {
6813 if (NewVD->isInvalidDecl())
6814 NewTemplate->setInvalidDecl();
6815 ActOnDocumentableDecl(NewTemplate);
6816 return NewTemplate;
6817 }
6818
6819 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6820 CompleteMemberSpecialization(NewVD, Previous);
6821
6822 return NewVD;
6823}
6824
6825/// Enum describing the %select options in diag::warn_decl_shadow.
6826enum ShadowedDeclKind {
6827 SDK_Local,
6828 SDK_Global,
6829 SDK_StaticMember,
6830 SDK_Field,
6831 SDK_Typedef,
6832 SDK_Using
6833};
6834
6835/// Determine what kind of declaration we're shadowing.
6836static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6837 const DeclContext *OldDC) {
6838 if (isa<TypeAliasDecl>(ShadowedDecl))
6839 return SDK_Using;
6840 else if (isa<TypedefDecl>(ShadowedDecl))
6841 return SDK_Typedef;
6842 else if (isa<RecordDecl>(OldDC))
6843 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6844
6845 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6846}
6847
6848/// Return the location of the capture if the given lambda captures the given
6849/// variable \p VD, or an invalid source location otherwise.
6850static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6851 const VarDecl *VD) {
6852 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6853 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6854 return Capture.getLocation();
6855 }
6856 return SourceLocation();
6857}
6858
6859static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6860 const LookupResult &R) {
6861 // Only diagnose if we're shadowing an unambiguous field or variable.
6862 if (R.getResultKind() != LookupResult::Found)
6863 return false;
6864
6865 // Return false if warning is ignored.
6866 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6867}
6868
6869/// \brief Return the declaration shadowed by the given variable \p D, or null
6870/// if it doesn't shadow any declaration or shadowing warnings are disabled.
6871NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6872 const LookupResult &R) {
6873 if (!shouldWarnIfShadowedDecl(Diags, R))
6874 return nullptr;
6875
6876 // Don't diagnose declarations at file scope.
6877 if (D->hasGlobalStorage())
6878 return nullptr;
6879
6880 NamedDecl *ShadowedDecl = R.getFoundDecl();
6881 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6882 ? ShadowedDecl
6883 : nullptr;
6884}
6885
6886/// \brief Return the declaration shadowed by the given typedef \p D, or null
6887/// if it doesn't shadow any declaration or shadowing warnings are disabled.
6888NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6889 const LookupResult &R) {
6890 // Don't warn if typedef declaration is part of a class
6891 if (D->getDeclContext()->isRecord())
6892 return nullptr;
6893
6894 if (!shouldWarnIfShadowedDecl(Diags, R))
6895 return nullptr;
6896
6897 NamedDecl *ShadowedDecl = R.getFoundDecl();
6898 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6899}
6900
6901/// \brief Diagnose variable or built-in function shadowing. Implements
6902/// -Wshadow.
6903///
6904/// This method is called whenever a VarDecl is added to a "useful"
6905/// scope.
6906///
6907/// \param ShadowedDecl the declaration that is shadowed by the given variable
6908/// \param R the lookup of the name
6909///
6910void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6911 const LookupResult &R) {
6912 DeclContext *NewDC = D->getDeclContext();
6913
6914 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6915 // Fields are not shadowed by variables in C++ static methods.
6916 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6917 if (MD->isStatic())
6918 return;
6919
6920 // Fields shadowed by constructor parameters are a special case. Usually
6921 // the constructor initializes the field with the parameter.
6922 if (isa<CXXConstructorDecl>(NewDC))
6923 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
6924 // Remember that this was shadowed so we can either warn about its
6925 // modification or its existence depending on warning settings.
6926 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
6927 return;
6928 }
6929 }
6930
6931 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6932 if (shadowedVar->isExternC()) {
6933 // For shadowing external vars, make sure that we point to the global
6934 // declaration, not a locally scoped extern declaration.
6935 for (auto I : shadowedVar->redecls())
6936 if (I->isFileVarDecl()) {
6937 ShadowedDecl = I;
6938 break;
6939 }
6940 }
6941
6942 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
6943
6944 unsigned WarningDiag = diag::warn_decl_shadow;
6945 SourceLocation CaptureLoc;
6946 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
6947 isa<CXXMethodDecl>(NewDC)) {
6948 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6949 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6950 if (RD->getLambdaCaptureDefault() == LCD_None) {
6951 // Try to avoid warnings for lambdas with an explicit capture list.
6952 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6953 // Warn only when the lambda captures the shadowed decl explicitly.
6954 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6955 if (CaptureLoc.isInvalid())
6956 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6957 } else {
6958 // Remember that this was shadowed so we can avoid the warning if the
6959 // shadowed decl isn't captured and the warning settings allow it.
6960 cast<LambdaScopeInfo>(getCurFunction())
6961 ->ShadowingDecls.push_back(
6962 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
6963 return;
6964 }
6965 }
6966 }
6967 }
6968
6969 // Only warn about certain kinds of shadowing for class members.
6970 if (NewDC && NewDC->isRecord()) {
6971 // In particular, don't warn about shadowing non-class members.
6972 if (!OldDC->isRecord())
6973 return;
6974
6975 // TODO: should we warn about static data members shadowing
6976 // static data members from base classes?
6977
6978 // TODO: don't diagnose for inaccessible shadowed members.
6979 // This is hard to do perfectly because we might friend the
6980 // shadowing context, but that's just a false negative.
6981 }
6982
6983
6984 DeclarationName Name = R.getLookupName();
6985
6986 // Emit warning and note.
6987 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6988 return;
6989 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6990 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6991 if (!CaptureLoc.isInvalid())
6992 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6993 << Name << /*explicitly*/ 1;
6994 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6995}
6996
6997/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6998/// when these variables are captured by the lambda.
6999void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7000 for (const auto &Shadow : LSI->ShadowingDecls) {
7001 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7002 // Try to avoid the warning when the shadowed decl isn't captured.
7003 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7004 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7005 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7006 ? diag::warn_decl_shadow_uncaptured_local
7007 : diag::warn_decl_shadow)
7008 << Shadow.VD->getDeclName()
7009 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7010 if (!CaptureLoc.isInvalid())
7011 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7012 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7013 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7014 }
7015}
7016
7017/// \brief Check -Wshadow without the advantage of a previous lookup.
7018void Sema::CheckShadow(Scope *S, VarDecl *D) {
7019 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7020 return;
7021
7022 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7023 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
7024 LookupName(R, S);
7025 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7026 CheckShadow(D, ShadowedDecl, R);
7027}
7028
7029/// Check if 'E', which is an expression that is about to be modified, refers
7030/// to a constructor parameter that shadows a field.
7031void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7032 // Quickly ignore expressions that can't be shadowing ctor parameters.
7033 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7034 return;
7035 E = E->IgnoreParenImpCasts();
7036 auto *DRE = dyn_cast<DeclRefExpr>(E);
7037 if (!DRE)
7038 return;
7039 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7040 auto I = ShadowingDecls.find(D);
7041 if (I == ShadowingDecls.end())
7042 return;
7043 const NamedDecl *ShadowedDecl = I->second;
7044 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7045 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7046 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7047 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7048
7049 // Avoid issuing multiple warnings about the same decl.
7050 ShadowingDecls.erase(I);
7051}
7052
7053/// Check for conflict between this global or extern "C" declaration and
7054/// previous global or extern "C" declarations. This is only used in C++.
7055template<typename T>
7056static bool checkGlobalOrExternCConflict(
7057 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7058 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""
) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 7058, __PRETTY_FUNCTION__))
;
7059 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7060
7061 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7062 // The common case: this global doesn't conflict with any extern "C"
7063 // declaration.
7064 return false;
7065 }
7066
7067 if (Prev) {
7068 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7069 // Both the old and new declarations have C language linkage. This is a
7070 // redeclaration.
7071 Previous.clear();
7072 Previous.addDecl(Prev);
7073 return true;
7074 }
7075
7076 // This is a global, non-extern "C" declaration, and there is a previous
7077 // non-global extern "C" declaration. Diagnose if this is a variable
7078 // declaration.
7079 if (!isa<VarDecl>(ND))
7080 return false;
7081 } else {
7082 // The declaration is extern "C". Check for any declaration in the
7083 // translation unit which might conflict.
7084 if (IsGlobal) {
7085 // We have already performed the lookup into the translation unit.
7086 IsGlobal = false;
7087 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7088 I != E; ++I) {
7089 if (isa<VarDecl>(*I)) {
7090 Prev = *I;
7091 break;
7092 }
7093 }
7094 } else {
7095 DeclContext::lookup_result R =
7096 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7097 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7098 I != E; ++I) {
7099 if (isa<VarDecl>(*I)) {
7100 Prev = *I;
7101 break;
7102 }
7103 // FIXME: If we have any other entity with this name in global scope,
7104 // the declaration is ill-formed, but that is a defect: it breaks the
7105 // 'stat' hack, for instance. Only variables can have mangled name
7106 // clashes with extern "C" declarations, so only they deserve a
7107 // diagnostic.
7108 }
7109 }
7110
7111 if (!Prev)
7112 return false;
7113 }
7114
7115 // Use the first declaration's location to ensure we point at something which
7116 // is lexically inside an extern "C" linkage-spec.
7117 assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose"
) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 7117, __PRETTY_FUNCTION__))
;
7118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7119 Prev = FD->getFirstDecl();
7120 else
7121 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7122
7123 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7124 << IsGlobal << ND;
7125 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7126 << IsGlobal;
7127 return false;
7128}
7129
7130/// Apply special rules for handling extern "C" declarations. Returns \c true
7131/// if we have found that this is a redeclaration of some prior entity.
7132///
7133/// Per C++ [dcl.link]p6:
7134/// Two declarations [for a function or variable] with C language linkage
7135/// with the same name that appear in different scopes refer to the same
7136/// [entity]. An entity with C language linkage shall not be declared with
7137/// the same name as an entity in global scope.
7138template<typename T>
7139static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7140 LookupResult &Previous) {
7141 if (!S.getLangOpts().CPlusPlus) {
7142 // In C, when declaring a global variable, look for a corresponding 'extern'
7143 // variable declared in function scope. We don't need this in C++, because
7144 // we find local extern decls in the surrounding file-scope DeclContext.
7145 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7146 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7147 Previous.clear();
7148 Previous.addDecl(Prev);
7149 return true;
7150 }
7151 }
7152 return false;
7153 }
7154
7155 // A declaration in the translation unit can conflict with an extern "C"
7156 // declaration.
7157 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7158 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7159
7160 // An extern "C" declaration can conflict with a declaration in the
7161 // translation unit or can be a redeclaration of an extern "C" declaration
7162 // in another scope.
7163 if (isIncompleteDeclExternC(S,ND))
7164 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7165
7166 // Neither global nor extern "C": nothing to do.
7167 return false;
7168}
7169
7170void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7171 // If the decl is already known invalid, don't check it.
7172 if (NewVD->isInvalidDecl())
7173 return;
7174
7175 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7176 QualType T = TInfo->getType();
7177
7178 // Defer checking an 'auto' type until its initializer is attached.
7179 if (T->isUndeducedType())
7180 return;
7181
7182 if (NewVD->hasAttrs())
7183 CheckAlignasUnderalignment(NewVD);
7184
7185 if (T->isObjCObjectType()) {
7186 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7187 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7188 T = Context.getObjCObjectPointerType(T);
7189 NewVD->setType(T);
7190 }
7191
7192 // Emit an error if an address space was applied to decl with local storage.
7193 // This includes arrays of objects with address space qualifiers, but not
7194 // automatic variables that point to other address spaces.
7195 // ISO/IEC TR 18037 S5.1.2
7196 if (!getLangOpts().OpenCL
7197 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
7198 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7199 NewVD->setInvalidDecl();
7200 return;
7201 }
7202
7203 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7204 // scope.
7205 if (getLangOpts().OpenCLVersion == 120 &&
7206 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7207 NewVD->isStaticLocal()) {
7208 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7209 NewVD->setInvalidDecl();
7210 return;
7211 }
7212
7213 if (getLangOpts().OpenCL) {
7214 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7215 if (NewVD->hasAttr<BlocksAttr>()) {
7216 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7217 return;
7218 }
7219
7220 if (T->isBlockPointerType()) {
7221 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7222 // can't use 'extern' storage class.
7223 if (!T.isConstQualified()) {
7224 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7225 << 0 /*const*/;
7226 NewVD->setInvalidDecl();
7227 return;
7228 }
7229 if (NewVD->hasExternalStorage()) {
7230 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7231 NewVD->setInvalidDecl();
7232 return;
7233 }
7234 }
7235 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7236 // __constant address space.
7237 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7238 // variables inside a function can also be declared in the global
7239 // address space.
7240 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7241 NewVD->hasExternalStorage()) {
7242 if (!T->isSamplerT() &&
7243 !(T.getAddressSpace() == LangAS::opencl_constant ||
7244 (T.getAddressSpace() == LangAS::opencl_global &&
7245 getLangOpts().OpenCLVersion == 200))) {
7246 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7247 if (getLangOpts().OpenCLVersion == 200)
7248 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7249 << Scope << "global or constant";
7250 else
7251 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7252 << Scope << "constant";
7253 NewVD->setInvalidDecl();
7254 return;
7255 }
7256 } else {
7257 if (T.getAddressSpace() == LangAS::opencl_global) {
7258 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7259 << 1 /*is any function*/ << "global";
7260 NewVD->setInvalidDecl();
7261 return;
7262 }
7263 if (T.getAddressSpace() == LangAS::opencl_constant ||
7264 T.getAddressSpace() == LangAS::opencl_local) {
7265 FunctionDecl *FD = getCurFunctionDecl();
7266 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7267 // in functions.
7268 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7269 if (T.getAddressSpace() == LangAS::opencl_constant)
7270 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7271 << 0 /*non-kernel only*/ << "constant";
7272 else
7273 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7274 << 0 /*non-kernel only*/ << "local";
7275 NewVD->setInvalidDecl();
7276 return;
7277 }
7278 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7279 // in the outermost scope of a kernel function.
7280 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7281 if (!getCurScope()->isFunctionScope()) {
7282 if (T.getAddressSpace() == LangAS::opencl_constant)
7283 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7284 << "constant";
7285 else
7286 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7287 << "local";
7288 NewVD->setInvalidDecl();
7289 return;
7290 }
7291 }
7292 } else if (T.getAddressSpace() != LangAS::Default) {
7293 // Do not allow other address spaces on automatic variable.
7294 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7295 NewVD->setInvalidDecl();
7296 return;
7297 }
7298 }
7299 }
7300
7301 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7302 && !NewVD->hasAttr<BlocksAttr>()) {
7303 if (getLangOpts().getGC() != LangOptions::NonGC)
7304 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7305 else {
7306 assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 7306, __PRETTY_FUNCTION__))
;
7307 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7308 }
7309 }
7310
7311 bool isVM = T->isVariablyModifiedType();
7312 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7313 NewVD->hasAttr<BlocksAttr>())
7314 getCurFunction()->setHasBranchProtectedScope();
7315
7316 if ((isVM && NewVD->hasLinkage()) ||
7317 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7318 bool SizeIsNegative;
7319 llvm::APSInt Oversized;
7320 TypeSourceInfo *FixedTInfo =
7321 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7322 SizeIsNegative, Oversized);
7323 if (!FixedTInfo && T->isVariableArrayType()) {
7324 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7325 // FIXME: This won't give the correct result for
7326 // int a[10][n];
7327 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7328
7329 if (NewVD->isFileVarDecl())
7330 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7331 << SizeRange;
7332 else if (NewVD->isStaticLocal())
7333 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7334 << SizeRange;
7335 else
7336 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7337 << SizeRange;
7338 NewVD->setInvalidDecl();
7339 return;
7340 }
7341
7342 if (!FixedTInfo) {
7343 if (NewVD->isFileVarDecl())
7344 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7345 else
7346 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7347 NewVD->setInvalidDecl();
7348 return;
7349 }
7350
7351 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7352 NewVD->setType(FixedTInfo->getType());
7353 NewVD->setTypeSourceInfo(FixedTInfo);
7354 }
7355
7356 if (T->isVoidType()) {
7357 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7358 // of objects and functions.
7359 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7360 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7361 << T;
7362 NewVD->setInvalidDecl();
7363 return;
7364 }
7365 }
7366
7367 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7368 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7369 NewVD->setInvalidDecl();
7370 return;
7371 }
7372
7373 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7374 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7375 NewVD->setInvalidDecl();
7376 return;
7377 }
7378
7379 if (NewVD->isConstexpr() && !T->isDependentType() &&
7380 RequireLiteralType(NewVD->getLocation(), T,
7381 diag::err_constexpr_var_non_literal)) {
7382 NewVD->setInvalidDecl();
7383 return;
7384 }
7385}
7386
7387/// \brief Perform semantic checking on a newly-created variable
7388/// declaration.
7389///
7390/// This routine performs all of the type-checking required for a
7391/// variable declaration once it has been built. It is used both to
7392/// check variables after they have been parsed and their declarators
7393/// have been translated into a declaration, and to check variables
7394/// that have been instantiated from a template.
7395///
7396/// Sets NewVD->isInvalidDecl() if an error was encountered.
7397///
7398/// Returns true if the variable declaration is a redeclaration.
7399bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7400 CheckVariableDeclarationType(NewVD);
7401
7402 // If the decl is already known invalid, don't check it.
7403 if (NewVD->isInvalidDecl())
7404 return false;
7405
7406 // If we did not find anything by this name, look for a non-visible
7407 // extern "C" declaration with the same name.
7408 if (Previous.empty() &&
7409 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7410 Previous.setShadowed();
7411
7412 if (!Previous.empty()) {
7413 MergeVarDecl(NewVD, Previous);
7414 return true;
7415 }
7416 return false;
7417}
7418
7419namespace {
7420struct FindOverriddenMethod {
7421 Sema *S;
7422 CXXMethodDecl *Method;
7423
7424 /// Member lookup function that determines whether a given C++
7425 /// method overrides a method in a base class, to be used with
7426 /// CXXRecordDecl::lookupInBases().
7427 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7428 RecordDecl *BaseRecord =
7429 Specifier->getType()->getAs<RecordType>()->getDecl();
7430
7431 DeclarationName Name = Method->getDeclName();
7432
7433 // FIXME: Do we care about other names here too?
7434 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7435 // We really want to find the base class destructor here.
7436 QualType T = S->Context.getTypeDeclType(BaseRecord);
7437 CanQualType CT = S->Context.getCanonicalType(T);
7438
7439 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7440 }
7441
7442 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7443 Path.Decls = Path.Decls.slice(1)) {
7444 NamedDecl *D = Path.Decls.front();
7445 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7446 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7447 return true;
7448 }
7449 }
7450
7451 return false;
7452 }
7453};
7454
7455enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7456} // end anonymous namespace
7457
7458/// \brief Report an error regarding overriding, along with any relevant
7459/// overriden methods.
7460///
7461/// \param DiagID the primary error to report.
7462/// \param MD the overriding method.
7463/// \param OEK which overrides to include as notes.
7464static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7465 OverrideErrorKind OEK = OEK_All) {
7466 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7467 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7468 E = MD->end_overridden_methods();
7469 I != E; ++I) {
7470 // This check (& the OEK parameter) could be replaced by a predicate, but
7471 // without lambdas that would be overkill. This is still nicer than writing
7472 // out the diag loop 3 times.
7473 if ((OEK == OEK_All) ||
7474 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7475 (OEK == OEK_Deleted && (*I)->isDeleted()))
7476 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7477 }
7478}
7479
7480/// AddOverriddenMethods - See if a method overrides any in the base classes,
7481/// and if so, check that it's a valid override and remember it.
7482bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7483 // Look for methods in base classes that this method might override.
7484 CXXBasePaths Paths;
7485 FindOverriddenMethod FOM;
7486 FOM.Method = MD;
7487 FOM.S = this;
7488 bool hasDeletedOverridenMethods = false;
7489 bool hasNonDeletedOverridenMethods = false;
7490 bool AddedAny = false;
7491 if (DC->lookupInBases(FOM, Paths)) {
7492 for (auto *I : Paths.found_decls()) {
7493 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7494 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7495 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7496 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7497 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7498 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7499 hasDeletedOverridenMethods |= OldMD->isDeleted();
7500 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7501 AddedAny = true;
7502 }
7503 }
7504 }
7505 }
7506
7507 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7508 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7509 }
7510 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7511 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7512 }
7513
7514 return AddedAny;
7515}
7516
7517namespace {
7518 // Struct for holding all of the extra arguments needed by
7519 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7520 struct ActOnFDArgs {
7521 Scope *S;
7522 Declarator &D;
7523 MultiTemplateParamsArg TemplateParamLists;
7524 bool AddToScope;
7525 };
7526} // end anonymous namespace
7527
7528namespace {
7529
7530// Callback to only accept typo corrections that have a non-zero edit distance.
7531// Also only accept corrections that have the same parent decl.
7532class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7533 public:
7534 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7535 CXXRecordDecl *Parent)
7536 : Context(Context), OriginalFD(TypoFD),
7537 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7538
7539 bool ValidateCandidate(const TypoCorrection &candidate) override {
7540 if (candidate.getEditDistance() == 0)
7541 return false;
7542
7543 SmallVector<unsigned, 1> MismatchedParams;
7544 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7545 CDeclEnd = candidate.end();
7546 CDecl != CDeclEnd; ++CDecl) {
7547 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7548
7549 if (FD && !FD->hasBody() &&
7550 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7551 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7552 CXXRecordDecl *Parent = MD->getParent();
7553 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7554 return true;
7555 } else if (!ExpectedParent) {
7556 return true;
7557 }
7558 }
7559 }
7560
7561 return false;
7562 }
7563
7564 private:
7565 ASTContext &Context;
7566 FunctionDecl *OriginalFD;
7567 CXXRecordDecl *ExpectedParent;
7568};
7569
7570} // end anonymous namespace
7571
7572void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7573 TypoCorrectedFunctionDefinitions.insert(F);
7574}
7575
7576/// \brief Generate diagnostics for an invalid function redeclaration.
7577///
7578/// This routine handles generating the diagnostic messages for an invalid
7579/// function redeclaration, including finding possible similar declarations
7580/// or performing typo correction if there are no previous declarations with
7581/// the same name.
7582///
7583/// Returns a NamedDecl iff typo correction was performed and substituting in
7584/// the new declaration name does not cause new errors.
7585static NamedDecl *DiagnoseInvalidRedeclaration(
7586 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7587 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7588 DeclarationName Name = NewFD->getDeclName();
7589 DeclContext *NewDC = NewFD->getDeclContext();
7590 SmallVector<unsigned, 1> MismatchedParams;
7591 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7592 TypoCorrection Correction;
7593 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7594 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7595 : diag::err_member_decl_does_not_match;
7596 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7597 IsLocalFriend ? Sema::LookupLocalFriendName
7598 : Sema::LookupOrdinaryName,
7599 Sema::ForRedeclaration);
7600
7601 NewFD->setInvalidDecl();
7602 if (IsLocalFriend)
7603 SemaRef.LookupName(Prev, S);
7604 else
7605 SemaRef.LookupQualifiedName(Prev, NewDC);
7606 assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 7607, __PRETTY_FUNCTION__))
7607 "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 7607, __PRETTY_FUNCTION__))
;
7608 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7609 if (!Prev.empty()) {
7610 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7611 Func != FuncEnd; ++Func) {
7612 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7613 if (FD &&
7614 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7615 // Add 1 to the index so that 0 can mean the mismatch didn't
7616 // involve a parameter
7617 unsigned ParamNum =
7618 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7619 NearMatches.push_back(std::make_pair(FD, ParamNum));
7620 }
7621 }
7622 // If the qualified name lookup yielded nothing, try typo correction
7623 } else if ((Correction = SemaRef.CorrectTypo(
7624 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7625 &ExtraArgs.D.getCXXScopeSpec(),
7626 llvm::make_unique<DifferentNameValidatorCCC>(
7627 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7628 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7629 // Set up everything for the call to ActOnFunctionDeclarator
7630 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7631 ExtraArgs.D.getIdentifierLoc());
7632 Previous.clear();
7633 Previous.setLookupName(Correction.getCorrection());
7634 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7635 CDeclEnd = Correction.end();
7636 CDecl != CDeclEnd; ++CDecl) {
7637 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7638 if (FD && !FD->hasBody() &&
7639 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7640 Previous.addDecl(FD);
7641 }
7642 }
7643 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7644
7645 NamedDecl *Result;
7646 // Retry building the function declaration with the new previous
7647 // declarations, and with errors suppressed.
7648 {
7649 // Trap errors.
7650 Sema::SFINAETrap Trap(SemaRef);
7651
7652 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7653 // pieces need to verify the typo-corrected C++ declaration and hopefully
7654 // eliminate the need for the parameter pack ExtraArgs.
7655 Result = SemaRef.ActOnFunctionDeclarator(
7656 ExtraArgs.S, ExtraArgs.D,
7657 Correction.getCorrectionDecl()->getDeclContext(),
7658 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7659 ExtraArgs.AddToScope);
7660
7661 if (Trap.hasErrorOccurred())
7662 Result = nullptr;
7663 }
7664
7665 if (Result) {
7666 // Determine which correction we picked.
7667 Decl *Canonical = Result->getCanonicalDecl();
7668 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7669 I != E; ++I)
7670 if ((*I)->getCanonicalDecl() == Canonical)
7671 Correction.setCorrectionDecl(*I);
7672
7673 // Let Sema know about the correction.
7674 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7675 SemaRef.diagnoseTypo(
7676 Correction,
7677 SemaRef.PDiag(IsLocalFriend
7678 ? diag::err_no_matching_local_friend_suggest
7679 : diag::err_member_decl_does_not_match_suggest)
7680 << Name << NewDC << IsDefinition);
7681 return Result;
7682 }
7683
7684 // Pretend the typo correction never occurred
7685 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7686 ExtraArgs.D.getIdentifierLoc());
7687 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7688 Previous.clear();
7689 Previous.setLookupName(Name);
7690 }
7691
7692 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7693 << Name << NewDC << IsDefinition << NewFD->getLocation();
7694
7695 bool NewFDisConst = false;
7696 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7697 NewFDisConst = NewMD->isConst();
7698
7699 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7700 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7701 NearMatch != NearMatchEnd; ++NearMatch) {
7702 FunctionDecl *FD = NearMatch->first;
7703 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7704 bool FDisConst = MD && MD->isConst();
7705 bool IsMember = MD || !IsLocalFriend;
7706
7707 // FIXME: These notes are poorly worded for the local friend case.
7708 if (unsigned Idx = NearMatch->second) {
7709 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7710 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7711 if (Loc.isInvalid()) Loc = FD->getLocation();
7712 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7713 : diag::note_local_decl_close_param_match)
7714 << Idx << FDParam->getType()
7715 << NewFD->getParamDecl(Idx - 1)->getType();
7716 } else if (FDisConst != NewFDisConst) {
7717 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7718 << NewFDisConst << FD->getSourceRange().getEnd();
7719 } else
7720 SemaRef.Diag(FD->getLocation(),
7721 IsMember ? diag::note_member_def_close_match
7722 : diag::note_local_decl_close_match);
7723 }
7724 return nullptr;
7725}
7726
7727static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7728 switch (D.getDeclSpec().getStorageClassSpec()) {
7729 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 7729)
;
7730 case DeclSpec::SCS_auto:
7731 case DeclSpec::SCS_register:
7732 case DeclSpec::SCS_mutable:
7733 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7734 diag::err_typecheck_sclass_func);
7735 D.getMutableDeclSpec().ClearStorageClassSpecs();
7736 D.setInvalidType();
7737 break;
7738 case DeclSpec::SCS_unspecified: break;
7739 case DeclSpec::SCS_extern:
7740 if (D.getDeclSpec().isExternInLinkageSpec())
7741 return SC_None;
7742 return SC_Extern;
7743 case DeclSpec::SCS_static: {
7744 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7745 // C99 6.7.1p5:
7746 // The declaration of an identifier for a function that has
7747 // block scope shall have no explicit storage-class specifier
7748 // other than extern
7749 // See also (C++ [dcl.stc]p4).
7750 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7751 diag::err_static_block_func);
7752 break;
7753 } else
7754 return SC_Static;
7755 }
7756 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7757 }
7758
7759 // No explicit storage class has already been returned
7760 return SC_None;
7761}
7762
7763static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7764 DeclContext *DC, QualType &R,
7765 TypeSourceInfo *TInfo,
7766 StorageClass SC,
7767 bool &IsVirtualOkay) {
7768 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7769 DeclarationName Name = NameInfo.getName();
7770
7771 FunctionDecl *NewFD = nullptr;
7772 bool isInline = D.getDeclSpec().isInlineSpecified();
7773
7774 if (!SemaRef.getLangOpts().CPlusPlus) {
7775 // Determine whether the function was written with a
7776 // prototype. This true when:
7777 // - there is a prototype in the declarator, or
7778 // - the type R of the function is some kind of typedef or other non-
7779 // attributed reference to a type name (which eventually refers to a
7780 // function type).
7781 bool HasPrototype =
7782 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7783 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7784
7785 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7786 D.getLocStart(), NameInfo, R,
7787 TInfo, SC, isInline,
7788 HasPrototype, false);
7789 if (D.isInvalidType())
7790 NewFD->setInvalidDecl();
7791
7792 return NewFD;
7793 }
7794
7795 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7796 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7797
7798 // Check that the return type is not an abstract class type.
7799 // For record types, this is done by the AbstractClassUsageDiagnoser once
7800 // the class has been completely parsed.
7801 if (!DC->isRecord() &&
7802 SemaRef.RequireNonAbstractType(
7803 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7804 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7805 D.setInvalidType();
7806
7807 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7808 // This is a C++ constructor declaration.
7809 assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 7810, __PRETTY_FUNCTION__))
7810 "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context"
) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 7810, __PRETTY_FUNCTION__))
;
7811
7812 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7813 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7814 D.getLocStart(), NameInfo,
7815 R, TInfo, isExplicit, isInline,
7816 /*isImplicitlyDeclared=*/false,
7817 isConstexpr);
7818
7819 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7820 // This is a C++ destructor declaration.
7821 if (DC->isRecord()) {
7822 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7823 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7824 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7825 SemaRef.Context, Record,
7826 D.getLocStart(),
7827 NameInfo, R, TInfo, isInline,
7828 /*isImplicitlyDeclared=*/false);
7829
7830 // If the class is complete, then we now create the implicit exception
7831 // specification. If the class is incomplete or dependent, we can't do
7832 // it yet.
7833 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7834 Record->getDefinition() && !Record->isBeingDefined() &&
7835 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7836 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7837 }
7838
7839 IsVirtualOkay = true;
7840 return NewDD;
7841
7842 } else {
7843 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7844 D.setInvalidType();
7845
7846 // Create a FunctionDecl to satisfy the function definition parsing
7847 // code path.
7848 return FunctionDecl::Create(SemaRef.Context, DC,
7849 D.getLocStart(),
7850 D.getIdentifierLoc(), Name, R, TInfo,
7851 SC, isInline,
7852 /*hasPrototype=*/true, isConstexpr);
7853 }
7854
7855 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7856 if (!DC->isRecord()) {
7857 SemaRef.Diag(D.getIdentifierLoc(),
7858 diag::err_conv_function_not_member);
7859 return nullptr;
7860 }
7861
7862 SemaRef.CheckConversionDeclarator(D, R, SC);
7863 IsVirtualOkay = true;
7864 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7865 D.getLocStart(), NameInfo,
7866 R, TInfo, isInline, isExplicit,
7867 isConstexpr, SourceLocation());
7868
7869 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7870 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7871
7872 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7873 isExplicit, NameInfo, R, TInfo,
7874 D.getLocEnd());
7875 } else if (DC->isRecord()) {
7876 // If the name of the function is the same as the name of the record,
7877 // then this must be an invalid constructor that has a return type.
7878 // (The parser checks for a return type and makes the declarator a
7879 // constructor if it has no return type).
7880 if (Name.getAsIdentifierInfo() &&
7881 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7882 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7883 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7884 << SourceRange(D.getIdentifierLoc());
7885 return nullptr;
7886 }
7887
7888 // This is a C++ method declaration.
7889 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7890 cast<CXXRecordDecl>(DC),
7891 D.getLocStart(), NameInfo, R,
7892 TInfo, SC, isInline,
7893 isConstexpr, SourceLocation());
7894 IsVirtualOkay = !Ret->isStatic();
7895 return Ret;
7896 } else {
7897 bool isFriend =
7898 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7899 if (!isFriend && SemaRef.CurContext->isRecord())
7900 return nullptr;
7901
7902 // Determine whether the function was written with a
7903 // prototype. This true when:
7904 // - we're in C++ (where every function has a prototype),
7905 return FunctionDecl::Create(SemaRef.Context, DC,
7906 D.getLocStart(),
7907 NameInfo, R, TInfo, SC, isInline,
7908 true/*HasPrototype*/, isConstexpr);
7909 }
7910}
7911
7912enum OpenCLParamType {
7913 ValidKernelParam,
7914 PtrPtrKernelParam,
7915 PtrKernelParam,
7916 InvalidAddrSpacePtrKernelParam,
7917 InvalidKernelParam,
7918 RecordKernelParam
7919};
7920
7921static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7922 if (PT->isPointerType()) {
7923 QualType PointeeType = PT->getPointeeType();
7924 if (PointeeType->isPointerType())
7925 return PtrPtrKernelParam;
7926 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7927 PointeeType.getAddressSpace() == 0)
7928 return InvalidAddrSpacePtrKernelParam;
7929 return PtrKernelParam;
7930 }
7931
7932 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7933 // be used as builtin types.
7934
7935 if (PT->isImageType())
7936 return PtrKernelParam;
7937
7938 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
7939 return InvalidKernelParam;
7940
7941 // OpenCL extension spec v1.2 s9.5:
7942 // This extension adds support for half scalar and vector types as built-in
7943 // types that can be used for arithmetic operations, conversions etc.
7944 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7945 return InvalidKernelParam;
7946
7947 if (PT->isRecordType())
7948 return RecordKernelParam;
7949
7950 return ValidKernelParam;
7951}
7952
7953static void checkIsValidOpenCLKernelParameter(
7954 Sema &S,
7955 Declarator &D,
7956 ParmVarDecl *Param,
7957 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7958 QualType PT = Param->getType();
7959
7960 // Cache the valid types we encounter to avoid rechecking structs that are
7961 // used again
7962 if (ValidTypes.count(PT.getTypePtr()))
7963 return;
7964
7965 switch (getOpenCLKernelParameterType(S, PT)) {
7966 case PtrPtrKernelParam:
7967 // OpenCL v1.2 s6.9.a:
7968 // A kernel function argument cannot be declared as a
7969 // pointer to a pointer type.
7970 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7971 D.setInvalidType();
7972 return;
7973
7974 case InvalidAddrSpacePtrKernelParam:
7975 // OpenCL v1.0 s6.5:
7976 // __kernel function arguments declared to be a pointer of a type can point
7977 // to one of the following address spaces only : __global, __local or
7978 // __constant.
7979 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7980 D.setInvalidType();
7981 return;
7982
7983 // OpenCL v1.2 s6.9.k:
7984 // Arguments to kernel functions in a program cannot be declared with the
7985 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7986 // uintptr_t or a struct and/or union that contain fields declared to be
7987 // one of these built-in scalar types.
7988
7989 case InvalidKernelParam:
7990 // OpenCL v1.2 s6.8 n:
7991 // A kernel function argument cannot be declared
7992 // of event_t type.
7993 // Do not diagnose half type since it is diagnosed as invalid argument
7994 // type for any function elsewhere.
7995 if (!PT->isHalfType())
7996 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7997 D.setInvalidType();
7998 return;
7999
8000 case PtrKernelParam:
8001 case ValidKernelParam:
8002 ValidTypes.insert(PT.getTypePtr());
8003 return;
8004
8005 case RecordKernelParam:
8006 break;
8007 }
8008
8009 // Track nested structs we will inspect
8010 SmallVector<const Decl *, 4> VisitStack;
8011
8012 // Track where we are in the nested structs. Items will migrate from
8013 // VisitStack to HistoryStack as we do the DFS for bad field.
8014 SmallVector<const FieldDecl *, 4> HistoryStack;
8015 HistoryStack.push_back(nullptr);
8016
8017 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8018 VisitStack.push_back(PD);
8019
8020 assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast
<void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "/tmp/buildd/llvm-toolchain-snapshot-5.0~svn306458/tools/clang/lib/Sema/SemaDecl.cpp"
, 8020, __PRETTY_FUNCTION__))
;
8021
8022 do {