Bug Summary

File:tools/clang/lib/Sema/SemaDecl.cpp
Warning:line 6561, column 9
Null pointer passed as an argument to a 'nonnull' parameter

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp

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