File: | tools/clang/lib/Sema/SemaDecl.cpp |
Warning: | line 3202, column 5 Value stored to 'NewType' is never read |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
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 | |
51 | using namespace clang; |
52 | using namespace sema; |
53 | |
54 | Sema::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 | |
63 | namespace { |
64 | |
65 | class 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 | /// Determine whether the token kind starts a simple-type-specifier. |
119 | bool 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 | case tok::kw_char8_t: |
152 | return getLangOpts().Char8; |
153 | |
154 | default: |
155 | break; |
156 | } |
157 | |
158 | return false; |
159 | } |
160 | |
161 | namespace { |
162 | enum class UnqualifiedTypeNameLookupResult { |
163 | NotFound, |
164 | FoundNonType, |
165 | FoundType |
166 | }; |
167 | } // end anonymous namespace |
168 | |
169 | /// Tries to perform unqualified lookup of the type decls in bases for |
170 | /// dependent class. |
171 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a |
172 | /// type decl, \a FoundType if only type decls are found. |
173 | static UnqualifiedTypeNameLookupResult |
174 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, |
175 | SourceLocation NameLoc, |
176 | const CXXRecordDecl *RD) { |
177 | if (!RD->hasDefinition()) |
178 | return UnqualifiedTypeNameLookupResult::NotFound; |
179 | // Look for type decls in base classes. |
180 | UnqualifiedTypeNameLookupResult FoundTypeDecl = |
181 | UnqualifiedTypeNameLookupResult::NotFound; |
182 | for (const auto &Base : RD->bases()) { |
183 | const CXXRecordDecl *BaseRD = nullptr; |
184 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) |
185 | BaseRD = BaseTT->getAsCXXRecordDecl(); |
186 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { |
187 | // Look for type decls in dependent base classes that have known primary |
188 | // templates. |
189 | if (!TST || !TST->isDependentType()) |
190 | continue; |
191 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); |
192 | if (!TD) |
193 | continue; |
194 | if (auto *BasePrimaryTemplate = |
195 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { |
196 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) |
197 | BaseRD = BasePrimaryTemplate; |
198 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { |
199 | if (const ClassTemplatePartialSpecializationDecl *PS = |
200 | CTD->findPartialSpecialization(Base.getType())) |
201 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) |
202 | BaseRD = PS; |
203 | } |
204 | } |
205 | } |
206 | if (BaseRD) { |
207 | for (NamedDecl *ND : BaseRD->lookup(&II)) { |
208 | if (!isa<TypeDecl>(ND)) |
209 | return UnqualifiedTypeNameLookupResult::FoundNonType; |
210 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; |
211 | } |
212 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { |
213 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { |
214 | case UnqualifiedTypeNameLookupResult::FoundNonType: |
215 | return UnqualifiedTypeNameLookupResult::FoundNonType; |
216 | case UnqualifiedTypeNameLookupResult::FoundType: |
217 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; |
218 | break; |
219 | case UnqualifiedTypeNameLookupResult::NotFound: |
220 | break; |
221 | } |
222 | } |
223 | } |
224 | } |
225 | |
226 | return FoundTypeDecl; |
227 | } |
228 | |
229 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, |
230 | const IdentifierInfo &II, |
231 | SourceLocation NameLoc) { |
232 | // Lookup in the parent class template context, if any. |
233 | const CXXRecordDecl *RD = nullptr; |
234 | UnqualifiedTypeNameLookupResult FoundTypeDecl = |
235 | UnqualifiedTypeNameLookupResult::NotFound; |
236 | for (DeclContext *DC = S.CurContext; |
237 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; |
238 | DC = DC->getParent()) { |
239 | // Look for type decls in dependent base classes that have known primary |
240 | // templates. |
241 | RD = dyn_cast<CXXRecordDecl>(DC); |
242 | if (RD && RD->getDescribedClassTemplate()) |
243 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); |
244 | } |
245 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) |
246 | return nullptr; |
247 | |
248 | // We found some types in dependent base classes. Recover as if the user |
249 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the |
250 | // lookup during template instantiation. |
251 | S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; |
252 | |
253 | ASTContext &Context = S.Context; |
254 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, |
255 | cast<Type>(Context.getRecordType(RD))); |
256 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); |
257 | |
258 | CXXScopeSpec SS; |
259 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); |
260 | |
261 | TypeLocBuilder Builder; |
262 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); |
263 | DepTL.setNameLoc(NameLoc); |
264 | DepTL.setElaboratedKeywordLoc(SourceLocation()); |
265 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
266 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
267 | } |
268 | |
269 | /// If the identifier refers to a type name within this scope, |
270 | /// return the declaration of that type. |
271 | /// |
272 | /// This routine performs ordinary name lookup of the identifier II |
273 | /// within the given scope, with optional C++ scope specifier SS, to |
274 | /// determine whether the name refers to a type. If so, returns an |
275 | /// opaque pointer (actually a QualType) corresponding to that |
276 | /// type. Otherwise, returns NULL. |
277 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, |
278 | Scope *S, CXXScopeSpec *SS, |
279 | bool isClassName, bool HasTrailingDot, |
280 | ParsedType ObjectTypePtr, |
281 | bool IsCtorOrDtorName, |
282 | bool WantNontrivialTypeSourceInfo, |
283 | bool IsClassTemplateDeductionContext, |
284 | IdentifierInfo **CorrectedII) { |
285 | // FIXME: Consider allowing this outside C++1z mode as an extension. |
286 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && |
287 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && |
288 | !isClassName && !HasTrailingDot; |
289 | |
290 | // Determine where we will perform name lookup. |
291 | DeclContext *LookupCtx = nullptr; |
292 | if (ObjectTypePtr) { |
293 | QualType ObjectType = ObjectTypePtr.get(); |
294 | if (ObjectType->isRecordType()) |
295 | LookupCtx = computeDeclContext(ObjectType); |
296 | } else if (SS && SS->isNotEmpty()) { |
297 | LookupCtx = computeDeclContext(*SS, false); |
298 | |
299 | if (!LookupCtx) { |
300 | if (isDependentScopeSpecifier(*SS)) { |
301 | // C++ [temp.res]p3: |
302 | // A qualified-id that refers to a type and in which the |
303 | // nested-name-specifier depends on a template-parameter (14.6.2) |
304 | // shall be prefixed by the keyword typename to indicate that the |
305 | // qualified-id denotes a type, forming an |
306 | // elaborated-type-specifier (7.1.5.3). |
307 | // |
308 | // We therefore do not perform any name lookup if the result would |
309 | // refer to a member of an unknown specialization. |
310 | if (!isClassName && !IsCtorOrDtorName) |
311 | return nullptr; |
312 | |
313 | // We know from the grammar that this name refers to a type, |
314 | // so build a dependent node to describe the type. |
315 | if (WantNontrivialTypeSourceInfo) |
316 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); |
317 | |
318 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); |
319 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, |
320 | II, NameLoc); |
321 | return ParsedType::make(T); |
322 | } |
323 | |
324 | return nullptr; |
325 | } |
326 | |
327 | if (!LookupCtx->isDependentContext() && |
328 | RequireCompleteDeclContext(*SS, LookupCtx)) |
329 | return nullptr; |
330 | } |
331 | |
332 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of |
333 | // lookup for class-names. |
334 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : |
335 | LookupOrdinaryName; |
336 | LookupResult Result(*this, &II, NameLoc, Kind); |
337 | if (LookupCtx) { |
338 | // Perform "qualified" name lookup into the declaration context we |
339 | // computed, which is either the type of the base of a member access |
340 | // expression or the declaration context associated with a prior |
341 | // nested-name-specifier. |
342 | LookupQualifiedName(Result, LookupCtx); |
343 | |
344 | if (ObjectTypePtr && Result.empty()) { |
345 | // C++ [basic.lookup.classref]p3: |
346 | // If the unqualified-id is ~type-name, the type-name is looked up |
347 | // in the context of the entire postfix-expression. If the type T of |
348 | // the object expression is of a class type C, the type-name is also |
349 | // looked up in the scope of class C. At least one of the lookups shall |
350 | // find a name that refers to (possibly cv-qualified) T. |
351 | LookupName(Result, S); |
352 | } |
353 | } else { |
354 | // Perform unqualified name lookup. |
355 | LookupName(Result, S); |
356 | |
357 | // For unqualified lookup in a class template in MSVC mode, look into |
358 | // dependent base classes where the primary class template is known. |
359 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { |
360 | if (ParsedType TypeInBase = |
361 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) |
362 | return TypeInBase; |
363 | } |
364 | } |
365 | |
366 | NamedDecl *IIDecl = nullptr; |
367 | switch (Result.getResultKind()) { |
368 | case LookupResult::NotFound: |
369 | case LookupResult::NotFoundInCurrentInstantiation: |
370 | if (CorrectedII) { |
371 | TypoCorrection Correction = |
372 | CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, |
373 | llvm::make_unique<TypeNameValidatorCCC>( |
374 | true, isClassName, AllowDeducedTemplate), |
375 | CTK_ErrorRecovery); |
376 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); |
377 | TemplateTy Template; |
378 | bool MemberOfUnknownSpecialization; |
379 | UnqualifiedId TemplateName; |
380 | TemplateName.setIdentifier(NewII, NameLoc); |
381 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); |
382 | CXXScopeSpec NewSS, *NewSSPtr = SS; |
383 | if (SS && NNS) { |
384 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); |
385 | NewSSPtr = &NewSS; |
386 | } |
387 | if (Correction && (NNS || NewII != &II) && |
388 | // Ignore a correction to a template type as the to-be-corrected |
389 | // identifier is not a template (typo correction for template names |
390 | // is handled elsewhere). |
391 | !(getLangOpts().CPlusPlus && NewSSPtr && |
392 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, |
393 | Template, MemberOfUnknownSpecialization))) { |
394 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, |
395 | isClassName, HasTrailingDot, ObjectTypePtr, |
396 | IsCtorOrDtorName, |
397 | WantNontrivialTypeSourceInfo, |
398 | IsClassTemplateDeductionContext); |
399 | if (Ty) { |
400 | diagnoseTypo(Correction, |
401 | PDiag(diag::err_unknown_type_or_class_name_suggest) |
402 | << Result.getLookupName() << isClassName); |
403 | if (SS && NNS) |
404 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); |
405 | *CorrectedII = NewII; |
406 | return Ty; |
407 | } |
408 | } |
409 | } |
410 | // If typo correction failed or was not performed, fall through |
411 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
412 | case LookupResult::FoundOverloaded: |
413 | case LookupResult::FoundUnresolvedValue: |
414 | Result.suppressDiagnostics(); |
415 | return nullptr; |
416 | |
417 | case LookupResult::Ambiguous: |
418 | // Recover from type-hiding ambiguities by hiding the type. We'll |
419 | // do the lookup again when looking for an object, and we can |
420 | // diagnose the error then. If we don't do this, then the error |
421 | // about hiding the type will be immediately followed by an error |
422 | // that only makes sense if the identifier was treated like a type. |
423 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { |
424 | Result.suppressDiagnostics(); |
425 | return nullptr; |
426 | } |
427 | |
428 | // Look to see if we have a type anywhere in the list of results. |
429 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); |
430 | Res != ResEnd; ++Res) { |
431 | if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || |
432 | (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { |
433 | if (!IIDecl || |
434 | (*Res)->getLocation().getRawEncoding() < |
435 | IIDecl->getLocation().getRawEncoding()) |
436 | IIDecl = *Res; |
437 | } |
438 | } |
439 | |
440 | if (!IIDecl) { |
441 | // None of the entities we found is a type, so there is no way |
442 | // to even assume that the result is a type. In this case, don't |
443 | // complain about the ambiguity. The parser will either try to |
444 | // perform this lookup again (e.g., as an object name), which |
445 | // will produce the ambiguity, or will complain that it expected |
446 | // a type name. |
447 | Result.suppressDiagnostics(); |
448 | return nullptr; |
449 | } |
450 | |
451 | // We found a type within the ambiguous lookup; diagnose the |
452 | // ambiguity and then return that type. This might be the right |
453 | // answer, or it might not be, but it suppresses any attempt to |
454 | // perform the name lookup again. |
455 | break; |
456 | |
457 | case LookupResult::Found: |
458 | IIDecl = Result.getFoundDecl(); |
459 | break; |
460 | } |
461 | |
462 | assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void > (0) : __assert_fail ("IIDecl && \"Didn't find decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 462, __PRETTY_FUNCTION__)); |
463 | |
464 | QualType T; |
465 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { |
466 | // C++ [class.qual]p2: A lookup that would find the injected-class-name |
467 | // instead names the constructors of the class, except when naming a class. |
468 | // This is ill-formed when we're not actually forming a ctor or dtor name. |
469 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); |
470 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); |
471 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && |
472 | FoundRD->isInjectedClassName() && |
473 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) |
474 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) |
475 | << &II << /*Type*/1; |
476 | |
477 | DiagnoseUseOfDecl(IIDecl, NameLoc); |
478 | |
479 | T = Context.getTypeDeclType(TD); |
480 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); |
481 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { |
482 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); |
483 | if (!HasTrailingDot) |
484 | T = Context.getObjCInterfaceType(IDecl); |
485 | } else if (AllowDeducedTemplate) { |
486 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) |
487 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), |
488 | QualType(), false); |
489 | } |
490 | |
491 | if (T.isNull()) { |
492 | // If it's not plausibly a type, suppress diagnostics. |
493 | Result.suppressDiagnostics(); |
494 | return nullptr; |
495 | } |
496 | |
497 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a |
498 | // constructor or destructor name (in such a case, the scope specifier |
499 | // will be attached to the enclosing Expr or Decl node). |
500 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && |
501 | !isa<ObjCInterfaceDecl>(IIDecl)) { |
502 | if (WantNontrivialTypeSourceInfo) { |
503 | // Construct a type with type-source information. |
504 | TypeLocBuilder Builder; |
505 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); |
506 | |
507 | T = getElaboratedType(ETK_None, *SS, T); |
508 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); |
509 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
510 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); |
511 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
512 | } else { |
513 | T = getElaboratedType(ETK_None, *SS, T); |
514 | } |
515 | } |
516 | |
517 | return ParsedType::make(T); |
518 | } |
519 | |
520 | // Builds a fake NNS for the given decl context. |
521 | static NestedNameSpecifier * |
522 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { |
523 | for (;; DC = DC->getLookupParent()) { |
524 | DC = DC->getPrimaryContext(); |
525 | auto *ND = dyn_cast<NamespaceDecl>(DC); |
526 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) |
527 | return NestedNameSpecifier::Create(Context, nullptr, ND); |
528 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) |
529 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), |
530 | RD->getTypeForDecl()); |
531 | else if (isa<TranslationUnitDecl>(DC)) |
532 | return NestedNameSpecifier::GlobalSpecifier(Context); |
533 | } |
534 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 534); |
535 | } |
536 | |
537 | /// Find the parent class with dependent bases of the innermost enclosing method |
538 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end |
539 | /// up allowing unqualified dependent type names at class-level, which MSVC |
540 | /// correctly rejects. |
541 | static const CXXRecordDecl * |
542 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { |
543 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { |
544 | DC = DC->getPrimaryContext(); |
545 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) |
546 | if (MD->getParent()->hasAnyDependentBases()) |
547 | return MD->getParent(); |
548 | } |
549 | return nullptr; |
550 | } |
551 | |
552 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, |
553 | SourceLocation NameLoc, |
554 | bool IsTemplateTypeArg) { |
555 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 555, __PRETTY_FUNCTION__)); |
556 | |
557 | NestedNameSpecifier *NNS = nullptr; |
558 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { |
559 | // If we weren't able to parse a default template argument, delay lookup |
560 | // until instantiation time by making a non-dependent DependentTypeName. We |
561 | // pretend we saw a NestedNameSpecifier referring to the current scope, and |
562 | // lookup is retried. |
563 | // FIXME: This hurts our diagnostic quality, since we get errors like "no |
564 | // type named 'Foo' in 'current_namespace'" when the user didn't write any |
565 | // name specifiers. |
566 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); |
567 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; |
568 | } else if (const CXXRecordDecl *RD = |
569 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { |
570 | // Build a DependentNameType that will perform lookup into RD at |
571 | // instantiation time. |
572 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), |
573 | RD->getTypeForDecl()); |
574 | |
575 | // Diagnose that this identifier was undeclared, and retry the lookup during |
576 | // template instantiation. |
577 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II |
578 | << RD; |
579 | } else { |
580 | // This is not a situation that we should recover from. |
581 | return ParsedType(); |
582 | } |
583 | |
584 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); |
585 | |
586 | // Build type location information. We synthesized the qualifier, so we have |
587 | // to build a fake NestedNameSpecifierLoc. |
588 | NestedNameSpecifierLocBuilder NNSLocBuilder; |
589 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); |
590 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); |
591 | |
592 | TypeLocBuilder Builder; |
593 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); |
594 | DepTL.setNameLoc(NameLoc); |
595 | DepTL.setElaboratedKeywordLoc(SourceLocation()); |
596 | DepTL.setQualifierLoc(QualifierLoc); |
597 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
598 | } |
599 | |
600 | /// isTagName() - This method is called *for error recovery purposes only* |
601 | /// to determine if the specified name is a valid tag name ("struct foo"). If |
602 | /// so, this returns the TST for the tag corresponding to it (TST_enum, |
603 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose |
604 | /// cases in C where the user forgot to specify the tag. |
605 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { |
606 | // Do a tag name lookup in this scope. |
607 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); |
608 | LookupName(R, S, false); |
609 | R.suppressDiagnostics(); |
610 | if (R.getResultKind() == LookupResult::Found) |
611 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { |
612 | switch (TD->getTagKind()) { |
613 | case TTK_Struct: return DeclSpec::TST_struct; |
614 | case TTK_Interface: return DeclSpec::TST_interface; |
615 | case TTK_Union: return DeclSpec::TST_union; |
616 | case TTK_Class: return DeclSpec::TST_class; |
617 | case TTK_Enum: return DeclSpec::TST_enum; |
618 | } |
619 | } |
620 | |
621 | return DeclSpec::TST_unspecified; |
622 | } |
623 | |
624 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, |
625 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes |
626 | /// then downgrade the missing typename error to a warning. |
627 | /// This is needed for MSVC compatibility; Example: |
628 | /// @code |
629 | /// template<class T> class A { |
630 | /// public: |
631 | /// typedef int TYPE; |
632 | /// }; |
633 | /// template<class T> class B : public A<T> { |
634 | /// public: |
635 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. |
636 | /// }; |
637 | /// @endcode |
638 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { |
639 | if (CurContext->isRecord()) { |
640 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) |
641 | return true; |
642 | |
643 | const Type *Ty = SS->getScopeRep()->getAsType(); |
644 | |
645 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); |
646 | for (const auto &Base : RD->bases()) |
647 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) |
648 | return true; |
649 | return S->isFunctionPrototypeScope(); |
650 | } |
651 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); |
652 | } |
653 | |
654 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, |
655 | SourceLocation IILoc, |
656 | Scope *S, |
657 | CXXScopeSpec *SS, |
658 | ParsedType &SuggestedType, |
659 | bool IsTemplateName) { |
660 | // Don't report typename errors for editor placeholders. |
661 | if (II->isEditorPlaceholder()) |
662 | return; |
663 | // We don't have anything to suggest (yet). |
664 | SuggestedType = nullptr; |
665 | |
666 | // There may have been a typo in the name of the type. Look up typo |
667 | // results, in case we have something that we can suggest. |
668 | if (TypoCorrection Corrected = |
669 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, |
670 | llvm::make_unique<TypeNameValidatorCCC>( |
671 | false, false, IsTemplateName, !IsTemplateName), |
672 | CTK_ErrorRecovery)) { |
673 | // FIXME: Support error recovery for the template-name case. |
674 | bool CanRecover = !IsTemplateName; |
675 | if (Corrected.isKeyword()) { |
676 | // We corrected to a keyword. |
677 | diagnoseTypo(Corrected, |
678 | PDiag(IsTemplateName ? diag::err_no_template_suggest |
679 | : diag::err_unknown_typename_suggest) |
680 | << II); |
681 | II = Corrected.getCorrectionAsIdentifierInfo(); |
682 | } else { |
683 | // We found a similarly-named type or interface; suggest that. |
684 | if (!SS || !SS->isSet()) { |
685 | diagnoseTypo(Corrected, |
686 | PDiag(IsTemplateName ? diag::err_no_template_suggest |
687 | : diag::err_unknown_typename_suggest) |
688 | << II, CanRecover); |
689 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { |
690 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
691 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
692 | II->getName().equals(CorrectedStr); |
693 | diagnoseTypo(Corrected, |
694 | PDiag(IsTemplateName |
695 | ? diag::err_no_member_template_suggest |
696 | : diag::err_unknown_nested_typename_suggest) |
697 | << II << DC << DroppedSpecifier << SS->getRange(), |
698 | CanRecover); |
699 | } else { |
700 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 700); |
701 | } |
702 | |
703 | if (!CanRecover) |
704 | return; |
705 | |
706 | CXXScopeSpec tmpSS; |
707 | if (Corrected.getCorrectionSpecifier()) |
708 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), |
709 | SourceRange(IILoc)); |
710 | // FIXME: Support class template argument deduction here. |
711 | SuggestedType = |
712 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, |
713 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, |
714 | /*IsCtorOrDtorName=*/false, |
715 | /*NonTrivialTypeSourceInfo=*/true); |
716 | } |
717 | return; |
718 | } |
719 | |
720 | if (getLangOpts().CPlusPlus && !IsTemplateName) { |
721 | // See if II is a class template that the user forgot to pass arguments to. |
722 | UnqualifiedId Name; |
723 | Name.setIdentifier(II, IILoc); |
724 | CXXScopeSpec EmptySS; |
725 | TemplateTy TemplateResult; |
726 | bool MemberOfUnknownSpecialization; |
727 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, |
728 | Name, nullptr, true, TemplateResult, |
729 | MemberOfUnknownSpecialization) == TNK_Type_template) { |
730 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); |
731 | return; |
732 | } |
733 | } |
734 | |
735 | // FIXME: Should we move the logic that tries to recover from a missing tag |
736 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? |
737 | |
738 | if (!SS || (!SS->isSet() && !SS->isInvalid())) |
739 | Diag(IILoc, IsTemplateName ? diag::err_no_template |
740 | : diag::err_unknown_typename) |
741 | << II; |
742 | else if (DeclContext *DC = computeDeclContext(*SS, false)) |
743 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template |
744 | : diag::err_typename_nested_not_found) |
745 | << II << DC << SS->getRange(); |
746 | else if (isDependentScopeSpecifier(*SS)) { |
747 | unsigned DiagID = diag::err_typename_missing; |
748 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) |
749 | DiagID = diag::ext_typename_missing; |
750 | |
751 | Diag(SS->getRange().getBegin(), DiagID) |
752 | << SS->getScopeRep() << II->getName() |
753 | << SourceRange(SS->getRange().getBegin(), IILoc) |
754 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); |
755 | SuggestedType = ActOnTypenameType(S, SourceLocation(), |
756 | *SS, *II, IILoc).get(); |
757 | } else { |
758 | assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 759, __PRETTY_FUNCTION__)) |
759 | "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 759, __PRETTY_FUNCTION__)); |
760 | } |
761 | } |
762 | |
763 | /// Determine whether the given result set contains either a type name |
764 | /// or |
765 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { |
766 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && |
767 | NextToken.is(tok::less); |
768 | |
769 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { |
770 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) |
771 | return true; |
772 | |
773 | if (CheckTemplate && isa<TemplateDecl>(*I)) |
774 | return true; |
775 | } |
776 | |
777 | return false; |
778 | } |
779 | |
780 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, |
781 | Scope *S, CXXScopeSpec &SS, |
782 | IdentifierInfo *&Name, |
783 | SourceLocation NameLoc) { |
784 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); |
785 | SemaRef.LookupParsedName(R, S, &SS); |
786 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { |
787 | StringRef FixItTagName; |
788 | switch (Tag->getTagKind()) { |
789 | case TTK_Class: |
790 | FixItTagName = "class "; |
791 | break; |
792 | |
793 | case TTK_Enum: |
794 | FixItTagName = "enum "; |
795 | break; |
796 | |
797 | case TTK_Struct: |
798 | FixItTagName = "struct "; |
799 | break; |
800 | |
801 | case TTK_Interface: |
802 | FixItTagName = "__interface "; |
803 | break; |
804 | |
805 | case TTK_Union: |
806 | FixItTagName = "union "; |
807 | break; |
808 | } |
809 | |
810 | StringRef TagName = FixItTagName.drop_back(); |
811 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) |
812 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus |
813 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); |
814 | |
815 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); |
816 | I != IEnd; ++I) |
817 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) |
818 | << Name << TagName; |
819 | |
820 | // Replace lookup results with just the tag decl. |
821 | Result.clear(Sema::LookupTagName); |
822 | SemaRef.LookupParsedName(Result, S, &SS); |
823 | return true; |
824 | } |
825 | |
826 | return false; |
827 | } |
828 | |
829 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. |
830 | static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, |
831 | QualType T, SourceLocation NameLoc) { |
832 | ASTContext &Context = S.Context; |
833 | |
834 | TypeLocBuilder Builder; |
835 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); |
836 | |
837 | T = S.getElaboratedType(ETK_None, SS, T); |
838 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); |
839 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); |
840 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); |
841 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); |
842 | } |
843 | |
844 | Sema::NameClassification |
845 | Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, |
846 | SourceLocation NameLoc, const Token &NextToken, |
847 | bool IsAddressOfOperand, |
848 | std::unique_ptr<CorrectionCandidateCallback> CCC) { |
849 | DeclarationNameInfo NameInfo(Name, NameLoc); |
850 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); |
851 | |
852 | if (NextToken.is(tok::coloncolon)) { |
853 | NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); |
854 | BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); |
855 | } else if (getLangOpts().CPlusPlus && SS.isSet() && |
856 | isCurrentClassName(*Name, S, &SS)) { |
857 | // Per [class.qual]p2, this names the constructors of SS, not the |
858 | // injected-class-name. We don't have a classification for that. |
859 | // There's not much point caching this result, since the parser |
860 | // will reject it later. |
861 | return NameClassification::Unknown(); |
862 | } |
863 | |
864 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); |
865 | LookupParsedName(Result, S, &SS, !CurMethod); |
866 | |
867 | // For unqualified lookup in a class template in MSVC mode, look into |
868 | // dependent base classes where the primary class template is known. |
869 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { |
870 | if (ParsedType TypeInBase = |
871 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) |
872 | return TypeInBase; |
873 | } |
874 | |
875 | // Perform lookup for Objective-C instance variables (including automatically |
876 | // synthesized instance variables), if we're in an Objective-C method. |
877 | // FIXME: This lookup really, really needs to be folded in to the normal |
878 | // unqualified lookup mechanism. |
879 | if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { |
880 | ExprResult E = LookupInObjCMethod(Result, S, Name, true); |
881 | if (E.get() || E.isInvalid()) |
882 | return E; |
883 | } |
884 | |
885 | bool SecondTry = false; |
886 | bool IsFilteredTemplateName = false; |
887 | |
888 | Corrected: |
889 | switch (Result.getResultKind()) { |
890 | case LookupResult::NotFound: |
891 | // If an unqualified-id is followed by a '(', then we have a function |
892 | // call. |
893 | if (!SS.isSet() && NextToken.is(tok::l_paren)) { |
894 | // In C++, this is an ADL-only call. |
895 | // FIXME: Reference? |
896 | if (getLangOpts().CPlusPlus) |
897 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); |
898 | |
899 | // C90 6.3.2.2: |
900 | // If the expression that precedes the parenthesized argument list in a |
901 | // function call consists solely of an identifier, and if no |
902 | // declaration is visible for this identifier, the identifier is |
903 | // implicitly declared exactly as if, in the innermost block containing |
904 | // the function call, the declaration |
905 | // |
906 | // extern int identifier (); |
907 | // |
908 | // appeared. |
909 | // |
910 | // We also allow this in C99 as an extension. |
911 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { |
912 | Result.addDecl(D); |
913 | Result.resolveKind(); |
914 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); |
915 | } |
916 | } |
917 | |
918 | // In C, we first see whether there is a tag type by the same name, in |
919 | // which case it's likely that the user just forgot to write "enum", |
920 | // "struct", or "union". |
921 | if (!getLangOpts().CPlusPlus && !SecondTry && |
922 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { |
923 | break; |
924 | } |
925 | |
926 | // Perform typo correction to determine if there is another name that is |
927 | // close to this name. |
928 | if (!SecondTry && CCC) { |
929 | SecondTry = true; |
930 | if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), |
931 | Result.getLookupKind(), S, |
932 | &SS, std::move(CCC), |
933 | CTK_ErrorRecovery)) { |
934 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; |
935 | unsigned QualifiedDiag = diag::err_no_member_suggest; |
936 | |
937 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); |
938 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); |
939 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && |
940 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { |
941 | UnqualifiedDiag = diag::err_no_template_suggest; |
942 | QualifiedDiag = diag::err_no_member_template_suggest; |
943 | } else if (UnderlyingFirstDecl && |
944 | (isa<TypeDecl>(UnderlyingFirstDecl) || |
945 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || |
946 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { |
947 | UnqualifiedDiag = diag::err_unknown_typename_suggest; |
948 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; |
949 | } |
950 | |
951 | if (SS.isEmpty()) { |
952 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); |
953 | } else {// FIXME: is this even reachable? Test it. |
954 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); |
955 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && |
956 | Name->getName().equals(CorrectedStr); |
957 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) |
958 | << Name << computeDeclContext(SS, false) |
959 | << DroppedSpecifier << SS.getRange()); |
960 | } |
961 | |
962 | // Update the name, so that the caller has the new name. |
963 | Name = Corrected.getCorrectionAsIdentifierInfo(); |
964 | |
965 | // Typo correction corrected to a keyword. |
966 | if (Corrected.isKeyword()) |
967 | return Name; |
968 | |
969 | // Also update the LookupResult... |
970 | // FIXME: This should probably go away at some point |
971 | Result.clear(); |
972 | Result.setLookupName(Corrected.getCorrection()); |
973 | if (FirstDecl) |
974 | Result.addDecl(FirstDecl); |
975 | |
976 | // If we found an Objective-C instance variable, let |
977 | // LookupInObjCMethod build the appropriate expression to |
978 | // reference the ivar. |
979 | // FIXME: This is a gross hack. |
980 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { |
981 | Result.clear(); |
982 | ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); |
983 | return E; |
984 | } |
985 | |
986 | goto Corrected; |
987 | } |
988 | } |
989 | |
990 | // We failed to correct; just fall through and let the parser deal with it. |
991 | Result.suppressDiagnostics(); |
992 | return NameClassification::Unknown(); |
993 | |
994 | case LookupResult::NotFoundInCurrentInstantiation: { |
995 | // We performed name lookup into the current instantiation, and there were |
996 | // dependent bases, so we treat this result the same way as any other |
997 | // dependent nested-name-specifier. |
998 | |
999 | // C++ [temp.res]p2: |
1000 | // A name used in a template declaration or definition and that is |
1001 | // dependent on a template-parameter is assumed not to name a type |
1002 | // unless the applicable name lookup finds a type name or the name is |
1003 | // qualified by the keyword typename. |
1004 | // |
1005 | // FIXME: If the next token is '<', we might want to ask the parser to |
1006 | // perform some heroics to see if we actually have a |
1007 | // template-argument-list, which would indicate a missing 'template' |
1008 | // keyword here. |
1009 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), |
1010 | NameInfo, IsAddressOfOperand, |
1011 | /*TemplateArgs=*/nullptr); |
1012 | } |
1013 | |
1014 | case LookupResult::Found: |
1015 | case LookupResult::FoundOverloaded: |
1016 | case LookupResult::FoundUnresolvedValue: |
1017 | break; |
1018 | |
1019 | case LookupResult::Ambiguous: |
1020 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && |
1021 | hasAnyAcceptableTemplateNames(Result)) { |
1022 | // C++ [temp.local]p3: |
1023 | // A lookup that finds an injected-class-name (10.2) can result in an |
1024 | // ambiguity in certain cases (for example, if it is found in more than |
1025 | // one base class). If all of the injected-class-names that are found |
1026 | // refer to specializations of the same class template, and if the name |
1027 | // is followed by a template-argument-list, the reference refers to the |
1028 | // class template itself and not a specialization thereof, and is not |
1029 | // ambiguous. |
1030 | // |
1031 | // This filtering can make an ambiguous result into an unambiguous one, |
1032 | // so try again after filtering out template names. |
1033 | FilterAcceptableTemplateNames(Result); |
1034 | if (!Result.isAmbiguous()) { |
1035 | IsFilteredTemplateName = true; |
1036 | break; |
1037 | } |
1038 | } |
1039 | |
1040 | // Diagnose the ambiguity and return an error. |
1041 | return NameClassification::Error(); |
1042 | } |
1043 | |
1044 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && |
1045 | (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { |
1046 | // C++ [temp.names]p3: |
1047 | // After name lookup (3.4) finds that a name is a template-name or that |
1048 | // an operator-function-id or a literal- operator-id refers to a set of |
1049 | // overloaded functions any member of which is a function template if |
1050 | // this is followed by a <, the < is always taken as the delimiter of a |
1051 | // template-argument-list and never as the less-than operator. |
1052 | if (!IsFilteredTemplateName) |
1053 | FilterAcceptableTemplateNames(Result); |
1054 | |
1055 | if (!Result.empty()) { |
1056 | bool IsFunctionTemplate; |
1057 | bool IsVarTemplate; |
1058 | TemplateName Template; |
1059 | if (Result.end() - Result.begin() > 1) { |
1060 | IsFunctionTemplate = true; |
1061 | Template = Context.getOverloadedTemplateName(Result.begin(), |
1062 | Result.end()); |
1063 | } else { |
1064 | TemplateDecl *TD |
1065 | = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); |
1066 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); |
1067 | IsVarTemplate = isa<VarTemplateDecl>(TD); |
1068 | |
1069 | if (SS.isSet() && !SS.isInvalid()) |
1070 | Template = Context.getQualifiedTemplateName(SS.getScopeRep(), |
1071 | /*TemplateKeyword=*/false, |
1072 | TD); |
1073 | else |
1074 | Template = TemplateName(TD); |
1075 | } |
1076 | |
1077 | if (IsFunctionTemplate) { |
1078 | // Function templates always go through overload resolution, at which |
1079 | // point we'll perform the various checks (e.g., accessibility) we need |
1080 | // to based on which function we selected. |
1081 | Result.suppressDiagnostics(); |
1082 | |
1083 | return NameClassification::FunctionTemplate(Template); |
1084 | } |
1085 | |
1086 | return IsVarTemplate ? NameClassification::VarTemplate(Template) |
1087 | : NameClassification::TypeTemplate(Template); |
1088 | } |
1089 | } |
1090 | |
1091 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); |
1092 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { |
1093 | DiagnoseUseOfDecl(Type, NameLoc); |
1094 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); |
1095 | QualType T = Context.getTypeDeclType(Type); |
1096 | if (SS.isNotEmpty()) |
1097 | return buildNestedType(*this, SS, T, NameLoc); |
1098 | return ParsedType::make(T); |
1099 | } |
1100 | |
1101 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); |
1102 | if (!Class) { |
1103 | // FIXME: It's unfortunate that we don't have a Type node for handling this. |
1104 | if (ObjCCompatibleAliasDecl *Alias = |
1105 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) |
1106 | Class = Alias->getClassInterface(); |
1107 | } |
1108 | |
1109 | if (Class) { |
1110 | DiagnoseUseOfDecl(Class, NameLoc); |
1111 | |
1112 | if (NextToken.is(tok::period)) { |
1113 | // Interface. <something> is parsed as a property reference expression. |
1114 | // Just return "unknown" as a fall-through for now. |
1115 | Result.suppressDiagnostics(); |
1116 | return NameClassification::Unknown(); |
1117 | } |
1118 | |
1119 | QualType T = Context.getObjCInterfaceType(Class); |
1120 | return ParsedType::make(T); |
1121 | } |
1122 | |
1123 | // We can have a type template here if we're classifying a template argument. |
1124 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && |
1125 | !isa<VarTemplateDecl>(FirstDecl)) |
1126 | return NameClassification::TypeTemplate( |
1127 | TemplateName(cast<TemplateDecl>(FirstDecl))); |
1128 | |
1129 | // Check for a tag type hidden by a non-type decl in a few cases where it |
1130 | // seems likely a type is wanted instead of the non-type that was found. |
1131 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); |
1132 | if ((NextToken.is(tok::identifier) || |
1133 | (NextIsOp && |
1134 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && |
1135 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { |
1136 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); |
1137 | DiagnoseUseOfDecl(Type, NameLoc); |
1138 | QualType T = Context.getTypeDeclType(Type); |
1139 | if (SS.isNotEmpty()) |
1140 | return buildNestedType(*this, SS, T, NameLoc); |
1141 | return ParsedType::make(T); |
1142 | } |
1143 | |
1144 | if (FirstDecl->isCXXClassMember()) |
1145 | return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, |
1146 | nullptr, S); |
1147 | |
1148 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); |
1149 | return BuildDeclarationNameExpr(SS, Result, ADL); |
1150 | } |
1151 | |
1152 | Sema::TemplateNameKindForDiagnostics |
1153 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { |
1154 | auto *TD = Name.getAsTemplateDecl(); |
1155 | if (!TD) |
1156 | return TemplateNameKindForDiagnostics::DependentTemplate; |
1157 | if (isa<ClassTemplateDecl>(TD)) |
1158 | return TemplateNameKindForDiagnostics::ClassTemplate; |
1159 | if (isa<FunctionTemplateDecl>(TD)) |
1160 | return TemplateNameKindForDiagnostics::FunctionTemplate; |
1161 | if (isa<VarTemplateDecl>(TD)) |
1162 | return TemplateNameKindForDiagnostics::VarTemplate; |
1163 | if (isa<TypeAliasTemplateDecl>(TD)) |
1164 | return TemplateNameKindForDiagnostics::AliasTemplate; |
1165 | if (isa<TemplateTemplateParmDecl>(TD)) |
1166 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; |
1167 | return TemplateNameKindForDiagnostics::DependentTemplate; |
1168 | } |
1169 | |
1170 | // Determines the context to return to after temporarily entering a |
1171 | // context. This depends in an unnecessarily complicated way on the |
1172 | // exact ordering of callbacks from the parser. |
1173 | DeclContext *Sema::getContainingDC(DeclContext *DC) { |
1174 | |
1175 | // Functions defined inline within classes aren't parsed until we've |
1176 | // finished parsing the top-level class, so the top-level class is |
1177 | // the context we'll need to return to. |
1178 | // A Lambda call operator whose parent is a class must not be treated |
1179 | // as an inline member function. A Lambda can be used legally |
1180 | // either as an in-class member initializer or a default argument. These |
1181 | // are parsed once the class has been marked complete and so the containing |
1182 | // context would be the nested class (when the lambda is defined in one); |
1183 | // If the class is not complete, then the lambda is being used in an |
1184 | // ill-formed fashion (such as to specify the width of a bit-field, or |
1185 | // in an array-bound) - in which case we still want to return the |
1186 | // lexically containing DC (which could be a nested class). |
1187 | if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { |
1188 | DC = DC->getLexicalParent(); |
1189 | |
1190 | // A function not defined within a class will always return to its |
1191 | // lexical context. |
1192 | if (!isa<CXXRecordDecl>(DC)) |
1193 | return DC; |
1194 | |
1195 | // A C++ inline method/friend is parsed *after* the topmost class |
1196 | // it was declared in is fully parsed ("complete"); the topmost |
1197 | // class is the context we need to return to. |
1198 | while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) |
1199 | DC = RD; |
1200 | |
1201 | // Return the declaration context of the topmost class the inline method is |
1202 | // declared in. |
1203 | return DC; |
1204 | } |
1205 | |
1206 | return DC->getLexicalParent(); |
1207 | } |
1208 | |
1209 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { |
1210 | assert(getContainingDC(DC) == CurContext &&((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1211, __PRETTY_FUNCTION__)) |
1211 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1211, __PRETTY_FUNCTION__)); |
1212 | CurContext = DC; |
1213 | S->setEntity(DC); |
1214 | } |
1215 | |
1216 | void Sema::PopDeclContext() { |
1217 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1217, __PRETTY_FUNCTION__)); |
1218 | |
1219 | CurContext = getContainingDC(CurContext); |
1220 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1220, __PRETTY_FUNCTION__)); |
1221 | } |
1222 | |
1223 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, |
1224 | Decl *D) { |
1225 | // Unlike PushDeclContext, the context to which we return is not necessarily |
1226 | // the containing DC of TD, because the new context will be some pre-existing |
1227 | // TagDecl definition instead of a fresh one. |
1228 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); |
1229 | CurContext = cast<TagDecl>(D)->getDefinition(); |
1230 | assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag" ) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1230, __PRETTY_FUNCTION__)); |
1231 | // Start lookups from the parent of the current context; we don't want to look |
1232 | // into the pre-existing complete definition. |
1233 | S->setEntity(CurContext->getLookupParent()); |
1234 | return Result; |
1235 | } |
1236 | |
1237 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { |
1238 | CurContext = static_cast<decltype(CurContext)>(Context); |
1239 | } |
1240 | |
1241 | /// EnterDeclaratorContext - Used when we must lookup names in the context |
1242 | /// of a declarator's nested name specifier. |
1243 | /// |
1244 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { |
1245 | // C++0x [basic.lookup.unqual]p13: |
1246 | // A name used in the definition of a static data member of class |
1247 | // X (after the qualified-id of the static member) is looked up as |
1248 | // if the name was used in a member function of X. |
1249 | // C++0x [basic.lookup.unqual]p14: |
1250 | // If a variable member of a namespace is defined outside of the |
1251 | // scope of its namespace then any name used in the definition of |
1252 | // the variable member (after the declarator-id) is looked up as |
1253 | // if the definition of the variable member occurred in its |
1254 | // namespace. |
1255 | // Both of these imply that we should push a scope whose context |
1256 | // is the semantic context of the declaration. We can't use |
1257 | // PushDeclContext here because that context is not necessarily |
1258 | // lexically contained in the current context. Fortunately, |
1259 | // the containing scope should have the appropriate information. |
1260 | |
1261 | assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ? static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1261, __PRETTY_FUNCTION__)); |
1262 | |
1263 | #ifndef NDEBUG |
1264 | Scope *Ancestor = S->getParent(); |
1265 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); |
1266 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch" ) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1266, __PRETTY_FUNCTION__)); |
1267 | #endif |
1268 | |
1269 | CurContext = DC; |
1270 | S->setEntity(DC); |
1271 | } |
1272 | |
1273 | void Sema::ExitDeclaratorContext(Scope *S) { |
1274 | assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!" ) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1274, __PRETTY_FUNCTION__)); |
1275 | |
1276 | // Switch back to the lexical context. The safety of this is |
1277 | // enforced by an assert in EnterDeclaratorContext. |
1278 | Scope *Ancestor = S->getParent(); |
1279 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); |
1280 | CurContext = Ancestor->getEntity(); |
1281 | |
1282 | // We don't need to do anything with the scope, which is going to |
1283 | // disappear. |
1284 | } |
1285 | |
1286 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { |
1287 | // We assume that the caller has already called |
1288 | // ActOnReenterTemplateScope so getTemplatedDecl() works. |
1289 | FunctionDecl *FD = D->getAsFunction(); |
1290 | if (!FD) |
1291 | return; |
1292 | |
1293 | // Same implementation as PushDeclContext, but enters the context |
1294 | // from the lexical parent, rather than the top-level class. |
1295 | assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1296, __PRETTY_FUNCTION__)) |
1296 | "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1296, __PRETTY_FUNCTION__)); |
1297 | CurContext = FD; |
1298 | S->setEntity(CurContext); |
1299 | |
1300 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { |
1301 | ParmVarDecl *Param = FD->getParamDecl(P); |
1302 | // If the parameter has an identifier, then add it to the scope |
1303 | if (Param->getIdentifier()) { |
1304 | S->AddDecl(Param); |
1305 | IdResolver.AddDecl(Param); |
1306 | } |
1307 | } |
1308 | } |
1309 | |
1310 | void Sema::ActOnExitFunctionContext() { |
1311 | // Same implementation as PopDeclContext, but returns to the lexical parent, |
1312 | // rather than the top-level class. |
1313 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1313, __PRETTY_FUNCTION__)); |
1314 | CurContext = CurContext->getLexicalParent(); |
1315 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1315, __PRETTY_FUNCTION__)); |
1316 | } |
1317 | |
1318 | /// Determine whether we allow overloading of the function |
1319 | /// PrevDecl with another declaration. |
1320 | /// |
1321 | /// This routine determines whether overloading is possible, not |
1322 | /// whether some new function is actually an overload. It will return |
1323 | /// true in C++ (where we can always provide overloads) or, as an |
1324 | /// extension, in C when the previous function is already an |
1325 | /// overloaded function declaration or has the "overloadable" |
1326 | /// attribute. |
1327 | static bool AllowOverloadingOfFunction(LookupResult &Previous, |
1328 | ASTContext &Context, |
1329 | const FunctionDecl *New) { |
1330 | if (Context.getLangOpts().CPlusPlus) |
1331 | return true; |
1332 | |
1333 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) |
1334 | return true; |
1335 | |
1336 | return Previous.getResultKind() == LookupResult::Found && |
1337 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || |
1338 | New->hasAttr<OverloadableAttr>()); |
1339 | } |
1340 | |
1341 | /// Add this decl to the scope shadowed decl chains. |
1342 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { |
1343 | // Move up the scope chain until we find the nearest enclosing |
1344 | // non-transparent context. The declaration will be introduced into this |
1345 | // scope. |
1346 | while (S->getEntity() && S->getEntity()->isTransparentContext()) |
1347 | S = S->getParent(); |
1348 | |
1349 | // Add scoped declarations into their context, so that they can be |
1350 | // found later. Declarations without a context won't be inserted |
1351 | // into any context. |
1352 | if (AddToContext) |
1353 | CurContext->addDecl(D); |
1354 | |
1355 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they |
1356 | // are function-local declarations. |
1357 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && |
1358 | !D->getDeclContext()->getRedeclContext()->Equals( |
1359 | D->getLexicalDeclContext()->getRedeclContext()) && |
1360 | !D->getLexicalDeclContext()->isFunctionOrMethod()) |
1361 | return; |
1362 | |
1363 | // Template instantiations should also not be pushed into scope. |
1364 | if (isa<FunctionDecl>(D) && |
1365 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) |
1366 | return; |
1367 | |
1368 | // If this replaces anything in the current scope, |
1369 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), |
1370 | IEnd = IdResolver.end(); |
1371 | for (; I != IEnd; ++I) { |
1372 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { |
1373 | S->RemoveDecl(*I); |
1374 | IdResolver.RemoveDecl(*I); |
1375 | |
1376 | // Should only need to replace one decl. |
1377 | break; |
1378 | } |
1379 | } |
1380 | |
1381 | S->AddDecl(D); |
1382 | |
1383 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { |
1384 | // Implicitly-generated labels may end up getting generated in an order that |
1385 | // isn't strictly lexical, which breaks name lookup. Be careful to insert |
1386 | // the label at the appropriate place in the identifier chain. |
1387 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { |
1388 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); |
1389 | if (IDC == CurContext) { |
1390 | if (!S->isDeclScope(*I)) |
1391 | continue; |
1392 | } else if (IDC->Encloses(CurContext)) |
1393 | break; |
1394 | } |
1395 | |
1396 | IdResolver.InsertDeclAfter(I, D); |
1397 | } else { |
1398 | IdResolver.AddDecl(D); |
1399 | } |
1400 | } |
1401 | |
1402 | void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { |
1403 | if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) |
1404 | TUScope->AddDecl(D); |
1405 | } |
1406 | |
1407 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, |
1408 | bool AllowInlineNamespace) { |
1409 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); |
1410 | } |
1411 | |
1412 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { |
1413 | DeclContext *TargetDC = DC->getPrimaryContext(); |
1414 | do { |
1415 | if (DeclContext *ScopeDC = S->getEntity()) |
1416 | if (ScopeDC->getPrimaryContext() == TargetDC) |
1417 | return S; |
1418 | } while ((S = S->getParent())); |
1419 | |
1420 | return nullptr; |
1421 | } |
1422 | |
1423 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, |
1424 | DeclContext*, |
1425 | ASTContext&); |
1426 | |
1427 | /// Filters out lookup results that don't fall within the given scope |
1428 | /// as determined by isDeclInScope. |
1429 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, |
1430 | bool ConsiderLinkage, |
1431 | bool AllowInlineNamespace) { |
1432 | LookupResult::Filter F = R.makeFilter(); |
1433 | while (F.hasNext()) { |
1434 | NamedDecl *D = F.next(); |
1435 | |
1436 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) |
1437 | continue; |
1438 | |
1439 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) |
1440 | continue; |
1441 | |
1442 | F.erase(); |
1443 | } |
1444 | |
1445 | F.done(); |
1446 | } |
1447 | |
1448 | /// We've determined that \p New is a redeclaration of \p Old. Check that they |
1449 | /// have compatible owning modules. |
1450 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { |
1451 | // FIXME: The Modules TS is not clear about how friend declarations are |
1452 | // to be treated. It's not meaningful to have different owning modules for |
1453 | // linkage in redeclarations of the same entity, so for now allow the |
1454 | // redeclaration and change the owning modules to match. |
1455 | if (New->getFriendObjectKind() && |
1456 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { |
1457 | New->setLocalOwningModule(Old->getOwningModule()); |
1458 | makeMergedDefinitionVisible(New); |
1459 | return false; |
1460 | } |
1461 | |
1462 | Module *NewM = New->getOwningModule(); |
1463 | Module *OldM = Old->getOwningModule(); |
1464 | if (NewM == OldM) |
1465 | return false; |
1466 | |
1467 | // FIXME: Check proclaimed-ownership-declarations here too. |
1468 | bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; |
1469 | bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; |
1470 | if (NewIsModuleInterface || OldIsModuleInterface) { |
1471 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: |
1472 | // if a declaration of D [...] appears in the purview of a module, all |
1473 | // other such declarations shall appear in the purview of the same module |
1474 | Diag(New->getLocation(), diag::err_mismatched_owning_module) |
1475 | << New |
1476 | << NewIsModuleInterface |
1477 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") |
1478 | << OldIsModuleInterface |
1479 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); |
1480 | Diag(Old->getLocation(), diag::note_previous_declaration); |
1481 | New->setInvalidDecl(); |
1482 | return true; |
1483 | } |
1484 | |
1485 | return false; |
1486 | } |
1487 | |
1488 | static bool isUsingDecl(NamedDecl *D) { |
1489 | return isa<UsingShadowDecl>(D) || |
1490 | isa<UnresolvedUsingTypenameDecl>(D) || |
1491 | isa<UnresolvedUsingValueDecl>(D); |
1492 | } |
1493 | |
1494 | /// Removes using shadow declarations from the lookup results. |
1495 | static void RemoveUsingDecls(LookupResult &R) { |
1496 | LookupResult::Filter F = R.makeFilter(); |
1497 | while (F.hasNext()) |
1498 | if (isUsingDecl(F.next())) |
1499 | F.erase(); |
1500 | |
1501 | F.done(); |
1502 | } |
1503 | |
1504 | /// Check for this common pattern: |
1505 | /// @code |
1506 | /// class S { |
1507 | /// S(const S&); // DO NOT IMPLEMENT |
1508 | /// void operator=(const S&); // DO NOT IMPLEMENT |
1509 | /// }; |
1510 | /// @endcode |
1511 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { |
1512 | // FIXME: Should check for private access too but access is set after we get |
1513 | // the decl here. |
1514 | if (D->doesThisDeclarationHaveABody()) |
1515 | return false; |
1516 | |
1517 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) |
1518 | return CD->isCopyConstructor(); |
1519 | return D->isCopyAssignmentOperator(); |
1520 | } |
1521 | |
1522 | // We need this to handle |
1523 | // |
1524 | // typedef struct { |
1525 | // void *foo() { return 0; } |
1526 | // } A; |
1527 | // |
1528 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' |
1529 | // for example. If 'A', foo will have external linkage. If we have '*A', |
1530 | // foo will have no linkage. Since we can't know until we get to the end |
1531 | // of the typedef, this function finds out if D might have non-external linkage. |
1532 | // Callers should verify at the end of the TU if it D has external linkage or |
1533 | // not. |
1534 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { |
1535 | const DeclContext *DC = D->getDeclContext(); |
1536 | while (!DC->isTranslationUnit()) { |
1537 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ |
1538 | if (!RD->hasNameForLinkage()) |
1539 | return true; |
1540 | } |
1541 | DC = DC->getParent(); |
1542 | } |
1543 | |
1544 | return !D->isExternallyVisible(); |
1545 | } |
1546 | |
1547 | // FIXME: This needs to be refactored; some other isInMainFile users want |
1548 | // these semantics. |
1549 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { |
1550 | if (S.TUKind != TU_Complete) |
1551 | return false; |
1552 | return S.SourceMgr.isInMainFile(Loc); |
1553 | } |
1554 | |
1555 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { |
1556 | assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1556, __PRETTY_FUNCTION__)); |
1557 | |
1558 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) |
1559 | return false; |
1560 | |
1561 | // Ignore all entities declared within templates, and out-of-line definitions |
1562 | // of members of class templates. |
1563 | if (D->getDeclContext()->isDependentContext() || |
1564 | D->getLexicalDeclContext()->isDependentContext()) |
1565 | return false; |
1566 | |
1567 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
1568 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
1569 | return false; |
1570 | // A non-out-of-line declaration of a member specialization was implicitly |
1571 | // instantiated; it's the out-of-line declaration that we're interested in. |
1572 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
1573 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) |
1574 | return false; |
1575 | |
1576 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { |
1577 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) |
1578 | return false; |
1579 | } else { |
1580 | // 'static inline' functions are defined in headers; don't warn. |
1581 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) |
1582 | return false; |
1583 | } |
1584 | |
1585 | if (FD->doesThisDeclarationHaveABody() && |
1586 | Context.DeclMustBeEmitted(FD)) |
1587 | return false; |
1588 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { |
1589 | // Constants and utility variables are defined in headers with internal |
1590 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker |
1591 | // like "inline".) |
1592 | if (!isMainFileLoc(*this, VD->getLocation())) |
1593 | return false; |
1594 | |
1595 | if (Context.DeclMustBeEmitted(VD)) |
1596 | return false; |
1597 | |
1598 | if (VD->isStaticDataMember() && |
1599 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
1600 | return false; |
1601 | if (VD->isStaticDataMember() && |
1602 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
1603 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) |
1604 | return false; |
1605 | |
1606 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) |
1607 | return false; |
1608 | } else { |
1609 | return false; |
1610 | } |
1611 | |
1612 | // Only warn for unused decls internal to the translation unit. |
1613 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function |
1614 | // for inline functions defined in the main source file, for instance. |
1615 | return mightHaveNonExternalLinkage(D); |
1616 | } |
1617 | |
1618 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { |
1619 | if (!D) |
1620 | return; |
1621 | |
1622 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { |
1623 | const FunctionDecl *First = FD->getFirstDecl(); |
1624 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) |
1625 | return; // First should already be in the vector. |
1626 | } |
1627 | |
1628 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { |
1629 | const VarDecl *First = VD->getFirstDecl(); |
1630 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) |
1631 | return; // First should already be in the vector. |
1632 | } |
1633 | |
1634 | if (ShouldWarnIfUnusedFileScopedDecl(D)) |
1635 | UnusedFileScopedDecls.push_back(D); |
1636 | } |
1637 | |
1638 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { |
1639 | if (D->isInvalidDecl()) |
1640 | return false; |
1641 | |
1642 | bool Referenced = false; |
1643 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { |
1644 | // For a decomposition declaration, warn if none of the bindings are |
1645 | // referenced, instead of if the variable itself is referenced (which |
1646 | // it is, by the bindings' expressions). |
1647 | for (auto *BD : DD->bindings()) { |
1648 | if (BD->isReferenced()) { |
1649 | Referenced = true; |
1650 | break; |
1651 | } |
1652 | } |
1653 | } else if (!D->getDeclName()) { |
1654 | return false; |
1655 | } else if (D->isReferenced() || D->isUsed()) { |
1656 | Referenced = true; |
1657 | } |
1658 | |
1659 | if (Referenced || D->hasAttr<UnusedAttr>() || |
1660 | D->hasAttr<ObjCPreciseLifetimeAttr>()) |
1661 | return false; |
1662 | |
1663 | if (isa<LabelDecl>(D)) |
1664 | return true; |
1665 | |
1666 | // Except for labels, we only care about unused decls that are local to |
1667 | // functions. |
1668 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); |
1669 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) |
1670 | // For dependent types, the diagnostic is deferred. |
1671 | WithinFunction = |
1672 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); |
1673 | if (!WithinFunction) |
1674 | return false; |
1675 | |
1676 | if (isa<TypedefNameDecl>(D)) |
1677 | return true; |
1678 | |
1679 | // White-list anything that isn't a local variable. |
1680 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) |
1681 | return false; |
1682 | |
1683 | // Types of valid local variables should be complete, so this should succeed. |
1684 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { |
1685 | |
1686 | // White-list anything with an __attribute__((unused)) type. |
1687 | const auto *Ty = VD->getType().getTypePtr(); |
1688 | |
1689 | // Only look at the outermost level of typedef. |
1690 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { |
1691 | if (TT->getDecl()->hasAttr<UnusedAttr>()) |
1692 | return false; |
1693 | } |
1694 | |
1695 | // If we failed to complete the type for some reason, or if the type is |
1696 | // dependent, don't diagnose the variable. |
1697 | if (Ty->isIncompleteType() || Ty->isDependentType()) |
1698 | return false; |
1699 | |
1700 | // Look at the element type to ensure that the warning behaviour is |
1701 | // consistent for both scalars and arrays. |
1702 | Ty = Ty->getBaseElementTypeUnsafe(); |
1703 | |
1704 | if (const TagType *TT = Ty->getAs<TagType>()) { |
1705 | const TagDecl *Tag = TT->getDecl(); |
1706 | if (Tag->hasAttr<UnusedAttr>()) |
1707 | return false; |
1708 | |
1709 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { |
1710 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) |
1711 | return false; |
1712 | |
1713 | if (const Expr *Init = VD->getInit()) { |
1714 | if (const ExprWithCleanups *Cleanups = |
1715 | dyn_cast<ExprWithCleanups>(Init)) |
1716 | Init = Cleanups->getSubExpr(); |
1717 | const CXXConstructExpr *Construct = |
1718 | dyn_cast<CXXConstructExpr>(Init); |
1719 | if (Construct && !Construct->isElidable()) { |
1720 | CXXConstructorDecl *CD = Construct->getConstructor(); |
1721 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && |
1722 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) |
1723 | return false; |
1724 | } |
1725 | } |
1726 | } |
1727 | } |
1728 | |
1729 | // TODO: __attribute__((unused)) templates? |
1730 | } |
1731 | |
1732 | return true; |
1733 | } |
1734 | |
1735 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, |
1736 | FixItHint &Hint) { |
1737 | if (isa<LabelDecl>(D)) { |
1738 | SourceLocation AfterColon = Lexer::findLocationAfterToken( |
1739 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), |
1740 | true); |
1741 | if (AfterColon.isInvalid()) |
1742 | return; |
1743 | Hint = FixItHint::CreateRemoval( |
1744 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); |
1745 | } |
1746 | } |
1747 | |
1748 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { |
1749 | if (D->getTypeForDecl()->isDependentType()) |
1750 | return; |
1751 | |
1752 | for (auto *TmpD : D->decls()) { |
1753 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) |
1754 | DiagnoseUnusedDecl(T); |
1755 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) |
1756 | DiagnoseUnusedNestedTypedefs(R); |
1757 | } |
1758 | } |
1759 | |
1760 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used |
1761 | /// unless they are marked attr(unused). |
1762 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { |
1763 | if (!ShouldDiagnoseUnusedDecl(D)) |
1764 | return; |
1765 | |
1766 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { |
1767 | // typedefs can be referenced later on, so the diagnostics are emitted |
1768 | // at end-of-translation-unit. |
1769 | UnusedLocalTypedefNameCandidates.insert(TD); |
1770 | return; |
1771 | } |
1772 | |
1773 | FixItHint Hint; |
1774 | GenerateFixForUnusedDecl(D, Context, Hint); |
1775 | |
1776 | unsigned DiagID; |
1777 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) |
1778 | DiagID = diag::warn_unused_exception_param; |
1779 | else if (isa<LabelDecl>(D)) |
1780 | DiagID = diag::warn_unused_label; |
1781 | else |
1782 | DiagID = diag::warn_unused_variable; |
1783 | |
1784 | Diag(D->getLocation(), DiagID) << D << Hint; |
1785 | } |
1786 | |
1787 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { |
1788 | // Verify that we have no forward references left. If so, there was a goto |
1789 | // or address of a label taken, but no definition of it. Label fwd |
1790 | // definitions are indicated with a null substmt which is also not a resolved |
1791 | // MS inline assembly label name. |
1792 | bool Diagnose = false; |
1793 | if (L->isMSAsmLabel()) |
1794 | Diagnose = !L->isResolvedMSAsmLabel(); |
1795 | else |
1796 | Diagnose = L->getStmt() == nullptr; |
1797 | if (Diagnose) |
1798 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); |
1799 | } |
1800 | |
1801 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { |
1802 | S->mergeNRVOIntoParent(); |
1803 | |
1804 | if (S->decl_empty()) return; |
1805 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1806, __PRETTY_FUNCTION__)) |
1806 | "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1806, __PRETTY_FUNCTION__)); |
1807 | |
1808 | for (auto *TmpD : S->decls()) { |
1809 | assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast <void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1809, __PRETTY_FUNCTION__)); |
1810 | |
1811 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?" ) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1811, __PRETTY_FUNCTION__)); |
1812 | NamedDecl *D = cast<NamedDecl>(TmpD); |
1813 | |
1814 | // Diagnose unused variables in this scope. |
1815 | if (!S->hasUnrecoverableErrorOccurred()) { |
1816 | DiagnoseUnusedDecl(D); |
1817 | if (const auto *RD = dyn_cast<RecordDecl>(D)) |
1818 | DiagnoseUnusedNestedTypedefs(RD); |
1819 | } |
1820 | |
1821 | if (!D->getDeclName()) continue; |
1822 | |
1823 | // If this was a forward reference to a label, verify it was defined. |
1824 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) |
1825 | CheckPoppedLabel(LD, *this); |
1826 | |
1827 | // Remove this name from our lexical scope, and warn on it if we haven't |
1828 | // already. |
1829 | IdResolver.RemoveDecl(D); |
1830 | auto ShadowI = ShadowingDecls.find(D); |
1831 | if (ShadowI != ShadowingDecls.end()) { |
1832 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { |
1833 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) |
1834 | << D << FD << FD->getParent(); |
1835 | Diag(FD->getLocation(), diag::note_previous_declaration); |
1836 | } |
1837 | ShadowingDecls.erase(ShadowI); |
1838 | } |
1839 | } |
1840 | } |
1841 | |
1842 | /// Look for an Objective-C class in the translation unit. |
1843 | /// |
1844 | /// \param Id The name of the Objective-C class we're looking for. If |
1845 | /// typo-correction fixes this name, the Id will be updated |
1846 | /// to the fixed name. |
1847 | /// |
1848 | /// \param IdLoc The location of the name in the translation unit. |
1849 | /// |
1850 | /// \param DoTypoCorrection If true, this routine will attempt typo correction |
1851 | /// if there is no class with the given name. |
1852 | /// |
1853 | /// \returns The declaration of the named Objective-C class, or NULL if the |
1854 | /// class could not be found. |
1855 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, |
1856 | SourceLocation IdLoc, |
1857 | bool DoTypoCorrection) { |
1858 | // The third "scope" argument is 0 since we aren't enabling lazy built-in |
1859 | // creation from this context. |
1860 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); |
1861 | |
1862 | if (!IDecl && DoTypoCorrection) { |
1863 | // Perform typo correction at the given location, but only if we |
1864 | // find an Objective-C class name. |
1865 | if (TypoCorrection C = CorrectTypo( |
1866 | DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, |
1867 | llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), |
1868 | CTK_ErrorRecovery)) { |
1869 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); |
1870 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); |
1871 | Id = IDecl->getIdentifier(); |
1872 | } |
1873 | } |
1874 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); |
1875 | // This routine must always return a class definition, if any. |
1876 | if (Def && Def->getDefinition()) |
1877 | Def = Def->getDefinition(); |
1878 | return Def; |
1879 | } |
1880 | |
1881 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting |
1882 | /// from S, where a non-field would be declared. This routine copes |
1883 | /// with the difference between C and C++ scoping rules in structs and |
1884 | /// unions. For example, the following code is well-formed in C but |
1885 | /// ill-formed in C++: |
1886 | /// @code |
1887 | /// struct S6 { |
1888 | /// enum { BAR } e; |
1889 | /// }; |
1890 | /// |
1891 | /// void test_S6() { |
1892 | /// struct S6 a; |
1893 | /// a.e = BAR; |
1894 | /// } |
1895 | /// @endcode |
1896 | /// For the declaration of BAR, this routine will return a different |
1897 | /// scope. The scope S will be the scope of the unnamed enumeration |
1898 | /// within S6. In C++, this routine will return the scope associated |
1899 | /// with S6, because the enumeration's scope is a transparent |
1900 | /// context but structures can contain non-field names. In C, this |
1901 | /// routine will return the translation unit scope, since the |
1902 | /// enumeration's scope is a transparent context and structures cannot |
1903 | /// contain non-field names. |
1904 | Scope *Sema::getNonFieldDeclScope(Scope *S) { |
1905 | while (((S->getFlags() & Scope::DeclScope) == 0) || |
1906 | (S->getEntity() && S->getEntity()->isTransparentContext()) || |
1907 | (S->isClassScope() && !getLangOpts().CPlusPlus)) |
1908 | S = S->getParent(); |
1909 | return S; |
1910 | } |
1911 | |
1912 | /// Looks up the declaration of "struct objc_super" and |
1913 | /// saves it for later use in building builtin declaration of |
1914 | /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such |
1915 | /// pre-existing declaration exists no action takes place. |
1916 | static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, |
1917 | IdentifierInfo *II) { |
1918 | if (!II->isStr("objc_msgSendSuper")) |
1919 | return; |
1920 | ASTContext &Context = ThisSema.Context; |
1921 | |
1922 | LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), |
1923 | SourceLocation(), Sema::LookupTagName); |
1924 | ThisSema.LookupName(Result, S); |
1925 | if (Result.getResultKind() == LookupResult::Found) |
1926 | if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) |
1927 | Context.setObjCSuperType(Context.getTagDeclType(TD)); |
1928 | } |
1929 | |
1930 | static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { |
1931 | switch (Error) { |
1932 | case ASTContext::GE_None: |
1933 | return ""; |
1934 | case ASTContext::GE_Missing_stdio: |
1935 | return "stdio.h"; |
1936 | case ASTContext::GE_Missing_setjmp: |
1937 | return "setjmp.h"; |
1938 | case ASTContext::GE_Missing_ucontext: |
1939 | return "ucontext.h"; |
1940 | } |
1941 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 1941); |
1942 | } |
1943 | |
1944 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at |
1945 | /// file scope. lazily create a decl for it. ForRedeclaration is true |
1946 | /// if we're creating this built-in in anticipation of redeclaring the |
1947 | /// built-in. |
1948 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, |
1949 | Scope *S, bool ForRedeclaration, |
1950 | SourceLocation Loc) { |
1951 | LookupPredefedObjCSuperType(*this, S, II); |
1952 | |
1953 | ASTContext::GetBuiltinTypeError Error; |
1954 | QualType R = Context.GetBuiltinType(ID, Error); |
1955 | if (Error) { |
1956 | if (ForRedeclaration) |
1957 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) |
1958 | << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); |
1959 | return nullptr; |
1960 | } |
1961 | |
1962 | if (!ForRedeclaration && |
1963 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || |
1964 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { |
1965 | Diag(Loc, diag::ext_implicit_lib_function_decl) |
1966 | << Context.BuiltinInfo.getName(ID) << R; |
1967 | if (Context.BuiltinInfo.getHeaderName(ID) && |
1968 | !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) |
1969 | Diag(Loc, diag::note_include_header_or_declare) |
1970 | << Context.BuiltinInfo.getHeaderName(ID) |
1971 | << Context.BuiltinInfo.getName(ID); |
1972 | } |
1973 | |
1974 | if (R.isNull()) |
1975 | return nullptr; |
1976 | |
1977 | DeclContext *Parent = Context.getTranslationUnitDecl(); |
1978 | if (getLangOpts().CPlusPlus) { |
1979 | LinkageSpecDecl *CLinkageDecl = |
1980 | LinkageSpecDecl::Create(Context, Parent, Loc, Loc, |
1981 | LinkageSpecDecl::lang_c, false); |
1982 | CLinkageDecl->setImplicit(); |
1983 | Parent->addDecl(CLinkageDecl); |
1984 | Parent = CLinkageDecl; |
1985 | } |
1986 | |
1987 | FunctionDecl *New = FunctionDecl::Create(Context, |
1988 | Parent, |
1989 | Loc, Loc, II, R, /*TInfo=*/nullptr, |
1990 | SC_Extern, |
1991 | false, |
1992 | R->isFunctionProtoType()); |
1993 | New->setImplicit(); |
1994 | |
1995 | // Create Decl objects for each parameter, adding them to the |
1996 | // FunctionDecl. |
1997 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { |
1998 | SmallVector<ParmVarDecl*, 16> Params; |
1999 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { |
2000 | ParmVarDecl *parm = |
2001 | ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), |
2002 | nullptr, FT->getParamType(i), /*TInfo=*/nullptr, |
2003 | SC_None, nullptr); |
2004 | parm->setScopeInfo(0, i); |
2005 | Params.push_back(parm); |
2006 | } |
2007 | New->setParams(Params); |
2008 | } |
2009 | |
2010 | AddKnownFunctionAttributes(New); |
2011 | RegisterLocallyScopedExternCDecl(New, S); |
2012 | |
2013 | // TUScope is the translation-unit scope to insert this function into. |
2014 | // FIXME: This is hideous. We need to teach PushOnScopeChains to |
2015 | // relate Scopes to DeclContexts, and probably eliminate CurContext |
2016 | // entirely, but we're not there yet. |
2017 | DeclContext *SavedContext = CurContext; |
2018 | CurContext = Parent; |
2019 | PushOnScopeChains(New, TUScope); |
2020 | CurContext = SavedContext; |
2021 | return New; |
2022 | } |
2023 | |
2024 | /// Typedef declarations don't have linkage, but they still denote the same |
2025 | /// entity if their types are the same. |
2026 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's |
2027 | /// isSameEntity. |
2028 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, |
2029 | TypedefNameDecl *Decl, |
2030 | LookupResult &Previous) { |
2031 | // This is only interesting when modules are enabled. |
2032 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) |
2033 | return; |
2034 | |
2035 | // Empty sets are uninteresting. |
2036 | if (Previous.empty()) |
2037 | return; |
2038 | |
2039 | LookupResult::Filter Filter = Previous.makeFilter(); |
2040 | while (Filter.hasNext()) { |
2041 | NamedDecl *Old = Filter.next(); |
2042 | |
2043 | // Non-hidden declarations are never ignored. |
2044 | if (S.isVisible(Old)) |
2045 | continue; |
2046 | |
2047 | // Declarations of the same entity are not ignored, even if they have |
2048 | // different linkages. |
2049 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { |
2050 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), |
2051 | Decl->getUnderlyingType())) |
2052 | continue; |
2053 | |
2054 | // If both declarations give a tag declaration a typedef name for linkage |
2055 | // purposes, then they declare the same entity. |
2056 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && |
2057 | Decl->getAnonDeclWithTypedefName()) |
2058 | continue; |
2059 | } |
2060 | |
2061 | Filter.erase(); |
2062 | } |
2063 | |
2064 | Filter.done(); |
2065 | } |
2066 | |
2067 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { |
2068 | QualType OldType; |
2069 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) |
2070 | OldType = OldTypedef->getUnderlyingType(); |
2071 | else |
2072 | OldType = Context.getTypeDeclType(Old); |
2073 | QualType NewType = New->getUnderlyingType(); |
2074 | |
2075 | if (NewType->isVariablyModifiedType()) { |
2076 | // Must not redefine a typedef with a variably-modified type. |
2077 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; |
2078 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) |
2079 | << Kind << NewType; |
2080 | if (Old->getLocation().isValid()) |
2081 | notePreviousDefinition(Old, New->getLocation()); |
2082 | New->setInvalidDecl(); |
2083 | return true; |
2084 | } |
2085 | |
2086 | if (OldType != NewType && |
2087 | !OldType->isDependentType() && |
2088 | !NewType->isDependentType() && |
2089 | !Context.hasSameType(OldType, NewType)) { |
2090 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; |
2091 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) |
2092 | << Kind << NewType << OldType; |
2093 | if (Old->getLocation().isValid()) |
2094 | notePreviousDefinition(Old, New->getLocation()); |
2095 | New->setInvalidDecl(); |
2096 | return true; |
2097 | } |
2098 | return false; |
2099 | } |
2100 | |
2101 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the |
2102 | /// same name and scope as a previous declaration 'Old'. Figure out |
2103 | /// how to resolve this situation, merging decls or emitting |
2104 | /// diagnostics as appropriate. If there was an error, set New to be invalid. |
2105 | /// |
2106 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, |
2107 | LookupResult &OldDecls) { |
2108 | // If the new decl is known invalid already, don't bother doing any |
2109 | // merging checks. |
2110 | if (New->isInvalidDecl()) return; |
2111 | |
2112 | // Allow multiple definitions for ObjC built-in typedefs. |
2113 | // FIXME: Verify the underlying types are equivalent! |
2114 | if (getLangOpts().ObjC) { |
2115 | const IdentifierInfo *TypeID = New->getIdentifier(); |
2116 | switch (TypeID->getLength()) { |
2117 | default: break; |
2118 | case 2: |
2119 | { |
2120 | if (!TypeID->isStr("id")) |
2121 | break; |
2122 | QualType T = New->getUnderlyingType(); |
2123 | if (!T->isPointerType()) |
2124 | break; |
2125 | if (!T->isVoidPointerType()) { |
2126 | QualType PT = T->getAs<PointerType>()->getPointeeType(); |
2127 | if (!PT->isStructureType()) |
2128 | break; |
2129 | } |
2130 | Context.setObjCIdRedefinitionType(T); |
2131 | // Install the built-in type for 'id', ignoring the current definition. |
2132 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); |
2133 | return; |
2134 | } |
2135 | case 5: |
2136 | if (!TypeID->isStr("Class")) |
2137 | break; |
2138 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); |
2139 | // Install the built-in type for 'Class', ignoring the current definition. |
2140 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); |
2141 | return; |
2142 | case 3: |
2143 | if (!TypeID->isStr("SEL")) |
2144 | break; |
2145 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); |
2146 | // Install the built-in type for 'SEL', ignoring the current definition. |
2147 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); |
2148 | return; |
2149 | } |
2150 | // Fall through - the typedef name was not a builtin type. |
2151 | } |
2152 | |
2153 | // Verify the old decl was also a type. |
2154 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); |
2155 | if (!Old) { |
2156 | Diag(New->getLocation(), diag::err_redefinition_different_kind) |
2157 | << New->getDeclName(); |
2158 | |
2159 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); |
2160 | if (OldD->getLocation().isValid()) |
2161 | notePreviousDefinition(OldD, New->getLocation()); |
2162 | |
2163 | return New->setInvalidDecl(); |
2164 | } |
2165 | |
2166 | // If the old declaration is invalid, just give up here. |
2167 | if (Old->isInvalidDecl()) |
2168 | return New->setInvalidDecl(); |
2169 | |
2170 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { |
2171 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); |
2172 | auto *NewTag = New->getAnonDeclWithTypedefName(); |
2173 | NamedDecl *Hidden = nullptr; |
2174 | if (OldTag && NewTag && |
2175 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && |
2176 | !hasVisibleDefinition(OldTag, &Hidden)) { |
2177 | // There is a definition of this tag, but it is not visible. Use it |
2178 | // instead of our tag. |
2179 | New->setTypeForDecl(OldTD->getTypeForDecl()); |
2180 | if (OldTD->isModed()) |
2181 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), |
2182 | OldTD->getUnderlyingType()); |
2183 | else |
2184 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); |
2185 | |
2186 | // Make the old tag definition visible. |
2187 | makeMergedDefinitionVisible(Hidden); |
2188 | |
2189 | // If this was an unscoped enumeration, yank all of its enumerators |
2190 | // out of the scope. |
2191 | if (isa<EnumDecl>(NewTag)) { |
2192 | Scope *EnumScope = getNonFieldDeclScope(S); |
2193 | for (auto *D : NewTag->decls()) { |
2194 | auto *ED = cast<EnumConstantDecl>(D); |
2195 | assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0 ) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 2195, __PRETTY_FUNCTION__)); |
2196 | EnumScope->RemoveDecl(ED); |
2197 | IdResolver.RemoveDecl(ED); |
2198 | ED->getLexicalDeclContext()->removeDecl(ED); |
2199 | } |
2200 | } |
2201 | } |
2202 | } |
2203 | |
2204 | // If the typedef types are not identical, reject them in all languages and |
2205 | // with any extensions enabled. |
2206 | if (isIncompatibleTypedef(Old, New)) |
2207 | return; |
2208 | |
2209 | // The types match. Link up the redeclaration chain and merge attributes if |
2210 | // the old declaration was a typedef. |
2211 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { |
2212 | New->setPreviousDecl(Typedef); |
2213 | mergeDeclAttributes(New, Old); |
2214 | } |
2215 | |
2216 | if (getLangOpts().MicrosoftExt) |
2217 | return; |
2218 | |
2219 | if (getLangOpts().CPlusPlus) { |
2220 | // C++ [dcl.typedef]p2: |
2221 | // In a given non-class scope, a typedef specifier can be used to |
2222 | // redefine the name of any type declared in that scope to refer |
2223 | // to the type to which it already refers. |
2224 | if (!isa<CXXRecordDecl>(CurContext)) |
2225 | return; |
2226 | |
2227 | // C++0x [dcl.typedef]p4: |
2228 | // In a given class scope, a typedef specifier can be used to redefine |
2229 | // any class-name declared in that scope that is not also a typedef-name |
2230 | // to refer to the type to which it already refers. |
2231 | // |
2232 | // This wording came in via DR424, which was a correction to the |
2233 | // wording in DR56, which accidentally banned code like: |
2234 | // |
2235 | // struct S { |
2236 | // typedef struct A { } A; |
2237 | // }; |
2238 | // |
2239 | // in the C++03 standard. We implement the C++0x semantics, which |
2240 | // allow the above but disallow |
2241 | // |
2242 | // struct S { |
2243 | // typedef int I; |
2244 | // typedef int I; |
2245 | // }; |
2246 | // |
2247 | // since that was the intent of DR56. |
2248 | if (!isa<TypedefNameDecl>(Old)) |
2249 | return; |
2250 | |
2251 | Diag(New->getLocation(), diag::err_redefinition) |
2252 | << New->getDeclName(); |
2253 | notePreviousDefinition(Old, New->getLocation()); |
2254 | return New->setInvalidDecl(); |
2255 | } |
2256 | |
2257 | // Modules always permit redefinition of typedefs, as does C11. |
2258 | if (getLangOpts().Modules || getLangOpts().C11) |
2259 | return; |
2260 | |
2261 | // If we have a redefinition of a typedef in C, emit a warning. This warning |
2262 | // is normally mapped to an error, but can be controlled with |
2263 | // -Wtypedef-redefinition. If either the original or the redefinition is |
2264 | // in a system header, don't emit this for compatibility with GCC. |
2265 | if (getDiagnostics().getSuppressSystemWarnings() && |
2266 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). |
2267 | (Old->isImplicit() || |
2268 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || |
2269 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) |
2270 | return; |
2271 | |
2272 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) |
2273 | << New->getDeclName(); |
2274 | notePreviousDefinition(Old, New->getLocation()); |
2275 | } |
2276 | |
2277 | /// DeclhasAttr - returns true if decl Declaration already has the target |
2278 | /// attribute. |
2279 | static bool DeclHasAttr(const Decl *D, const Attr *A) { |
2280 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); |
2281 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); |
2282 | for (const auto *i : D->attrs()) |
2283 | if (i->getKind() == A->getKind()) { |
2284 | if (Ann) { |
2285 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) |
2286 | return true; |
2287 | continue; |
2288 | } |
2289 | // FIXME: Don't hardcode this check |
2290 | if (OA && isa<OwnershipAttr>(i)) |
2291 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); |
2292 | return true; |
2293 | } |
2294 | |
2295 | return false; |
2296 | } |
2297 | |
2298 | static bool isAttributeTargetADefinition(Decl *D) { |
2299 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) |
2300 | return VD->isThisDeclarationADefinition(); |
2301 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) |
2302 | return TD->isCompleteDefinition() || TD->isBeingDefined(); |
2303 | return true; |
2304 | } |
2305 | |
2306 | /// Merge alignment attributes from \p Old to \p New, taking into account the |
2307 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. |
2308 | /// |
2309 | /// \return \c true if any attributes were added to \p New. |
2310 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { |
2311 | // Look for alignas attributes on Old, and pick out whichever attribute |
2312 | // specifies the strictest alignment requirement. |
2313 | AlignedAttr *OldAlignasAttr = nullptr; |
2314 | AlignedAttr *OldStrictestAlignAttr = nullptr; |
2315 | unsigned OldAlign = 0; |
2316 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { |
2317 | // FIXME: We have no way of representing inherited dependent alignments |
2318 | // in a case like: |
2319 | // template<int A, int B> struct alignas(A) X; |
2320 | // template<int A, int B> struct alignas(B) X {}; |
2321 | // For now, we just ignore any alignas attributes which are not on the |
2322 | // definition in such a case. |
2323 | if (I->isAlignmentDependent()) |
2324 | return false; |
2325 | |
2326 | if (I->isAlignas()) |
2327 | OldAlignasAttr = I; |
2328 | |
2329 | unsigned Align = I->getAlignment(S.Context); |
2330 | if (Align > OldAlign) { |
2331 | OldAlign = Align; |
2332 | OldStrictestAlignAttr = I; |
2333 | } |
2334 | } |
2335 | |
2336 | // Look for alignas attributes on New. |
2337 | AlignedAttr *NewAlignasAttr = nullptr; |
2338 | unsigned NewAlign = 0; |
2339 | for (auto *I : New->specific_attrs<AlignedAttr>()) { |
2340 | if (I->isAlignmentDependent()) |
2341 | return false; |
2342 | |
2343 | if (I->isAlignas()) |
2344 | NewAlignasAttr = I; |
2345 | |
2346 | unsigned Align = I->getAlignment(S.Context); |
2347 | if (Align > NewAlign) |
2348 | NewAlign = Align; |
2349 | } |
2350 | |
2351 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { |
2352 | // Both declarations have 'alignas' attributes. We require them to match. |
2353 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but |
2354 | // fall short. (If two declarations both have alignas, they must both match |
2355 | // every definition, and so must match each other if there is a definition.) |
2356 | |
2357 | // If either declaration only contains 'alignas(0)' specifiers, then it |
2358 | // specifies the natural alignment for the type. |
2359 | if (OldAlign == 0 || NewAlign == 0) { |
2360 | QualType Ty; |
2361 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) |
2362 | Ty = VD->getType(); |
2363 | else |
2364 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); |
2365 | |
2366 | if (OldAlign == 0) |
2367 | OldAlign = S.Context.getTypeAlign(Ty); |
2368 | if (NewAlign == 0) |
2369 | NewAlign = S.Context.getTypeAlign(Ty); |
2370 | } |
2371 | |
2372 | if (OldAlign != NewAlign) { |
2373 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) |
2374 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() |
2375 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); |
2376 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); |
2377 | } |
2378 | } |
2379 | |
2380 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { |
2381 | // C++11 [dcl.align]p6: |
2382 | // if any declaration of an entity has an alignment-specifier, |
2383 | // every defining declaration of that entity shall specify an |
2384 | // equivalent alignment. |
2385 | // C11 6.7.5/7: |
2386 | // If the definition of an object does not have an alignment |
2387 | // specifier, any other declaration of that object shall also |
2388 | // have no alignment specifier. |
2389 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) |
2390 | << OldAlignasAttr; |
2391 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) |
2392 | << OldAlignasAttr; |
2393 | } |
2394 | |
2395 | bool AnyAdded = false; |
2396 | |
2397 | // Ensure we have an attribute representing the strictest alignment. |
2398 | if (OldAlign > NewAlign) { |
2399 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); |
2400 | Clone->setInherited(true); |
2401 | New->addAttr(Clone); |
2402 | AnyAdded = true; |
2403 | } |
2404 | |
2405 | // Ensure we have an alignas attribute if the old declaration had one. |
2406 | if (OldAlignasAttr && !NewAlignasAttr && |
2407 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { |
2408 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); |
2409 | Clone->setInherited(true); |
2410 | New->addAttr(Clone); |
2411 | AnyAdded = true; |
2412 | } |
2413 | |
2414 | return AnyAdded; |
2415 | } |
2416 | |
2417 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, |
2418 | const InheritableAttr *Attr, |
2419 | Sema::AvailabilityMergeKind AMK) { |
2420 | // This function copies an attribute Attr from a previous declaration to the |
2421 | // new declaration D if the new declaration doesn't itself have that attribute |
2422 | // yet or if that attribute allows duplicates. |
2423 | // If you're adding a new attribute that requires logic different from |
2424 | // "use explicit attribute on decl if present, else use attribute from |
2425 | // previous decl", for example if the attribute needs to be consistent |
2426 | // between redeclarations, you need to call a custom merge function here. |
2427 | InheritableAttr *NewAttr = nullptr; |
2428 | unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); |
2429 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) |
2430 | NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), |
2431 | AA->isImplicit(), AA->getIntroduced(), |
2432 | AA->getDeprecated(), |
2433 | AA->getObsoleted(), AA->getUnavailable(), |
2434 | AA->getMessage(), AA->getStrict(), |
2435 | AA->getReplacement(), AMK, |
2436 | AttrSpellingListIndex); |
2437 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) |
2438 | NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), |
2439 | AttrSpellingListIndex); |
2440 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) |
2441 | NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), |
2442 | AttrSpellingListIndex); |
2443 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) |
2444 | NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), |
2445 | AttrSpellingListIndex); |
2446 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) |
2447 | NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), |
2448 | AttrSpellingListIndex); |
2449 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) |
2450 | NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), |
2451 | FA->getFormatIdx(), FA->getFirstArg(), |
2452 | AttrSpellingListIndex); |
2453 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) |
2454 | NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), |
2455 | AttrSpellingListIndex); |
2456 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) |
2457 | NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), |
2458 | AttrSpellingListIndex); |
2459 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) |
2460 | NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), |
2461 | AttrSpellingListIndex, |
2462 | IA->getSemanticSpelling()); |
2463 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) |
2464 | NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), |
2465 | &S.Context.Idents.get(AA->getSpelling()), |
2466 | AttrSpellingListIndex); |
2467 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && |
2468 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || |
2469 | isa<CUDAGlobalAttr>(Attr))) { |
2470 | // CUDA target attributes are part of function signature for |
2471 | // overloading purposes and must not be merged. |
2472 | return false; |
2473 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) |
2474 | NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); |
2475 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) |
2476 | NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); |
2477 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) |
2478 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); |
2479 | else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) |
2480 | NewAttr = S.mergeCommonAttr(D, *CommonA); |
2481 | else if (isa<AlignedAttr>(Attr)) |
2482 | // AlignedAttrs are handled separately, because we need to handle all |
2483 | // such attributes on a declaration at the same time. |
2484 | NewAttr = nullptr; |
2485 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && |
2486 | (AMK == Sema::AMK_Override || |
2487 | AMK == Sema::AMK_ProtocolImplementation)) |
2488 | NewAttr = nullptr; |
2489 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) |
2490 | NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, |
2491 | UA->getGuid()); |
2492 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) |
2493 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); |
2494 | |
2495 | if (NewAttr) { |
2496 | NewAttr->setInherited(true); |
2497 | D->addAttr(NewAttr); |
2498 | if (isa<MSInheritanceAttr>(NewAttr)) |
2499 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); |
2500 | return true; |
2501 | } |
2502 | |
2503 | return false; |
2504 | } |
2505 | |
2506 | static const NamedDecl *getDefinition(const Decl *D) { |
2507 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) |
2508 | return TD->getDefinition(); |
2509 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { |
2510 | const VarDecl *Def = VD->getDefinition(); |
2511 | if (Def) |
2512 | return Def; |
2513 | return VD->getActingDefinition(); |
2514 | } |
2515 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) |
2516 | return FD->getDefinition(); |
2517 | return nullptr; |
2518 | } |
2519 | |
2520 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { |
2521 | for (const auto *Attribute : D->attrs()) |
2522 | if (Attribute->getKind() == Kind) |
2523 | return true; |
2524 | return false; |
2525 | } |
2526 | |
2527 | /// checkNewAttributesAfterDef - If we already have a definition, check that |
2528 | /// there are no new attributes in this declaration. |
2529 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { |
2530 | if (!New->hasAttrs()) |
2531 | return; |
2532 | |
2533 | const NamedDecl *Def = getDefinition(Old); |
2534 | if (!Def || Def == New) |
2535 | return; |
2536 | |
2537 | AttrVec &NewAttributes = New->getAttrs(); |
2538 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { |
2539 | const Attr *NewAttribute = NewAttributes[I]; |
2540 | |
2541 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { |
2542 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { |
2543 | Sema::SkipBodyInfo SkipBody; |
2544 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); |
2545 | |
2546 | // If we're skipping this definition, drop the "alias" attribute. |
2547 | if (SkipBody.ShouldSkip) { |
2548 | NewAttributes.erase(NewAttributes.begin() + I); |
2549 | --E; |
2550 | continue; |
2551 | } |
2552 | } else { |
2553 | VarDecl *VD = cast<VarDecl>(New); |
2554 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == |
2555 | VarDecl::TentativeDefinition |
2556 | ? diag::err_alias_after_tentative |
2557 | : diag::err_redefinition; |
2558 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); |
2559 | if (Diag == diag::err_redefinition) |
2560 | S.notePreviousDefinition(Def, VD->getLocation()); |
2561 | else |
2562 | S.Diag(Def->getLocation(), diag::note_previous_definition); |
2563 | VD->setInvalidDecl(); |
2564 | } |
2565 | ++I; |
2566 | continue; |
2567 | } |
2568 | |
2569 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { |
2570 | // Tentative definitions are only interesting for the alias check above. |
2571 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { |
2572 | ++I; |
2573 | continue; |
2574 | } |
2575 | } |
2576 | |
2577 | if (hasAttribute(Def, NewAttribute->getKind())) { |
2578 | ++I; |
2579 | continue; // regular attr merging will take care of validating this. |
2580 | } |
2581 | |
2582 | if (isa<C11NoReturnAttr>(NewAttribute)) { |
2583 | // C's _Noreturn is allowed to be added to a function after it is defined. |
2584 | ++I; |
2585 | continue; |
2586 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { |
2587 | if (AA->isAlignas()) { |
2588 | // C++11 [dcl.align]p6: |
2589 | // if any declaration of an entity has an alignment-specifier, |
2590 | // every defining declaration of that entity shall specify an |
2591 | // equivalent alignment. |
2592 | // C11 6.7.5/7: |
2593 | // If the definition of an object does not have an alignment |
2594 | // specifier, any other declaration of that object shall also |
2595 | // have no alignment specifier. |
2596 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) |
2597 | << AA; |
2598 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) |
2599 | << AA; |
2600 | NewAttributes.erase(NewAttributes.begin() + I); |
2601 | --E; |
2602 | continue; |
2603 | } |
2604 | } |
2605 | |
2606 | S.Diag(NewAttribute->getLocation(), |
2607 | diag::warn_attribute_precede_definition); |
2608 | S.Diag(Def->getLocation(), diag::note_previous_definition); |
2609 | NewAttributes.erase(NewAttributes.begin() + I); |
2610 | --E; |
2611 | } |
2612 | } |
2613 | |
2614 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. |
2615 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, |
2616 | AvailabilityMergeKind AMK) { |
2617 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { |
2618 | UsedAttr *NewAttr = OldAttr->clone(Context); |
2619 | NewAttr->setInherited(true); |
2620 | New->addAttr(NewAttr); |
2621 | } |
2622 | |
2623 | if (!Old->hasAttrs() && !New->hasAttrs()) |
2624 | return; |
2625 | |
2626 | // Attributes declared post-definition are currently ignored. |
2627 | checkNewAttributesAfterDef(*this, New, Old); |
2628 | |
2629 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { |
2630 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { |
2631 | if (OldA->getLabel() != NewA->getLabel()) { |
2632 | // This redeclaration changes __asm__ label. |
2633 | Diag(New->getLocation(), diag::err_different_asm_label); |
2634 | Diag(OldA->getLocation(), diag::note_previous_declaration); |
2635 | } |
2636 | } else if (Old->isUsed()) { |
2637 | // This redeclaration adds an __asm__ label to a declaration that has |
2638 | // already been ODR-used. |
2639 | Diag(New->getLocation(), diag::err_late_asm_label_name) |
2640 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); |
2641 | } |
2642 | } |
2643 | |
2644 | // Re-declaration cannot add abi_tag's. |
2645 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { |
2646 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { |
2647 | for (const auto &NewTag : NewAbiTagAttr->tags()) { |
2648 | if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), |
2649 | NewTag) == OldAbiTagAttr->tags_end()) { |
2650 | Diag(NewAbiTagAttr->getLocation(), |
2651 | diag::err_new_abi_tag_on_redeclaration) |
2652 | << NewTag; |
2653 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); |
2654 | } |
2655 | } |
2656 | } else { |
2657 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); |
2658 | Diag(Old->getLocation(), diag::note_previous_declaration); |
2659 | } |
2660 | } |
2661 | |
2662 | // This redeclaration adds a section attribute. |
2663 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { |
2664 | if (auto *VD = dyn_cast<VarDecl>(New)) { |
2665 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { |
2666 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); |
2667 | Diag(Old->getLocation(), diag::note_previous_declaration); |
2668 | } |
2669 | } |
2670 | } |
2671 | |
2672 | // Redeclaration adds code-seg attribute. |
2673 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); |
2674 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && |
2675 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { |
2676 | Diag(New->getLocation(), diag::warn_mismatched_section) |
2677 | << 0 /*codeseg*/; |
2678 | Diag(Old->getLocation(), diag::note_previous_declaration); |
2679 | } |
2680 | |
2681 | if (!Old->hasAttrs()) |
2682 | return; |
2683 | |
2684 | bool foundAny = New->hasAttrs(); |
2685 | |
2686 | // Ensure that any moving of objects within the allocated map is done before |
2687 | // we process them. |
2688 | if (!foundAny) New->setAttrs(AttrVec()); |
2689 | |
2690 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { |
2691 | // Ignore deprecated/unavailable/availability attributes if requested. |
2692 | AvailabilityMergeKind LocalAMK = AMK_None; |
2693 | if (isa<DeprecatedAttr>(I) || |
2694 | isa<UnavailableAttr>(I) || |
2695 | isa<AvailabilityAttr>(I)) { |
2696 | switch (AMK) { |
2697 | case AMK_None: |
2698 | continue; |
2699 | |
2700 | case AMK_Redeclaration: |
2701 | case AMK_Override: |
2702 | case AMK_ProtocolImplementation: |
2703 | LocalAMK = AMK; |
2704 | break; |
2705 | } |
2706 | } |
2707 | |
2708 | // Already handled. |
2709 | if (isa<UsedAttr>(I)) |
2710 | continue; |
2711 | |
2712 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) |
2713 | foundAny = true; |
2714 | } |
2715 | |
2716 | if (mergeAlignedAttrs(*this, New, Old)) |
2717 | foundAny = true; |
2718 | |
2719 | if (!foundAny) New->dropAttrs(); |
2720 | } |
2721 | |
2722 | /// mergeParamDeclAttributes - Copy attributes from the old parameter |
2723 | /// to the new one. |
2724 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, |
2725 | const ParmVarDecl *oldDecl, |
2726 | Sema &S) { |
2727 | // C++11 [dcl.attr.depend]p2: |
2728 | // The first declaration of a function shall specify the |
2729 | // carries_dependency attribute for its declarator-id if any declaration |
2730 | // of the function specifies the carries_dependency attribute. |
2731 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); |
2732 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { |
2733 | S.Diag(CDA->getLocation(), |
2734 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; |
2735 | // Find the first declaration of the parameter. |
2736 | // FIXME: Should we build redeclaration chains for function parameters? |
2737 | const FunctionDecl *FirstFD = |
2738 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); |
2739 | const ParmVarDecl *FirstVD = |
2740 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); |
2741 | S.Diag(FirstVD->getLocation(), |
2742 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; |
2743 | } |
2744 | |
2745 | if (!oldDecl->hasAttrs()) |
2746 | return; |
2747 | |
2748 | bool foundAny = newDecl->hasAttrs(); |
2749 | |
2750 | // Ensure that any moving of objects within the allocated map is |
2751 | // done before we process them. |
2752 | if (!foundAny) newDecl->setAttrs(AttrVec()); |
2753 | |
2754 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { |
2755 | if (!DeclHasAttr(newDecl, I)) { |
2756 | InheritableAttr *newAttr = |
2757 | cast<InheritableParamAttr>(I->clone(S.Context)); |
2758 | newAttr->setInherited(true); |
2759 | newDecl->addAttr(newAttr); |
2760 | foundAny = true; |
2761 | } |
2762 | } |
2763 | |
2764 | if (!foundAny) newDecl->dropAttrs(); |
2765 | } |
2766 | |
2767 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, |
2768 | const ParmVarDecl *OldParam, |
2769 | Sema &S) { |
2770 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { |
2771 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { |
2772 | if (*Oldnullability != *Newnullability) { |
2773 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) |
2774 | << DiagNullabilityKind( |
2775 | *Newnullability, |
2776 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) |
2777 | != 0)) |
2778 | << DiagNullabilityKind( |
2779 | *Oldnullability, |
2780 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) |
2781 | != 0)); |
2782 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); |
2783 | } |
2784 | } else { |
2785 | QualType NewT = NewParam->getType(); |
2786 | NewT = S.Context.getAttributedType( |
2787 | AttributedType::getNullabilityAttrKind(*Oldnullability), |
2788 | NewT, NewT); |
2789 | NewParam->setType(NewT); |
2790 | } |
2791 | } |
2792 | } |
2793 | |
2794 | namespace { |
2795 | |
2796 | /// Used in MergeFunctionDecl to keep track of function parameters in |
2797 | /// C. |
2798 | struct GNUCompatibleParamWarning { |
2799 | ParmVarDecl *OldParm; |
2800 | ParmVarDecl *NewParm; |
2801 | QualType PromotedType; |
2802 | }; |
2803 | |
2804 | } // end anonymous namespace |
2805 | |
2806 | /// getSpecialMember - get the special member enum for a method. |
2807 | Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { |
2808 | if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { |
2809 | if (Ctor->isDefaultConstructor()) |
2810 | return Sema::CXXDefaultConstructor; |
2811 | |
2812 | if (Ctor->isCopyConstructor()) |
2813 | return Sema::CXXCopyConstructor; |
2814 | |
2815 | if (Ctor->isMoveConstructor()) |
2816 | return Sema::CXXMoveConstructor; |
2817 | } else if (isa<CXXDestructorDecl>(MD)) { |
2818 | return Sema::CXXDestructor; |
2819 | } else if (MD->isCopyAssignmentOperator()) { |
2820 | return Sema::CXXCopyAssignment; |
2821 | } else if (MD->isMoveAssignmentOperator()) { |
2822 | return Sema::CXXMoveAssignment; |
2823 | } |
2824 | |
2825 | return Sema::CXXInvalid; |
2826 | } |
2827 | |
2828 | // Determine whether the previous declaration was a definition, implicit |
2829 | // declaration, or a declaration. |
2830 | template <typename T> |
2831 | static std::pair<diag::kind, SourceLocation> |
2832 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { |
2833 | diag::kind PrevDiag; |
2834 | SourceLocation OldLocation = Old->getLocation(); |
2835 | if (Old->isThisDeclarationADefinition()) |
2836 | PrevDiag = diag::note_previous_definition; |
2837 | else if (Old->isImplicit()) { |
2838 | PrevDiag = diag::note_previous_implicit_declaration; |
2839 | if (OldLocation.isInvalid()) |
2840 | OldLocation = New->getLocation(); |
2841 | } else |
2842 | PrevDiag = diag::note_previous_declaration; |
2843 | return std::make_pair(PrevDiag, OldLocation); |
2844 | } |
2845 | |
2846 | /// canRedefineFunction - checks if a function can be redefined. Currently, |
2847 | /// only extern inline functions can be redefined, and even then only in |
2848 | /// GNU89 mode. |
2849 | static bool canRedefineFunction(const FunctionDecl *FD, |
2850 | const LangOptions& LangOpts) { |
2851 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && |
2852 | !LangOpts.CPlusPlus && |
2853 | FD->isInlineSpecified() && |
2854 | FD->getStorageClass() == SC_Extern); |
2855 | } |
2856 | |
2857 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { |
2858 | const AttributedType *AT = T->getAs<AttributedType>(); |
2859 | while (AT && !AT->isCallingConv()) |
2860 | AT = AT->getModifiedType()->getAs<AttributedType>(); |
2861 | return AT; |
2862 | } |
2863 | |
2864 | template <typename T> |
2865 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { |
2866 | const DeclContext *DC = Old->getDeclContext(); |
2867 | if (DC->isRecord()) |
2868 | return false; |
2869 | |
2870 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); |
2871 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) |
2872 | return true; |
2873 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) |
2874 | return true; |
2875 | return false; |
2876 | } |
2877 | |
2878 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } |
2879 | static bool isExternC(VarTemplateDecl *) { return false; } |
2880 | |
2881 | /// Check whether a redeclaration of an entity introduced by a |
2882 | /// using-declaration is valid, given that we know it's not an overload |
2883 | /// (nor a hidden tag declaration). |
2884 | template<typename ExpectedDecl> |
2885 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, |
2886 | ExpectedDecl *New) { |
2887 | // C++11 [basic.scope.declarative]p4: |
2888 | // Given a set of declarations in a single declarative region, each of |
2889 | // which specifies the same unqualified name, |
2890 | // -- they shall all refer to the same entity, or all refer to functions |
2891 | // and function templates; or |
2892 | // -- exactly one declaration shall declare a class name or enumeration |
2893 | // name that is not a typedef name and the other declarations shall all |
2894 | // refer to the same variable or enumerator, or all refer to functions |
2895 | // and function templates; in this case the class name or enumeration |
2896 | // name is hidden (3.3.10). |
2897 | |
2898 | // C++11 [namespace.udecl]p14: |
2899 | // If a function declaration in namespace scope or block scope has the |
2900 | // same name and the same parameter-type-list as a function introduced |
2901 | // by a using-declaration, and the declarations do not declare the same |
2902 | // function, the program is ill-formed. |
2903 | |
2904 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); |
2905 | if (Old && |
2906 | !Old->getDeclContext()->getRedeclContext()->Equals( |
2907 | New->getDeclContext()->getRedeclContext()) && |
2908 | !(isExternC(Old) && isExternC(New))) |
2909 | Old = nullptr; |
2910 | |
2911 | if (!Old) { |
2912 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); |
2913 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); |
2914 | S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; |
2915 | return true; |
2916 | } |
2917 | return false; |
2918 | } |
2919 | |
2920 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, |
2921 | const FunctionDecl *B) { |
2922 | assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast <void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 2922, __PRETTY_FUNCTION__)); |
2923 | |
2924 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { |
2925 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); |
2926 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); |
2927 | if (AttrA == AttrB) |
2928 | return true; |
2929 | return AttrA && AttrB && AttrA->getType() == AttrB->getType(); |
2930 | }; |
2931 | |
2932 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); |
2933 | } |
2934 | |
2935 | /// If necessary, adjust the semantic declaration context for a qualified |
2936 | /// declaration to name the correct inline namespace within the qualifier. |
2937 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, |
2938 | DeclaratorDecl *OldD) { |
2939 | // The only case where we need to update the DeclContext is when |
2940 | // redeclaration lookup for a qualified name finds a declaration |
2941 | // in an inline namespace within the context named by the qualifier: |
2942 | // |
2943 | // inline namespace N { int f(); } |
2944 | // int ::f(); // Sema DC needs adjusting from :: to N::. |
2945 | // |
2946 | // For unqualified declarations, the semantic context *can* change |
2947 | // along the redeclaration chain (for local extern declarations, |
2948 | // extern "C" declarations, and friend declarations in particular). |
2949 | if (!NewD->getQualifier()) |
2950 | return; |
2951 | |
2952 | // NewD is probably already in the right context. |
2953 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); |
2954 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); |
2955 | if (NamedDC->Equals(SemaDC)) |
2956 | return; |
2957 | |
2958 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 2960, __PRETTY_FUNCTION__)) |
2959 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 2960, __PRETTY_FUNCTION__)) |
2960 | "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 2960, __PRETTY_FUNCTION__)); |
2961 | |
2962 | auto *LexDC = NewD->getLexicalDeclContext(); |
2963 | auto FixSemaDC = [=](NamedDecl *D) { |
2964 | if (!D) |
2965 | return; |
2966 | D->setDeclContext(SemaDC); |
2967 | D->setLexicalDeclContext(LexDC); |
2968 | }; |
2969 | |
2970 | FixSemaDC(NewD); |
2971 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) |
2972 | FixSemaDC(FD->getDescribedFunctionTemplate()); |
2973 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) |
2974 | FixSemaDC(VD->getDescribedVarTemplate()); |
2975 | } |
2976 | |
2977 | /// MergeFunctionDecl - We just parsed a function 'New' from |
2978 | /// declarator D which has the same name and scope as a previous |
2979 | /// declaration 'Old'. Figure out how to resolve this situation, |
2980 | /// merging decls or emitting diagnostics as appropriate. |
2981 | /// |
2982 | /// In C++, New and Old must be declarations that are not |
2983 | /// overloaded. Use IsOverload to determine whether New and Old are |
2984 | /// overloaded, and to select the Old declaration that New should be |
2985 | /// merged with. |
2986 | /// |
2987 | /// Returns true if there was an error, false otherwise. |
2988 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, |
2989 | Scope *S, bool MergeTypeWithOld) { |
2990 | // Verify the old decl was also a function. |
2991 | FunctionDecl *Old = OldD->getAsFunction(); |
2992 | if (!Old) { |
2993 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { |
2994 | if (New->getFriendObjectKind()) { |
2995 | Diag(New->getLocation(), diag::err_using_decl_friend); |
2996 | Diag(Shadow->getTargetDecl()->getLocation(), |
2997 | diag::note_using_decl_target); |
2998 | Diag(Shadow->getUsingDecl()->getLocation(), |
2999 | diag::note_using_decl) << 0; |
3000 | return true; |
3001 | } |
3002 | |
3003 | // Check whether the two declarations might declare the same function. |
3004 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) |
3005 | return true; |
3006 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); |
3007 | } else { |
3008 | Diag(New->getLocation(), diag::err_redefinition_different_kind) |
3009 | << New->getDeclName(); |
3010 | notePreviousDefinition(OldD, New->getLocation()); |
3011 | return true; |
3012 | } |
3013 | } |
3014 | |
3015 | // If the old declaration is invalid, just give up here. |
3016 | if (Old->isInvalidDecl()) |
3017 | return true; |
3018 | |
3019 | // Disallow redeclaration of some builtins. |
3020 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { |
3021 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); |
3022 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) |
3023 | << Old << Old->getType(); |
3024 | return true; |
3025 | } |
3026 | |
3027 | diag::kind PrevDiag; |
3028 | SourceLocation OldLocation; |
3029 | std::tie(PrevDiag, OldLocation) = |
3030 | getNoteDiagForInvalidRedeclaration(Old, New); |
3031 | |
3032 | // Don't complain about this if we're in GNU89 mode and the old function |
3033 | // is an extern inline function. |
3034 | // Don't complain about specializations. They are not supposed to have |
3035 | // storage classes. |
3036 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && |
3037 | New->getStorageClass() == SC_Static && |
3038 | Old->hasExternalFormalLinkage() && |
3039 | !New->getTemplateSpecializationInfo() && |
3040 | !canRedefineFunction(Old, getLangOpts())) { |
3041 | if (getLangOpts().MicrosoftExt) { |
3042 | Diag(New->getLocation(), diag::ext_static_non_static) << New; |
3043 | Diag(OldLocation, PrevDiag); |
3044 | } else { |
3045 | Diag(New->getLocation(), diag::err_static_non_static) << New; |
3046 | Diag(OldLocation, PrevDiag); |
3047 | return true; |
3048 | } |
3049 | } |
3050 | |
3051 | if (New->hasAttr<InternalLinkageAttr>() && |
3052 | !Old->hasAttr<InternalLinkageAttr>()) { |
3053 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) |
3054 | << New->getDeclName(); |
3055 | notePreviousDefinition(Old, New->getLocation()); |
3056 | New->dropAttr<InternalLinkageAttr>(); |
3057 | } |
3058 | |
3059 | if (CheckRedeclarationModuleOwnership(New, Old)) |
3060 | return true; |
3061 | |
3062 | if (!getLangOpts().CPlusPlus) { |
3063 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); |
3064 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { |
3065 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) |
3066 | << New << OldOvl; |
3067 | |
3068 | // Try our best to find a decl that actually has the overloadable |
3069 | // attribute for the note. In most cases (e.g. programs with only one |
3070 | // broken declaration/definition), this won't matter. |
3071 | // |
3072 | // FIXME: We could do this if we juggled some extra state in |
3073 | // OverloadableAttr, rather than just removing it. |
3074 | const Decl *DiagOld = Old; |
3075 | if (OldOvl) { |
3076 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { |
3077 | const auto *A = D->getAttr<OverloadableAttr>(); |
3078 | return A && !A->isImplicit(); |
3079 | }); |
3080 | // If we've implicitly added *all* of the overloadable attrs to this |
3081 | // chain, emitting a "previous redecl" note is pointless. |
3082 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; |
3083 | } |
3084 | |
3085 | if (DiagOld) |
3086 | Diag(DiagOld->getLocation(), |
3087 | diag::note_attribute_overloadable_prev_overload) |
3088 | << OldOvl; |
3089 | |
3090 | if (OldOvl) |
3091 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); |
3092 | else |
3093 | New->dropAttr<OverloadableAttr>(); |
3094 | } |
3095 | } |
3096 | |
3097 | // If a function is first declared with a calling convention, but is later |
3098 | // declared or defined without one, all following decls assume the calling |
3099 | // convention of the first. |
3100 | // |
3101 | // It's OK if a function is first declared without a calling convention, |
3102 | // but is later declared or defined with the default calling convention. |
3103 | // |
3104 | // To test if either decl has an explicit calling convention, we look for |
3105 | // AttributedType sugar nodes on the type as written. If they are missing or |
3106 | // were canonicalized away, we assume the calling convention was implicit. |
3107 | // |
3108 | // Note also that we DO NOT return at this point, because we still have |
3109 | // other tests to run. |
3110 | QualType OldQType = Context.getCanonicalType(Old->getType()); |
3111 | QualType NewQType = Context.getCanonicalType(New->getType()); |
3112 | const FunctionType *OldType = cast<FunctionType>(OldQType); |
3113 | const FunctionType *NewType = cast<FunctionType>(NewQType); |
3114 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); |
3115 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); |
3116 | bool RequiresAdjustment = false; |
3117 | |
3118 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { |
3119 | FunctionDecl *First = Old->getFirstDecl(); |
3120 | const FunctionType *FT = |
3121 | First->getType().getCanonicalType()->castAs<FunctionType>(); |
3122 | FunctionType::ExtInfo FI = FT->getExtInfo(); |
3123 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); |
3124 | if (!NewCCExplicit) { |
3125 | // Inherit the CC from the previous declaration if it was specified |
3126 | // there but not here. |
3127 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); |
3128 | RequiresAdjustment = true; |
3129 | } else { |
3130 | // Calling conventions aren't compatible, so complain. |
3131 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); |
3132 | Diag(New->getLocation(), diag::err_cconv_change) |
3133 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) |
3134 | << !FirstCCExplicit |
3135 | << (!FirstCCExplicit ? "" : |
3136 | FunctionType::getNameForCallConv(FI.getCC())); |
3137 | |
3138 | // Put the note on the first decl, since it is the one that matters. |
3139 | Diag(First->getLocation(), diag::note_previous_declaration); |
3140 | return true; |
3141 | } |
3142 | } |
3143 | |
3144 | // FIXME: diagnose the other way around? |
3145 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { |
3146 | NewTypeInfo = NewTypeInfo.withNoReturn(true); |
3147 | RequiresAdjustment = true; |
3148 | } |
3149 | |
3150 | // Merge regparm attribute. |
3151 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || |
3152 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { |
3153 | if (NewTypeInfo.getHasRegParm()) { |
3154 | Diag(New->getLocation(), diag::err_regparm_mismatch) |
3155 | << NewType->getRegParmType() |
3156 | << OldType->getRegParmType(); |
3157 | Diag(OldLocation, diag::note_previous_declaration); |
3158 | return true; |
3159 | } |
3160 | |
3161 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); |
3162 | RequiresAdjustment = true; |
3163 | } |
3164 | |
3165 | // Merge ns_returns_retained attribute. |
3166 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { |
3167 | if (NewTypeInfo.getProducesResult()) { |
3168 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) |
3169 | << "'ns_returns_retained'"; |
3170 | Diag(OldLocation, diag::note_previous_declaration); |
3171 | return true; |
3172 | } |
3173 | |
3174 | NewTypeInfo = NewTypeInfo.withProducesResult(true); |
3175 | RequiresAdjustment = true; |
3176 | } |
3177 | |
3178 | if (OldTypeInfo.getNoCallerSavedRegs() != |
3179 | NewTypeInfo.getNoCallerSavedRegs()) { |
3180 | if (NewTypeInfo.getNoCallerSavedRegs()) { |
3181 | AnyX86NoCallerSavedRegistersAttr *Attr = |
3182 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); |
3183 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; |
3184 | Diag(OldLocation, diag::note_previous_declaration); |
3185 | return true; |
3186 | } |
3187 | |
3188 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); |
3189 | RequiresAdjustment = true; |
3190 | } |
3191 | |
3192 | if (RequiresAdjustment) { |
3193 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); |
3194 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); |
3195 | |
3196 | QualType AdjustedQT = QualType(AdjustedType, 0); |
3197 | LangAS AS = Old->getType().getAddressSpace(); |
3198 | AdjustedQT = Context.getAddrSpaceQualType(AdjustedQT, AS); |
3199 | |
3200 | New->setType(AdjustedQT); |
3201 | NewQType = Context.getCanonicalType(New->getType()); |
3202 | NewType = cast<FunctionType>(NewQType); |
Value stored to 'NewType' is never read | |
3203 | } |
3204 | |
3205 | // If this redeclaration makes the function inline, we may need to add it to |
3206 | // UndefinedButUsed. |
3207 | if (!Old->isInlined() && New->isInlined() && |
3208 | !New->hasAttr<GNUInlineAttr>() && |
3209 | !getLangOpts().GNUInline && |
3210 | Old->isUsed(false) && |
3211 | !Old->isDefined() && !New->isThisDeclarationADefinition()) |
3212 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), |
3213 | SourceLocation())); |
3214 | |
3215 | // If this redeclaration makes it newly gnu_inline, we don't want to warn |
3216 | // about it. |
3217 | if (New->hasAttr<GNUInlineAttr>() && |
3218 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { |
3219 | UndefinedButUsed.erase(Old->getCanonicalDecl()); |
3220 | } |
3221 | |
3222 | // If pass_object_size params don't match up perfectly, this isn't a valid |
3223 | // redeclaration. |
3224 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && |
3225 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { |
3226 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) |
3227 | << New->getDeclName(); |
3228 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); |
3229 | return true; |
3230 | } |
3231 | |
3232 | if (getLangOpts().CPlusPlus) { |
3233 | // C++1z [over.load]p2 |
3234 | // Certain function declarations cannot be overloaded: |
3235 | // -- Function declarations that differ only in the return type, |
3236 | // the exception specification, or both cannot be overloaded. |
3237 | |
3238 | // Check the exception specifications match. This may recompute the type of |
3239 | // both Old and New if it resolved exception specifications, so grab the |
3240 | // types again after this. Because this updates the type, we do this before |
3241 | // any of the other checks below, which may update the "de facto" NewQType |
3242 | // but do not necessarily update the type of New. |
3243 | if (CheckEquivalentExceptionSpec(Old, New)) |
3244 | return true; |
3245 | OldQType = Context.getCanonicalType(Old->getType()); |
3246 | NewQType = Context.getCanonicalType(New->getType()); |
3247 | |
3248 | // Go back to the type source info to compare the declared return types, |
3249 | // per C++1y [dcl.type.auto]p13: |
3250 | // Redeclarations or specializations of a function or function template |
3251 | // with a declared return type that uses a placeholder type shall also |
3252 | // use that placeholder, not a deduced type. |
3253 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); |
3254 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); |
3255 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && |
3256 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, |
3257 | OldDeclaredReturnType)) { |
3258 | QualType ResQT; |
3259 | if (NewDeclaredReturnType->isObjCObjectPointerType() && |
3260 | OldDeclaredReturnType->isObjCObjectPointerType()) |
3261 | // FIXME: This does the wrong thing for a deduced return type. |
3262 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); |
3263 | if (ResQT.isNull()) { |
3264 | if (New->isCXXClassMember() && New->isOutOfLine()) |
3265 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) |
3266 | << New << New->getReturnTypeSourceRange(); |
3267 | else |
3268 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) |
3269 | << New->getReturnTypeSourceRange(); |
3270 | Diag(OldLocation, PrevDiag) << Old << Old->getType() |
3271 | << Old->getReturnTypeSourceRange(); |
3272 | return true; |
3273 | } |
3274 | else |
3275 | NewQType = ResQT; |
3276 | } |
3277 | |
3278 | QualType OldReturnType = OldType->getReturnType(); |
3279 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); |
3280 | if (OldReturnType != NewReturnType) { |
3281 | // If this function has a deduced return type and has already been |
3282 | // defined, copy the deduced value from the old declaration. |
3283 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); |
3284 | if (OldAT && OldAT->isDeduced()) { |
3285 | New->setType( |
3286 | SubstAutoType(New->getType(), |
3287 | OldAT->isDependentType() ? Context.DependentTy |
3288 | : OldAT->getDeducedType())); |
3289 | NewQType = Context.getCanonicalType( |
3290 | SubstAutoType(NewQType, |
3291 | OldAT->isDependentType() ? Context.DependentTy |
3292 | : OldAT->getDeducedType())); |
3293 | } |
3294 | } |
3295 | |
3296 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); |
3297 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); |
3298 | if (OldMethod && NewMethod) { |
3299 | // Preserve triviality. |
3300 | NewMethod->setTrivial(OldMethod->isTrivial()); |
3301 | |
3302 | // MSVC allows explicit template specialization at class scope: |
3303 | // 2 CXXMethodDecls referring to the same function will be injected. |
3304 | // We don't want a redeclaration error. |
3305 | bool IsClassScopeExplicitSpecialization = |
3306 | OldMethod->isFunctionTemplateSpecialization() && |
3307 | NewMethod->isFunctionTemplateSpecialization(); |
3308 | bool isFriend = NewMethod->getFriendObjectKind(); |
3309 | |
3310 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && |
3311 | !IsClassScopeExplicitSpecialization) { |
3312 | // -- Member function declarations with the same name and the |
3313 | // same parameter types cannot be overloaded if any of them |
3314 | // is a static member function declaration. |
3315 | if (OldMethod->isStatic() != NewMethod->isStatic()) { |
3316 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); |
3317 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); |
3318 | return true; |
3319 | } |
3320 | |
3321 | // C++ [class.mem]p1: |
3322 | // [...] A member shall not be declared twice in the |
3323 | // member-specification, except that a nested class or member |
3324 | // class template can be declared and then later defined. |
3325 | if (!inTemplateInstantiation()) { |
3326 | unsigned NewDiag; |
3327 | if (isa<CXXConstructorDecl>(OldMethod)) |
3328 | NewDiag = diag::err_constructor_redeclared; |
3329 | else if (isa<CXXDestructorDecl>(NewMethod)) |
3330 | NewDiag = diag::err_destructor_redeclared; |
3331 | else if (isa<CXXConversionDecl>(NewMethod)) |
3332 | NewDiag = diag::err_conv_function_redeclared; |
3333 | else |
3334 | NewDiag = diag::err_member_redeclared; |
3335 | |
3336 | Diag(New->getLocation(), NewDiag); |
3337 | } else { |
3338 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) |
3339 | << New << New->getType(); |
3340 | } |
3341 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); |
3342 | return true; |
3343 | |
3344 | // Complain if this is an explicit declaration of a special |
3345 | // member that was initially declared implicitly. |
3346 | // |
3347 | // As an exception, it's okay to befriend such methods in order |
3348 | // to permit the implicit constructor/destructor/operator calls. |
3349 | } else if (OldMethod->isImplicit()) { |
3350 | if (isFriend) { |
3351 | NewMethod->setImplicit(); |
3352 | } else { |
3353 | Diag(NewMethod->getLocation(), |
3354 | diag::err_definition_of_implicitly_declared_member) |
3355 | << New << getSpecialMember(OldMethod); |
3356 | return true; |
3357 | } |
3358 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { |
3359 | Diag(NewMethod->getLocation(), |
3360 | diag::err_definition_of_explicitly_defaulted_member) |
3361 | << getSpecialMember(OldMethod); |
3362 | return true; |
3363 | } |
3364 | } |
3365 | |
3366 | // C++11 [dcl.attr.noreturn]p1: |
3367 | // The first declaration of a function shall specify the noreturn |
3368 | // attribute if any declaration of that function specifies the noreturn |
3369 | // attribute. |
3370 | const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); |
3371 | if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { |
3372 | Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); |
3373 | Diag(Old->getFirstDecl()->getLocation(), |
3374 | diag::note_noreturn_missing_first_decl); |
3375 | } |
3376 | |
3377 | // C++11 [dcl.attr.depend]p2: |
3378 | // The first declaration of a function shall specify the |
3379 | // carries_dependency attribute for its declarator-id if any declaration |
3380 | // of the function specifies the carries_dependency attribute. |
3381 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); |
3382 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { |
3383 | Diag(CDA->getLocation(), |
3384 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; |
3385 | Diag(Old->getFirstDecl()->getLocation(), |
3386 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; |
3387 | } |
3388 | |
3389 | // (C++98 8.3.5p3): |
3390 | // All declarations for a function shall agree exactly in both the |
3391 | // return type and the parameter-type-list. |
3392 | // We also want to respect all the extended bits except noreturn. |
3393 | |
3394 | // noreturn should now match unless the old type info didn't have it. |
3395 | QualType OldQTypeForComparison = OldQType; |
3396 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { |
3397 | auto *OldType = OldQType->castAs<FunctionProtoType>(); |
3398 | const FunctionType *OldTypeForComparison |
3399 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); |
3400 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); |
3401 | assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void> (0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 3401, __PRETTY_FUNCTION__)); |
3402 | } |
3403 | |
3404 | if (haveIncompatibleLanguageLinkages(Old, New)) { |
3405 | // As a special case, retain the language linkage from previous |
3406 | // declarations of a friend function as an extension. |
3407 | // |
3408 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC |
3409 | // and is useful because there's otherwise no way to specify language |
3410 | // linkage within class scope. |
3411 | // |
3412 | // Check cautiously as the friend object kind isn't yet complete. |
3413 | if (New->getFriendObjectKind() != Decl::FOK_None) { |
3414 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; |
3415 | Diag(OldLocation, PrevDiag); |
3416 | } else { |
3417 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; |
3418 | Diag(OldLocation, PrevDiag); |
3419 | return true; |
3420 | } |
3421 | } |
3422 | |
3423 | if (OldQTypeForComparison == NewQType) |
3424 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
3425 | |
3426 | // If the types are imprecise (due to dependent constructs in friends or |
3427 | // local extern declarations), it's OK if they differ. We'll check again |
3428 | // during instantiation. |
3429 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) |
3430 | return false; |
3431 | |
3432 | // Fall through for conflicting redeclarations and redefinitions. |
3433 | } |
3434 | |
3435 | // C: Function types need to be compatible, not identical. This handles |
3436 | // duplicate function decls like "void f(int); void f(enum X);" properly. |
3437 | if (!getLangOpts().CPlusPlus && |
3438 | Context.typesAreCompatible(OldQType, NewQType)) { |
3439 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); |
3440 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); |
3441 | const FunctionProtoType *OldProto = nullptr; |
3442 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && |
3443 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { |
3444 | // The old declaration provided a function prototype, but the |
3445 | // new declaration does not. Merge in the prototype. |
3446 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C" ) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 3446, __PRETTY_FUNCTION__)); |
3447 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); |
3448 | NewQType = |
3449 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, |
3450 | OldProto->getExtProtoInfo()); |
3451 | New->setType(NewQType); |
3452 | New->setHasInheritedPrototype(); |
3453 | |
3454 | // Synthesize parameters with the same types. |
3455 | SmallVector<ParmVarDecl*, 16> Params; |
3456 | for (const auto &ParamType : OldProto->param_types()) { |
3457 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), |
3458 | SourceLocation(), nullptr, |
3459 | ParamType, /*TInfo=*/nullptr, |
3460 | SC_None, nullptr); |
3461 | Param->setScopeInfo(0, Params.size()); |
3462 | Param->setImplicit(); |
3463 | Params.push_back(Param); |
3464 | } |
3465 | |
3466 | New->setParams(Params); |
3467 | } |
3468 | |
3469 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
3470 | } |
3471 | |
3472 | // GNU C permits a K&R definition to follow a prototype declaration |
3473 | // if the declared types of the parameters in the K&R definition |
3474 | // match the types in the prototype declaration, even when the |
3475 | // promoted types of the parameters from the K&R definition differ |
3476 | // from the types in the prototype. GCC then keeps the types from |
3477 | // the prototype. |
3478 | // |
3479 | // If a variadic prototype is followed by a non-variadic K&R definition, |
3480 | // the K&R definition becomes variadic. This is sort of an edge case, but |
3481 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and |
3482 | // C99 6.9.1p8. |
3483 | if (!getLangOpts().CPlusPlus && |
3484 | Old->hasPrototype() && !New->hasPrototype() && |
3485 | New->getType()->getAs<FunctionProtoType>() && |
3486 | Old->getNumParams() == New->getNumParams()) { |
3487 | SmallVector<QualType, 16> ArgTypes; |
3488 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; |
3489 | const FunctionProtoType *OldProto |
3490 | = Old->getType()->getAs<FunctionProtoType>(); |
3491 | const FunctionProtoType *NewProto |
3492 | = New->getType()->getAs<FunctionProtoType>(); |
3493 | |
3494 | // Determine whether this is the GNU C extension. |
3495 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), |
3496 | NewProto->getReturnType()); |
3497 | bool LooseCompatible = !MergedReturn.isNull(); |
3498 | for (unsigned Idx = 0, End = Old->getNumParams(); |
3499 | LooseCompatible && Idx != End; ++Idx) { |
3500 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); |
3501 | ParmVarDecl *NewParm = New->getParamDecl(Idx); |
3502 | if (Context.typesAreCompatible(OldParm->getType(), |
3503 | NewProto->getParamType(Idx))) { |
3504 | ArgTypes.push_back(NewParm->getType()); |
3505 | } else if (Context.typesAreCompatible(OldParm->getType(), |
3506 | NewParm->getType(), |
3507 | /*CompareUnqualified=*/true)) { |
3508 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, |
3509 | NewProto->getParamType(Idx) }; |
3510 | Warnings.push_back(Warn); |
3511 | ArgTypes.push_back(NewParm->getType()); |
3512 | } else |
3513 | LooseCompatible = false; |
3514 | } |
3515 | |
3516 | if (LooseCompatible) { |
3517 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { |
3518 | Diag(Warnings[Warn].NewParm->getLocation(), |
3519 | diag::ext_param_promoted_not_compatible_with_prototype) |
3520 | << Warnings[Warn].PromotedType |
3521 | << Warnings[Warn].OldParm->getType(); |
3522 | if (Warnings[Warn].OldParm->getLocation().isValid()) |
3523 | Diag(Warnings[Warn].OldParm->getLocation(), |
3524 | diag::note_previous_declaration); |
3525 | } |
3526 | |
3527 | if (MergeTypeWithOld) |
3528 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, |
3529 | OldProto->getExtProtoInfo())); |
3530 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); |
3531 | } |
3532 | |
3533 | // Fall through to diagnose conflicting types. |
3534 | } |
3535 | |
3536 | // A function that has already been declared has been redeclared or |
3537 | // defined with a different type; show an appropriate diagnostic. |
3538 | |
3539 | // If the previous declaration was an implicitly-generated builtin |
3540 | // declaration, then at the very least we should use a specialized note. |
3541 | unsigned BuiltinID; |
3542 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { |
3543 | // If it's actually a library-defined builtin function like 'malloc' |
3544 | // or 'printf', just warn about the incompatible redeclaration. |
3545 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { |
3546 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; |
3547 | Diag(OldLocation, diag::note_previous_builtin_declaration) |
3548 | << Old << Old->getType(); |
3549 | |
3550 | // If this is a global redeclaration, just forget hereafter |
3551 | // about the "builtin-ness" of the function. |
3552 | // |
3553 | // Doing this for local extern declarations is problematic. If |
3554 | // the builtin declaration remains visible, a second invalid |
3555 | // local declaration will produce a hard error; if it doesn't |
3556 | // remain visible, a single bogus local redeclaration (which is |
3557 | // actually only a warning) could break all the downstream code. |
3558 | if (!New->getLexicalDeclContext()->isFunctionOrMethod()) |
3559 | New->getIdentifier()->revertBuiltin(); |
3560 | |
3561 | return false; |
3562 | } |
3563 | |
3564 | PrevDiag = diag::note_previous_builtin_declaration; |
3565 | } |
3566 | |
3567 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); |
3568 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); |
3569 | return true; |
3570 | } |
3571 | |
3572 | /// Completes the merge of two function declarations that are |
3573 | /// known to be compatible. |
3574 | /// |
3575 | /// This routine handles the merging of attributes and other |
3576 | /// properties of function declarations from the old declaration to |
3577 | /// the new declaration, once we know that New is in fact a |
3578 | /// redeclaration of Old. |
3579 | /// |
3580 | /// \returns false |
3581 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, |
3582 | Scope *S, bool MergeTypeWithOld) { |
3583 | // Merge the attributes |
3584 | mergeDeclAttributes(New, Old); |
3585 | |
3586 | // Merge "pure" flag. |
3587 | if (Old->isPure()) |
3588 | New->setPure(); |
3589 | |
3590 | // Merge "used" flag. |
3591 | if (Old->getMostRecentDecl()->isUsed(false)) |
3592 | New->setIsUsed(); |
3593 | |
3594 | // Merge attributes from the parameters. These can mismatch with K&R |
3595 | // declarations. |
3596 | if (New->getNumParams() == Old->getNumParams()) |
3597 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { |
3598 | ParmVarDecl *NewParam = New->getParamDecl(i); |
3599 | ParmVarDecl *OldParam = Old->getParamDecl(i); |
3600 | mergeParamDeclAttributes(NewParam, OldParam, *this); |
3601 | mergeParamDeclTypes(NewParam, OldParam, *this); |
3602 | } |
3603 | |
3604 | if (getLangOpts().CPlusPlus) |
3605 | return MergeCXXFunctionDecl(New, Old, S); |
3606 | |
3607 | // Merge the function types so the we get the composite types for the return |
3608 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl |
3609 | // was visible. |
3610 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); |
3611 | if (!Merged.isNull() && MergeTypeWithOld) |
3612 | New->setType(Merged); |
3613 | |
3614 | return false; |
3615 | } |
3616 | |
3617 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, |
3618 | ObjCMethodDecl *oldMethod) { |
3619 | // Merge the attributes, including deprecated/unavailable |
3620 | AvailabilityMergeKind MergeKind = |
3621 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) |
3622 | ? AMK_ProtocolImplementation |
3623 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration |
3624 | : AMK_Override; |
3625 | |
3626 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); |
3627 | |
3628 | // Merge attributes from the parameters. |
3629 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), |
3630 | oe = oldMethod->param_end(); |
3631 | for (ObjCMethodDecl::param_iterator |
3632 | ni = newMethod->param_begin(), ne = newMethod->param_end(); |
3633 | ni != ne && oi != oe; ++ni, ++oi) |
3634 | mergeParamDeclAttributes(*ni, *oi, *this); |
3635 | |
3636 | CheckObjCMethodOverride(newMethod, oldMethod); |
3637 | } |
3638 | |
3639 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { |
3640 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType() )) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 3640, __PRETTY_FUNCTION__)); |
3641 | |
3642 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() |
3643 | ? diag::err_redefinition_different_type |
3644 | : diag::err_redeclaration_different_type) |
3645 | << New->getDeclName() << New->getType() << Old->getType(); |
3646 | |
3647 | diag::kind PrevDiag; |
3648 | SourceLocation OldLocation; |
3649 | std::tie(PrevDiag, OldLocation) |
3650 | = getNoteDiagForInvalidRedeclaration(Old, New); |
3651 | S.Diag(OldLocation, PrevDiag); |
3652 | New->setInvalidDecl(); |
3653 | } |
3654 | |
3655 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and |
3656 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, |
3657 | /// emitting diagnostics as appropriate. |
3658 | /// |
3659 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back |
3660 | /// to here in AddInitializerToDecl. We can't check them before the initializer |
3661 | /// is attached. |
3662 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, |
3663 | bool MergeTypeWithOld) { |
3664 | if (New->isInvalidDecl() || Old->isInvalidDecl()) |
3665 | return; |
3666 | |
3667 | QualType MergedT; |
3668 | if (getLangOpts().CPlusPlus) { |
3669 | if (New->getType()->isUndeducedType()) { |
3670 | // We don't know what the new type is until the initializer is attached. |
3671 | return; |
3672 | } else if (Context.hasSameType(New->getType(), Old->getType())) { |
3673 | // These could still be something that needs exception specs checked. |
3674 | return MergeVarDeclExceptionSpecs(New, Old); |
3675 | } |
3676 | // C++ [basic.link]p10: |
3677 | // [...] the types specified by all declarations referring to a given |
3678 | // object or function shall be identical, except that declarations for an |
3679 | // array object can specify array types that differ by the presence or |
3680 | // absence of a major array bound (8.3.4). |
3681 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { |
3682 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); |
3683 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); |
3684 | |
3685 | // We are merging a variable declaration New into Old. If it has an array |
3686 | // bound, and that bound differs from Old's bound, we should diagnose the |
3687 | // mismatch. |
3688 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { |
3689 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; |
3690 | PrevVD = PrevVD->getPreviousDecl()) { |
3691 | const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); |
3692 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) |
3693 | continue; |
3694 | |
3695 | if (!Context.hasSameType(NewArray, PrevVDTy)) |
3696 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); |
3697 | } |
3698 | } |
3699 | |
3700 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { |
3701 | if (Context.hasSameType(OldArray->getElementType(), |
3702 | NewArray->getElementType())) |
3703 | MergedT = New->getType(); |
3704 | } |
3705 | // FIXME: Check visibility. New is hidden but has a complete type. If New |
3706 | // has no array bound, it should not inherit one from Old, if Old is not |
3707 | // visible. |
3708 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { |
3709 | if (Context.hasSameType(OldArray->getElementType(), |
3710 | NewArray->getElementType())) |
3711 | MergedT = Old->getType(); |
3712 | } |
3713 | } |
3714 | else if (New->getType()->isObjCObjectPointerType() && |
3715 | Old->getType()->isObjCObjectPointerType()) { |
3716 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), |
3717 | Old->getType()); |
3718 | } |
3719 | } else { |
3720 | // C 6.2.7p2: |
3721 | // All declarations that refer to the same object or function shall have |
3722 | // compatible type. |
3723 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); |
3724 | } |
3725 | if (MergedT.isNull()) { |
3726 | // It's OK if we couldn't merge types if either type is dependent, for a |
3727 | // block-scope variable. In other cases (static data members of class |
3728 | // templates, variable templates, ...), we require the types to be |
3729 | // equivalent. |
3730 | // FIXME: The C++ standard doesn't say anything about this. |
3731 | if ((New->getType()->isDependentType() || |
3732 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { |
3733 | // If the old type was dependent, we can't merge with it, so the new type |
3734 | // becomes dependent for now. We'll reproduce the original type when we |
3735 | // instantiate the TypeSourceInfo for the variable. |
3736 | if (!New->getType()->isDependentType() && MergeTypeWithOld) |
3737 | New->setType(Context.DependentTy); |
3738 | return; |
3739 | } |
3740 | return diagnoseVarDeclTypeMismatch(*this, New, Old); |
3741 | } |
3742 | |
3743 | // Don't actually update the type on the new declaration if the old |
3744 | // declaration was an extern declaration in a different scope. |
3745 | if (MergeTypeWithOld) |
3746 | New->setType(MergedT); |
3747 | } |
3748 | |
3749 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, |
3750 | LookupResult &Previous) { |
3751 | // C11 6.2.7p4: |
3752 | // For an identifier with internal or external linkage declared |
3753 | // in a scope in which a prior declaration of that identifier is |
3754 | // visible, if the prior declaration specifies internal or |
3755 | // external linkage, the type of the identifier at the later |
3756 | // declaration becomes the composite type. |
3757 | // |
3758 | // If the variable isn't visible, we do not merge with its type. |
3759 | if (Previous.isShadowed()) |
3760 | return false; |
3761 | |
3762 | if (S.getLangOpts().CPlusPlus) { |
3763 | // C++11 [dcl.array]p3: |
3764 | // If there is a preceding declaration of the entity in the same |
3765 | // scope in which the bound was specified, an omitted array bound |
3766 | // is taken to be the same as in that earlier declaration. |
3767 | return NewVD->isPreviousDeclInSameBlockScope() || |
3768 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && |
3769 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); |
3770 | } else { |
3771 | // If the old declaration was function-local, don't merge with its |
3772 | // type unless we're in the same function. |
3773 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || |
3774 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); |
3775 | } |
3776 | } |
3777 | |
3778 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name |
3779 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this |
3780 | /// situation, merging decls or emitting diagnostics as appropriate. |
3781 | /// |
3782 | /// Tentative definition rules (C99 6.9.2p2) are checked by |
3783 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative |
3784 | /// definitions here, since the initializer hasn't been attached. |
3785 | /// |
3786 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { |
3787 | // If the new decl is already invalid, don't do any other checking. |
3788 | if (New->isInvalidDecl()) |
3789 | return; |
3790 | |
3791 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) |
3792 | return; |
3793 | |
3794 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); |
3795 | |
3796 | // Verify the old decl was also a variable or variable template. |
3797 | VarDecl *Old = nullptr; |
3798 | VarTemplateDecl *OldTemplate = nullptr; |
3799 | if (Previous.isSingleResult()) { |
3800 | if (NewTemplate) { |
3801 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); |
3802 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; |
3803 | |
3804 | if (auto *Shadow = |
3805 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) |
3806 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) |
3807 | return New->setInvalidDecl(); |
3808 | } else { |
3809 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); |
3810 | |
3811 | if (auto *Shadow = |
3812 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) |
3813 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) |
3814 | return New->setInvalidDecl(); |
3815 | } |
3816 | } |
3817 | if (!Old) { |
3818 | Diag(New->getLocation(), diag::err_redefinition_different_kind) |
3819 | << New->getDeclName(); |
3820 | notePreviousDefinition(Previous.getRepresentativeDecl(), |
3821 | New->getLocation()); |
3822 | return New->setInvalidDecl(); |
3823 | } |
3824 | |
3825 | // Ensure the template parameters are compatible. |
3826 | if (NewTemplate && |
3827 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), |
3828 | OldTemplate->getTemplateParameters(), |
3829 | /*Complain=*/true, TPL_TemplateMatch)) |
3830 | return New->setInvalidDecl(); |
3831 | |
3832 | // C++ [class.mem]p1: |
3833 | // A member shall not be declared twice in the member-specification [...] |
3834 | // |
3835 | // Here, we need only consider static data members. |
3836 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { |
3837 | Diag(New->getLocation(), diag::err_duplicate_member) |
3838 | << New->getIdentifier(); |
3839 | Diag(Old->getLocation(), diag::note_previous_declaration); |
3840 | New->setInvalidDecl(); |
3841 | } |
3842 | |
3843 | mergeDeclAttributes(New, Old); |
3844 | // Warn if an already-declared variable is made a weak_import in a subsequent |
3845 | // declaration |
3846 | if (New->hasAttr<WeakImportAttr>() && |
3847 | Old->getStorageClass() == SC_None && |
3848 | !Old->hasAttr<WeakImportAttr>()) { |
3849 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); |
3850 | notePreviousDefinition(Old, New->getLocation()); |
3851 | // Remove weak_import attribute on new declaration. |
3852 | New->dropAttr<WeakImportAttr>(); |
3853 | } |
3854 | |
3855 | if (New->hasAttr<InternalLinkageAttr>() && |
3856 | !Old->hasAttr<InternalLinkageAttr>()) { |
3857 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) |
3858 | << New->getDeclName(); |
3859 | notePreviousDefinition(Old, New->getLocation()); |
3860 | New->dropAttr<InternalLinkageAttr>(); |
3861 | } |
3862 | |
3863 | // Merge the types. |
3864 | VarDecl *MostRecent = Old->getMostRecentDecl(); |
3865 | if (MostRecent != Old) { |
3866 | MergeVarDeclTypes(New, MostRecent, |
3867 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); |
3868 | if (New->isInvalidDecl()) |
3869 | return; |
3870 | } |
3871 | |
3872 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); |
3873 | if (New->isInvalidDecl()) |
3874 | return; |
3875 | |
3876 | diag::kind PrevDiag; |
3877 | SourceLocation OldLocation; |
3878 | std::tie(PrevDiag, OldLocation) = |
3879 | getNoteDiagForInvalidRedeclaration(Old, New); |
3880 | |
3881 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. |
3882 | if (New->getStorageClass() == SC_Static && |
3883 | !New->isStaticDataMember() && |
3884 | Old->hasExternalFormalLinkage()) { |
3885 | if (getLangOpts().MicrosoftExt) { |
3886 | Diag(New->getLocation(), diag::ext_static_non_static) |
3887 | << New->getDeclName(); |
3888 | Diag(OldLocation, PrevDiag); |
3889 | } else { |
3890 | Diag(New->getLocation(), diag::err_static_non_static) |
3891 | << New->getDeclName(); |
3892 | Diag(OldLocation, PrevDiag); |
3893 | return New->setInvalidDecl(); |
3894 | } |
3895 | } |
3896 | // C99 6.2.2p4: |
3897 | // For an identifier declared with the storage-class specifier |
3898 | // extern in a scope in which a prior declaration of that |
3899 | // identifier is visible,23) if the prior declaration specifies |
3900 | // internal or external linkage, the linkage of the identifier at |
3901 | // the later declaration is the same as the linkage specified at |
3902 | // the prior declaration. If no prior declaration is visible, or |
3903 | // if the prior declaration specifies no linkage, then the |
3904 | // identifier has external linkage. |
3905 | if (New->hasExternalStorage() && Old->hasLinkage()) |
3906 | /* Okay */; |
3907 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && |
3908 | !New->isStaticDataMember() && |
3909 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { |
3910 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); |
3911 | Diag(OldLocation, PrevDiag); |
3912 | return New->setInvalidDecl(); |
3913 | } |
3914 | |
3915 | // Check if extern is followed by non-extern and vice-versa. |
3916 | if (New->hasExternalStorage() && |
3917 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { |
3918 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); |
3919 | Diag(OldLocation, PrevDiag); |
3920 | return New->setInvalidDecl(); |
3921 | } |
3922 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && |
3923 | !New->hasExternalStorage()) { |
3924 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); |
3925 | Diag(OldLocation, PrevDiag); |
3926 | return New->setInvalidDecl(); |
3927 | } |
3928 | |
3929 | if (CheckRedeclarationModuleOwnership(New, Old)) |
3930 | return; |
3931 | |
3932 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. |
3933 | |
3934 | // FIXME: The test for external storage here seems wrong? We still |
3935 | // need to check for mismatches. |
3936 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && |
3937 | // Don't complain about out-of-line definitions of static members. |
3938 | !(Old->getLexicalDeclContext()->isRecord() && |
3939 | !New->getLexicalDeclContext()->isRecord())) { |
3940 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); |
3941 | Diag(OldLocation, PrevDiag); |
3942 | return New->setInvalidDecl(); |
3943 | } |
3944 | |
3945 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { |
3946 | if (VarDecl *Def = Old->getDefinition()) { |
3947 | // C++1z [dcl.fcn.spec]p4: |
3948 | // If the definition of a variable appears in a translation unit before |
3949 | // its first declaration as inline, the program is ill-formed. |
3950 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; |
3951 | Diag(Def->getLocation(), diag::note_previous_definition); |
3952 | } |
3953 | } |
3954 | |
3955 | // If this redeclaration makes the variable inline, we may need to add it to |
3956 | // UndefinedButUsed. |
3957 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && |
3958 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) |
3959 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), |
3960 | SourceLocation())); |
3961 | |
3962 | if (New->getTLSKind() != Old->getTLSKind()) { |
3963 | if (!Old->getTLSKind()) { |
3964 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); |
3965 | Diag(OldLocation, PrevDiag); |
3966 | } else if (!New->getTLSKind()) { |
3967 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); |
3968 | Diag(OldLocation, PrevDiag); |
3969 | } else { |
3970 | // Do not allow redeclaration to change the variable between requiring |
3971 | // static and dynamic initialization. |
3972 | // FIXME: GCC allows this, but uses the TLS keyword on the first |
3973 | // declaration to determine the kind. Do we need to be compatible here? |
3974 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) |
3975 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); |
3976 | Diag(OldLocation, PrevDiag); |
3977 | } |
3978 | } |
3979 | |
3980 | // C++ doesn't have tentative definitions, so go right ahead and check here. |
3981 | if (getLangOpts().CPlusPlus && |
3982 | New->isThisDeclarationADefinition() == VarDecl::Definition) { |
3983 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && |
3984 | Old->getCanonicalDecl()->isConstexpr()) { |
3985 | // This definition won't be a definition any more once it's been merged. |
3986 | Diag(New->getLocation(), |
3987 | diag::warn_deprecated_redundant_constexpr_static_def); |
3988 | } else if (VarDecl *Def = Old->getDefinition()) { |
3989 | if (checkVarDeclRedefinition(Def, New)) |
3990 | return; |
3991 | } |
3992 | } |
3993 | |
3994 | if (haveIncompatibleLanguageLinkages(Old, New)) { |
3995 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; |
3996 | Diag(OldLocation, PrevDiag); |
3997 | New->setInvalidDecl(); |
3998 | return; |
3999 | } |
4000 | |
4001 | // Merge "used" flag. |
4002 | if (Old->getMostRecentDecl()->isUsed(false)) |
4003 | New->setIsUsed(); |
4004 | |
4005 | // Keep a chain of previous declarations. |
4006 | New->setPreviousDecl(Old); |
4007 | if (NewTemplate) |
4008 | NewTemplate->setPreviousDecl(OldTemplate); |
4009 | adjustDeclContextForDeclaratorDecl(New, Old); |
4010 | |
4011 | // Inherit access appropriately. |
4012 | New->setAccess(Old->getAccess()); |
4013 | if (NewTemplate) |
4014 | NewTemplate->setAccess(New->getAccess()); |
4015 | |
4016 | if (Old->isInline()) |
4017 | New->setImplicitlyInline(); |
4018 | } |
4019 | |
4020 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { |
4021 | SourceManager &SrcMgr = getSourceManager(); |
4022 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); |
4023 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); |
4024 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); |
4025 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); |
4026 | auto &HSI = PP.getHeaderSearchInfo(); |
4027 | StringRef HdrFilename = |
4028 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); |
4029 | |
4030 | auto noteFromModuleOrInclude = [&](Module *Mod, |
4031 | SourceLocation IncLoc) -> bool { |
4032 | // Redefinition errors with modules are common with non modular mapped |
4033 | // headers, example: a non-modular header H in module A that also gets |
4034 | // included directly in a TU. Pointing twice to the same header/definition |
4035 | // is confusing, try to get better diagnostics when modules is on. |
4036 | if (IncLoc.isValid()) { |
4037 | if (Mod) { |
4038 | Diag(IncLoc, diag::note_redefinition_modules_same_file) |
4039 | << HdrFilename.str() << Mod->getFullModuleName(); |
4040 | if (!Mod->DefinitionLoc.isInvalid()) |
4041 | Diag(Mod->DefinitionLoc, diag::note_defined_here) |
4042 | << Mod->getFullModuleName(); |
4043 | } else { |
4044 | Diag(IncLoc, diag::note_redefinition_include_same_file) |
4045 | << HdrFilename.str(); |
4046 | } |
4047 | return true; |
4048 | } |
4049 | |
4050 | return false; |
4051 | }; |
4052 | |
4053 | // Is it the same file and same offset? Provide more information on why |
4054 | // this leads to a redefinition error. |
4055 | bool EmittedDiag = false; |
4056 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { |
4057 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); |
4058 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); |
4059 | EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); |
4060 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); |
4061 | |
4062 | // If the header has no guards, emit a note suggesting one. |
4063 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) |
4064 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); |
4065 | |
4066 | if (EmittedDiag) |
4067 | return; |
4068 | } |
4069 | |
4070 | // Redefinition coming from different files or couldn't do better above. |
4071 | if (Old->getLocation().isValid()) |
4072 | Diag(Old->getLocation(), diag::note_previous_definition); |
4073 | } |
4074 | |
4075 | /// We've just determined that \p Old and \p New both appear to be definitions |
4076 | /// of the same variable. Either diagnose or fix the problem. |
4077 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { |
4078 | if (!hasVisibleDefinition(Old) && |
4079 | (New->getFormalLinkage() == InternalLinkage || |
4080 | New->isInline() || |
4081 | New->getDescribedVarTemplate() || |
4082 | New->getNumTemplateParameterLists() || |
4083 | New->getDeclContext()->isDependentContext())) { |
4084 | // The previous definition is hidden, and multiple definitions are |
4085 | // permitted (in separate TUs). Demote this to a declaration. |
4086 | New->demoteThisDefinitionToDeclaration(); |
4087 | |
4088 | // Make the canonical definition visible. |
4089 | if (auto *OldTD = Old->getDescribedVarTemplate()) |
4090 | makeMergedDefinitionVisible(OldTD); |
4091 | makeMergedDefinitionVisible(Old); |
4092 | return false; |
4093 | } else { |
4094 | Diag(New->getLocation(), diag::err_redefinition) << New; |
4095 | notePreviousDefinition(Old, New->getLocation()); |
4096 | New->setInvalidDecl(); |
4097 | return true; |
4098 | } |
4099 | } |
4100 | |
4101 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with |
4102 | /// no declarator (e.g. "struct foo;") is parsed. |
4103 | Decl * |
4104 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
4105 | RecordDecl *&AnonRecord) { |
4106 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, |
4107 | AnonRecord); |
4108 | } |
4109 | |
4110 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to |
4111 | // disambiguate entities defined in different scopes. |
4112 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks |
4113 | // compatibility. |
4114 | // We will pick our mangling number depending on which version of MSVC is being |
4115 | // targeted. |
4116 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { |
4117 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) |
4118 | ? S->getMSCurManglingNumber() |
4119 | : S->getMSLastManglingNumber(); |
4120 | } |
4121 | |
4122 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { |
4123 | if (!Context.getLangOpts().CPlusPlus) |
4124 | return; |
4125 | |
4126 | if (isa<CXXRecordDecl>(Tag->getParent())) { |
4127 | // If this tag is the direct child of a class, number it if |
4128 | // it is anonymous. |
4129 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) |
4130 | return; |
4131 | MangleNumberingContext &MCtx = |
4132 | Context.getManglingNumberContext(Tag->getParent()); |
4133 | Context.setManglingNumber( |
4134 | Tag, MCtx.getManglingNumber( |
4135 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); |
4136 | return; |
4137 | } |
4138 | |
4139 | // If this tag isn't a direct child of a class, number it if it is local. |
4140 | Decl *ManglingContextDecl; |
4141 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( |
4142 | Tag->getDeclContext(), ManglingContextDecl)) { |
4143 | Context.setManglingNumber( |
4144 | Tag, MCtx->getManglingNumber( |
4145 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); |
4146 | } |
4147 | } |
4148 | |
4149 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, |
4150 | TypedefNameDecl *NewTD) { |
4151 | if (TagFromDeclSpec->isInvalidDecl()) |
4152 | return; |
4153 | |
4154 | // Do nothing if the tag already has a name for linkage purposes. |
4155 | if (TagFromDeclSpec->hasNameForLinkage()) |
4156 | return; |
4157 | |
4158 | // A well-formed anonymous tag must always be a TUK_Definition. |
4159 | assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast <void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4159, __PRETTY_FUNCTION__)); |
4160 | |
4161 | // The type must match the tag exactly; no qualifiers allowed. |
4162 | if (!Context.hasSameType(NewTD->getUnderlyingType(), |
4163 | Context.getTagDeclType(TagFromDeclSpec))) { |
4164 | if (getLangOpts().CPlusPlus) |
4165 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); |
4166 | return; |
4167 | } |
4168 | |
4169 | // If we've already computed linkage for the anonymous tag, then |
4170 | // adding a typedef name for the anonymous decl can change that |
4171 | // linkage, which might be a serious problem. Diagnose this as |
4172 | // unsupported and ignore the typedef name. TODO: we should |
4173 | // pursue this as a language defect and establish a formal rule |
4174 | // for how to handle it. |
4175 | if (TagFromDeclSpec->hasLinkageBeenComputed()) { |
4176 | Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); |
4177 | |
4178 | SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); |
4179 | tagLoc = getLocForEndOfToken(tagLoc); |
4180 | |
4181 | llvm::SmallString<40> textToInsert; |
4182 | textToInsert += ' '; |
4183 | textToInsert += NewTD->getIdentifier()->getName(); |
4184 | Diag(tagLoc, diag::note_typedef_changes_linkage) |
4185 | << FixItHint::CreateInsertion(tagLoc, textToInsert); |
4186 | return; |
4187 | } |
4188 | |
4189 | // Otherwise, set this is the anon-decl typedef for the tag. |
4190 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); |
4191 | } |
4192 | |
4193 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { |
4194 | switch (T) { |
4195 | case DeclSpec::TST_class: |
4196 | return 0; |
4197 | case DeclSpec::TST_struct: |
4198 | return 1; |
4199 | case DeclSpec::TST_interface: |
4200 | return 2; |
4201 | case DeclSpec::TST_union: |
4202 | return 3; |
4203 | case DeclSpec::TST_enum: |
4204 | return 4; |
4205 | default: |
4206 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4206); |
4207 | } |
4208 | } |
4209 | |
4210 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with |
4211 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template |
4212 | /// parameters to cope with template friend declarations. |
4213 | Decl * |
4214 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, |
4215 | MultiTemplateParamsArg TemplateParams, |
4216 | bool IsExplicitInstantiation, |
4217 | RecordDecl *&AnonRecord) { |
4218 | Decl *TagD = nullptr; |
4219 | TagDecl *Tag = nullptr; |
4220 | if (DS.getTypeSpecType() == DeclSpec::TST_class || |
4221 | DS.getTypeSpecType() == DeclSpec::TST_struct || |
4222 | DS.getTypeSpecType() == DeclSpec::TST_interface || |
4223 | DS.getTypeSpecType() == DeclSpec::TST_union || |
4224 | DS.getTypeSpecType() == DeclSpec::TST_enum) { |
4225 | TagD = DS.getRepAsDecl(); |
4226 | |
4227 | if (!TagD) // We probably had an error |
4228 | return nullptr; |
4229 | |
4230 | // Note that the above type specs guarantee that the |
4231 | // type rep is a Decl, whereas in many of the others |
4232 | // it's a Type. |
4233 | if (isa<TagDecl>(TagD)) |
4234 | Tag = cast<TagDecl>(TagD); |
4235 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) |
4236 | Tag = CTD->getTemplatedDecl(); |
4237 | } |
4238 | |
4239 | if (Tag) { |
4240 | handleTagNumbering(Tag, S); |
4241 | Tag->setFreeStanding(); |
4242 | if (Tag->isInvalidDecl()) |
4243 | return Tag; |
4244 | } |
4245 | |
4246 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { |
4247 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object |
4248 | // or incomplete types shall not be restrict-qualified." |
4249 | if (TypeQuals & DeclSpec::TQ_restrict) |
4250 | Diag(DS.getRestrictSpecLoc(), |
4251 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) |
4252 | << DS.getSourceRange(); |
4253 | } |
4254 | |
4255 | if (DS.isInlineSpecified()) |
4256 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) |
4257 | << getLangOpts().CPlusPlus17; |
4258 | |
4259 | if (DS.isConstexprSpecified()) { |
4260 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations |
4261 | // and definitions of functions and variables. |
4262 | if (Tag) |
4263 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) |
4264 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); |
4265 | else |
4266 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); |
4267 | // Don't emit warnings after this error. |
4268 | return TagD; |
4269 | } |
4270 | |
4271 | DiagnoseFunctionSpecifiers(DS); |
4272 | |
4273 | if (DS.isFriendSpecified()) { |
4274 | // If we're dealing with a decl but not a TagDecl, assume that |
4275 | // whatever routines created it handled the friendship aspect. |
4276 | if (TagD && !Tag) |
4277 | return nullptr; |
4278 | return ActOnFriendTypeDecl(S, DS, TemplateParams); |
4279 | } |
4280 | |
4281 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); |
4282 | bool IsExplicitSpecialization = |
4283 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; |
4284 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && |
4285 | !IsExplicitInstantiation && !IsExplicitSpecialization && |
4286 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { |
4287 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a |
4288 | // nested-name-specifier unless it is an explicit instantiation |
4289 | // or an explicit specialization. |
4290 | // |
4291 | // FIXME: We allow class template partial specializations here too, per the |
4292 | // obvious intent of DR1819. |
4293 | // |
4294 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. |
4295 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) |
4296 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); |
4297 | return nullptr; |
4298 | } |
4299 | |
4300 | // Track whether this decl-specifier declares anything. |
4301 | bool DeclaresAnything = true; |
4302 | |
4303 | // Handle anonymous struct definitions. |
4304 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { |
4305 | if (!Record->getDeclName() && Record->isCompleteDefinition() && |
4306 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { |
4307 | if (getLangOpts().CPlusPlus || |
4308 | Record->getDeclContext()->isRecord()) { |
4309 | // If CurContext is a DeclContext that can contain statements, |
4310 | // RecursiveASTVisitor won't visit the decls that |
4311 | // BuildAnonymousStructOrUnion() will put into CurContext. |
4312 | // Also store them here so that they can be part of the |
4313 | // DeclStmt that gets created in this case. |
4314 | // FIXME: Also return the IndirectFieldDecls created by |
4315 | // BuildAnonymousStructOr union, for the same reason? |
4316 | if (CurContext->isFunctionOrMethod()) |
4317 | AnonRecord = Record; |
4318 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, |
4319 | Context.getPrintingPolicy()); |
4320 | } |
4321 | |
4322 | DeclaresAnything = false; |
4323 | } |
4324 | } |
4325 | |
4326 | // C11 6.7.2.1p2: |
4327 | // A struct-declaration that does not declare an anonymous structure or |
4328 | // anonymous union shall contain a struct-declarator-list. |
4329 | // |
4330 | // This rule also existed in C89 and C99; the grammar for struct-declaration |
4331 | // did not permit a struct-declaration without a struct-declarator-list. |
4332 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && |
4333 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { |
4334 | // Check for Microsoft C extension: anonymous struct/union member. |
4335 | // Handle 2 kinds of anonymous struct/union: |
4336 | // struct STRUCT; |
4337 | // union UNION; |
4338 | // and |
4339 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. |
4340 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. |
4341 | if ((Tag && Tag->getDeclName()) || |
4342 | DS.getTypeSpecType() == DeclSpec::TST_typename) { |
4343 | RecordDecl *Record = nullptr; |
4344 | if (Tag) |
4345 | Record = dyn_cast<RecordDecl>(Tag); |
4346 | else if (const RecordType *RT = |
4347 | DS.getRepAsType().get()->getAsStructureType()) |
4348 | Record = RT->getDecl(); |
4349 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) |
4350 | Record = UT->getDecl(); |
4351 | |
4352 | if (Record && getLangOpts().MicrosoftExt) { |
4353 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) |
4354 | << Record->isUnion() << DS.getSourceRange(); |
4355 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); |
4356 | } |
4357 | |
4358 | DeclaresAnything = false; |
4359 | } |
4360 | } |
4361 | |
4362 | // Skip all the checks below if we have a type error. |
4363 | if (DS.getTypeSpecType() == DeclSpec::TST_error || |
4364 | (TagD && TagD->isInvalidDecl())) |
4365 | return TagD; |
4366 | |
4367 | if (getLangOpts().CPlusPlus && |
4368 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) |
4369 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) |
4370 | if (Enum->enumerator_begin() == Enum->enumerator_end() && |
4371 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) |
4372 | DeclaresAnything = false; |
4373 | |
4374 | if (!DS.isMissingDeclaratorOk()) { |
4375 | // Customize diagnostic for a typedef missing a name. |
4376 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) |
4377 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) |
4378 | << DS.getSourceRange(); |
4379 | else |
4380 | DeclaresAnything = false; |
4381 | } |
4382 | |
4383 | if (DS.isModulePrivateSpecified() && |
4384 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) |
4385 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) |
4386 | << Tag->getTagKind() |
4387 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); |
4388 | |
4389 | ActOnDocumentableDecl(TagD); |
4390 | |
4391 | // C 6.7/2: |
4392 | // A declaration [...] shall declare at least a declarator [...], a tag, |
4393 | // or the members of an enumeration. |
4394 | // C++ [dcl.dcl]p3: |
4395 | // [If there are no declarators], and except for the declaration of an |
4396 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more |
4397 | // names into the program, or shall redeclare a name introduced by a |
4398 | // previous declaration. |
4399 | if (!DeclaresAnything) { |
4400 | // In C, we allow this as a (popular) extension / bug. Don't bother |
4401 | // producing further diagnostics for redundant qualifiers after this. |
4402 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); |
4403 | return TagD; |
4404 | } |
4405 | |
4406 | // C++ [dcl.stc]p1: |
4407 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the |
4408 | // init-declarator-list of the declaration shall not be empty. |
4409 | // C++ [dcl.fct.spec]p1: |
4410 | // If a cv-qualifier appears in a decl-specifier-seq, the |
4411 | // init-declarator-list of the declaration shall not be empty. |
4412 | // |
4413 | // Spurious qualifiers here appear to be valid in C. |
4414 | unsigned DiagID = diag::warn_standalone_specifier; |
4415 | if (getLangOpts().CPlusPlus) |
4416 | DiagID = diag::ext_standalone_specifier; |
4417 | |
4418 | // Note that a linkage-specification sets a storage class, but |
4419 | // 'extern "C" struct foo;' is actually valid and not theoretically |
4420 | // useless. |
4421 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { |
4422 | if (SCS == DeclSpec::SCS_mutable) |
4423 | // Since mutable is not a viable storage class specifier in C, there is |
4424 | // no reason to treat it as an extension. Instead, diagnose as an error. |
4425 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); |
4426 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) |
4427 | Diag(DS.getStorageClassSpecLoc(), DiagID) |
4428 | << DeclSpec::getSpecifierName(SCS); |
4429 | } |
4430 | |
4431 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) |
4432 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) |
4433 | << DeclSpec::getSpecifierName(TSCS); |
4434 | if (DS.getTypeQualifiers()) { |
4435 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) |
4436 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; |
4437 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) |
4438 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; |
4439 | // Restrict is covered above. |
4440 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) |
4441 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; |
4442 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) |
4443 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; |
4444 | } |
4445 | |
4446 | // Warn about ignored type attributes, for example: |
4447 | // __attribute__((aligned)) struct A; |
4448 | // Attributes should be placed after tag to apply to type declaration. |
4449 | if (!DS.getAttributes().empty()) { |
4450 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); |
4451 | if (TypeSpecType == DeclSpec::TST_class || |
4452 | TypeSpecType == DeclSpec::TST_struct || |
4453 | TypeSpecType == DeclSpec::TST_interface || |
4454 | TypeSpecType == DeclSpec::TST_union || |
4455 | TypeSpecType == DeclSpec::TST_enum) { |
4456 | for (const ParsedAttr &AL : DS.getAttributes()) |
4457 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) |
4458 | << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); |
4459 | } |
4460 | } |
4461 | |
4462 | return TagD; |
4463 | } |
4464 | |
4465 | /// We are trying to inject an anonymous member into the given scope; |
4466 | /// check if there's an existing declaration that can't be overloaded. |
4467 | /// |
4468 | /// \return true if this is a forbidden redeclaration |
4469 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, |
4470 | Scope *S, |
4471 | DeclContext *Owner, |
4472 | DeclarationName Name, |
4473 | SourceLocation NameLoc, |
4474 | bool IsUnion) { |
4475 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, |
4476 | Sema::ForVisibleRedeclaration); |
4477 | if (!SemaRef.LookupName(R, S)) return false; |
4478 | |
4479 | // Pick a representative declaration. |
4480 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); |
4481 | assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast <void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4481, __PRETTY_FUNCTION__)); |
4482 | |
4483 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) |
4484 | return false; |
4485 | |
4486 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) |
4487 | << IsUnion << Name; |
4488 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); |
4489 | |
4490 | return true; |
4491 | } |
4492 | |
4493 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the |
4494 | /// anonymous struct or union AnonRecord into the owning context Owner |
4495 | /// and scope S. This routine will be invoked just after we realize |
4496 | /// that an unnamed union or struct is actually an anonymous union or |
4497 | /// struct, e.g., |
4498 | /// |
4499 | /// @code |
4500 | /// union { |
4501 | /// int i; |
4502 | /// float f; |
4503 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and |
4504 | /// // f into the surrounding scope.x |
4505 | /// @endcode |
4506 | /// |
4507 | /// This routine is recursive, injecting the names of nested anonymous |
4508 | /// structs/unions into the owning context and scope as well. |
4509 | static bool |
4510 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, |
4511 | RecordDecl *AnonRecord, AccessSpecifier AS, |
4512 | SmallVectorImpl<NamedDecl *> &Chaining) { |
4513 | bool Invalid = false; |
4514 | |
4515 | // Look every FieldDecl and IndirectFieldDecl with a name. |
4516 | for (auto *D : AnonRecord->decls()) { |
4517 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && |
4518 | cast<NamedDecl>(D)->getDeclName()) { |
4519 | ValueDecl *VD = cast<ValueDecl>(D); |
4520 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), |
4521 | VD->getLocation(), |
4522 | AnonRecord->isUnion())) { |
4523 | // C++ [class.union]p2: |
4524 | // The names of the members of an anonymous union shall be |
4525 | // distinct from the names of any other entity in the |
4526 | // scope in which the anonymous union is declared. |
4527 | Invalid = true; |
4528 | } else { |
4529 | // C++ [class.union]p2: |
4530 | // For the purpose of name lookup, after the anonymous union |
4531 | // definition, the members of the anonymous union are |
4532 | // considered to have been defined in the scope in which the |
4533 | // anonymous union is declared. |
4534 | unsigned OldChainingSize = Chaining.size(); |
4535 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) |
4536 | Chaining.append(IF->chain_begin(), IF->chain_end()); |
4537 | else |
4538 | Chaining.push_back(VD); |
4539 | |
4540 | assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4540, __PRETTY_FUNCTION__)); |
4541 | NamedDecl **NamedChain = |
4542 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; |
4543 | for (unsigned i = 0; i < Chaining.size(); i++) |
4544 | NamedChain[i] = Chaining[i]; |
4545 | |
4546 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( |
4547 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), |
4548 | VD->getType(), {NamedChain, Chaining.size()}); |
4549 | |
4550 | for (const auto *Attr : VD->attrs()) |
4551 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); |
4552 | |
4553 | IndirectField->setAccess(AS); |
4554 | IndirectField->setImplicit(); |
4555 | SemaRef.PushOnScopeChains(IndirectField, S); |
4556 | |
4557 | // That includes picking up the appropriate access specifier. |
4558 | if (AS != AS_none) IndirectField->setAccess(AS); |
4559 | |
4560 | Chaining.resize(OldChainingSize); |
4561 | } |
4562 | } |
4563 | } |
4564 | |
4565 | return Invalid; |
4566 | } |
4567 | |
4568 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to |
4569 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: |
4570 | /// illegal input values are mapped to SC_None. |
4571 | static StorageClass |
4572 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { |
4573 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); |
4574 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4575, __PRETTY_FUNCTION__)) |
4575 | "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4575, __PRETTY_FUNCTION__)); |
4576 | switch (StorageClassSpec) { |
4577 | case DeclSpec::SCS_unspecified: return SC_None; |
4578 | case DeclSpec::SCS_extern: |
4579 | if (DS.isExternInLinkageSpec()) |
4580 | return SC_None; |
4581 | return SC_Extern; |
4582 | case DeclSpec::SCS_static: return SC_Static; |
4583 | case DeclSpec::SCS_auto: return SC_Auto; |
4584 | case DeclSpec::SCS_register: return SC_Register; |
4585 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; |
4586 | // Illegal SCSs map to None: error reporting is up to the caller. |
4587 | case DeclSpec::SCS_mutable: // Fall through. |
4588 | case DeclSpec::SCS_typedef: return SC_None; |
4589 | } |
4590 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4590); |
4591 | } |
4592 | |
4593 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { |
4594 | assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void> (0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4594, __PRETTY_FUNCTION__)); |
4595 | |
4596 | for (const auto *I : Record->decls()) { |
4597 | const auto *FD = dyn_cast<FieldDecl>(I); |
4598 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) |
4599 | FD = IFD->getAnonField(); |
4600 | if (FD && FD->hasInClassInitializer()) |
4601 | return FD->getLocation(); |
4602 | } |
4603 | |
4604 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4604); |
4605 | } |
4606 | |
4607 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, |
4608 | SourceLocation DefaultInitLoc) { |
4609 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) |
4610 | return; |
4611 | |
4612 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); |
4613 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; |
4614 | } |
4615 | |
4616 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, |
4617 | CXXRecordDecl *AnonUnion) { |
4618 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) |
4619 | return; |
4620 | |
4621 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); |
4622 | } |
4623 | |
4624 | /// BuildAnonymousStructOrUnion - Handle the declaration of an |
4625 | /// anonymous structure or union. Anonymous unions are a C++ feature |
4626 | /// (C++ [class.union]) and a C11 feature; anonymous structures |
4627 | /// are a C11 feature and GNU C++ extension. |
4628 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, |
4629 | AccessSpecifier AS, |
4630 | RecordDecl *Record, |
4631 | const PrintingPolicy &Policy) { |
4632 | DeclContext *Owner = Record->getDeclContext(); |
4633 | |
4634 | // Diagnose whether this anonymous struct/union is an extension. |
4635 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) |
4636 | Diag(Record->getLocation(), diag::ext_anonymous_union); |
4637 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) |
4638 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); |
4639 | else if (!Record->isUnion() && !getLangOpts().C11) |
4640 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); |
4641 | |
4642 | // C and C++ require different kinds of checks for anonymous |
4643 | // structs/unions. |
4644 | bool Invalid = false; |
4645 | if (getLangOpts().CPlusPlus) { |
4646 | const char *PrevSpec = nullptr; |
4647 | unsigned DiagID; |
4648 | if (Record->isUnion()) { |
4649 | // C++ [class.union]p6: |
4650 | // C++17 [class.union.anon]p2: |
4651 | // Anonymous unions declared in a named namespace or in the |
4652 | // global namespace shall be declared static. |
4653 | DeclContext *OwnerScope = Owner->getRedeclContext(); |
4654 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && |
4655 | (OwnerScope->isTranslationUnit() || |
4656 | (OwnerScope->isNamespace() && |
4657 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { |
4658 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) |
4659 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); |
4660 | |
4661 | // Recover by adding 'static'. |
4662 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), |
4663 | PrevSpec, DiagID, Policy); |
4664 | } |
4665 | // C++ [class.union]p6: |
4666 | // A storage class is not allowed in a declaration of an |
4667 | // anonymous union in a class scope. |
4668 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && |
4669 | isa<RecordDecl>(Owner)) { |
4670 | Diag(DS.getStorageClassSpecLoc(), |
4671 | diag::err_anonymous_union_with_storage_spec) |
4672 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); |
4673 | |
4674 | // Recover by removing the storage specifier. |
4675 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, |
4676 | SourceLocation(), |
4677 | PrevSpec, DiagID, Context.getPrintingPolicy()); |
4678 | } |
4679 | } |
4680 | |
4681 | // Ignore const/volatile/restrict qualifiers. |
4682 | if (DS.getTypeQualifiers()) { |
4683 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) |
4684 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) |
4685 | << Record->isUnion() << "const" |
4686 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); |
4687 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) |
4688 | Diag(DS.getVolatileSpecLoc(), |
4689 | diag::ext_anonymous_struct_union_qualified) |
4690 | << Record->isUnion() << "volatile" |
4691 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); |
4692 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) |
4693 | Diag(DS.getRestrictSpecLoc(), |
4694 | diag::ext_anonymous_struct_union_qualified) |
4695 | << Record->isUnion() << "restrict" |
4696 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); |
4697 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) |
4698 | Diag(DS.getAtomicSpecLoc(), |
4699 | diag::ext_anonymous_struct_union_qualified) |
4700 | << Record->isUnion() << "_Atomic" |
4701 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); |
4702 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) |
4703 | Diag(DS.getUnalignedSpecLoc(), |
4704 | diag::ext_anonymous_struct_union_qualified) |
4705 | << Record->isUnion() << "__unaligned" |
4706 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); |
4707 | |
4708 | DS.ClearTypeQualifiers(); |
4709 | } |
4710 | |
4711 | // C++ [class.union]p2: |
4712 | // The member-specification of an anonymous union shall only |
4713 | // define non-static data members. [Note: nested types and |
4714 | // functions cannot be declared within an anonymous union. ] |
4715 | for (auto *Mem : Record->decls()) { |
4716 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { |
4717 | // C++ [class.union]p3: |
4718 | // An anonymous union shall not have private or protected |
4719 | // members (clause 11). |
4720 | assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0 ) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4720, __PRETTY_FUNCTION__)); |
4721 | if (FD->getAccess() != AS_public) { |
4722 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) |
4723 | << Record->isUnion() << (FD->getAccess() == AS_protected); |
4724 | Invalid = true; |
4725 | } |
4726 | |
4727 | // C++ [class.union]p1 |
4728 | // An object of a class with a non-trivial constructor, a non-trivial |
4729 | // copy constructor, a non-trivial destructor, or a non-trivial copy |
4730 | // assignment operator cannot be a member of a union, nor can an |
4731 | // array of such objects. |
4732 | if (CheckNontrivialField(FD)) |
4733 | Invalid = true; |
4734 | } else if (Mem->isImplicit()) { |
4735 | // Any implicit members are fine. |
4736 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { |
4737 | // This is a type that showed up in an |
4738 | // elaborated-type-specifier inside the anonymous struct or |
4739 | // union, but which actually declares a type outside of the |
4740 | // anonymous struct or union. It's okay. |
4741 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { |
4742 | if (!MemRecord->isAnonymousStructOrUnion() && |
4743 | MemRecord->getDeclName()) { |
4744 | // Visual C++ allows type definition in anonymous struct or union. |
4745 | if (getLangOpts().MicrosoftExt) |
4746 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) |
4747 | << Record->isUnion(); |
4748 | else { |
4749 | // This is a nested type declaration. |
4750 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) |
4751 | << Record->isUnion(); |
4752 | Invalid = true; |
4753 | } |
4754 | } else { |
4755 | // This is an anonymous type definition within another anonymous type. |
4756 | // This is a popular extension, provided by Plan9, MSVC and GCC, but |
4757 | // not part of standard C++. |
4758 | Diag(MemRecord->getLocation(), |
4759 | diag::ext_anonymous_record_with_anonymous_type) |
4760 | << Record->isUnion(); |
4761 | } |
4762 | } else if (isa<AccessSpecDecl>(Mem)) { |
4763 | // Any access specifier is fine. |
4764 | } else if (isa<StaticAssertDecl>(Mem)) { |
4765 | // In C++1z, static_assert declarations are also fine. |
4766 | } else { |
4767 | // We have something that isn't a non-static data |
4768 | // member. Complain about it. |
4769 | unsigned DK = diag::err_anonymous_record_bad_member; |
4770 | if (isa<TypeDecl>(Mem)) |
4771 | DK = diag::err_anonymous_record_with_type; |
4772 | else if (isa<FunctionDecl>(Mem)) |
4773 | DK = diag::err_anonymous_record_with_function; |
4774 | else if (isa<VarDecl>(Mem)) |
4775 | DK = diag::err_anonymous_record_with_static; |
4776 | |
4777 | // Visual C++ allows type definition in anonymous struct or union. |
4778 | if (getLangOpts().MicrosoftExt && |
4779 | DK == diag::err_anonymous_record_with_type) |
4780 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) |
4781 | << Record->isUnion(); |
4782 | else { |
4783 | Diag(Mem->getLocation(), DK) << Record->isUnion(); |
4784 | Invalid = true; |
4785 | } |
4786 | } |
4787 | } |
4788 | |
4789 | // C++11 [class.union]p8 (DR1460): |
4790 | // At most one variant member of a union may have a |
4791 | // brace-or-equal-initializer. |
4792 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && |
4793 | Owner->isRecord()) |
4794 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), |
4795 | cast<CXXRecordDecl>(Record)); |
4796 | } |
4797 | |
4798 | if (!Record->isUnion() && !Owner->isRecord()) { |
4799 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) |
4800 | << getLangOpts().CPlusPlus; |
4801 | Invalid = true; |
4802 | } |
4803 | |
4804 | // Mock up a declarator. |
4805 | Declarator Dc(DS, DeclaratorContext::MemberContext); |
4806 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); |
4807 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4807, __PRETTY_FUNCTION__)); |
4808 | |
4809 | // Create a declaration for this anonymous struct/union. |
4810 | NamedDecl *Anon = nullptr; |
4811 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { |
4812 | Anon = FieldDecl::Create( |
4813 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), |
4814 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, |
4815 | /*BitWidth=*/nullptr, /*Mutable=*/false, |
4816 | /*InitStyle=*/ICIS_NoInit); |
4817 | Anon->setAccess(AS); |
4818 | if (getLangOpts().CPlusPlus) |
4819 | FieldCollector->Add(cast<FieldDecl>(Anon)); |
4820 | } else { |
4821 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); |
4822 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); |
4823 | if (SCSpec == DeclSpec::SCS_mutable) { |
4824 | // mutable can only appear on non-static class members, so it's always |
4825 | // an error here |
4826 | Diag(Record->getLocation(), diag::err_mutable_nonmember); |
4827 | Invalid = true; |
4828 | SC = SC_None; |
4829 | } |
4830 | |
4831 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), |
4832 | Record->getLocation(), /*IdentifierInfo=*/nullptr, |
4833 | Context.getTypeDeclType(Record), TInfo, SC); |
4834 | |
4835 | // Default-initialize the implicit variable. This initialization will be |
4836 | // trivial in almost all cases, except if a union member has an in-class |
4837 | // initializer: |
4838 | // union { int n = 0; }; |
4839 | ActOnUninitializedDecl(Anon); |
4840 | } |
4841 | Anon->setImplicit(); |
4842 | |
4843 | // Mark this as an anonymous struct/union type. |
4844 | Record->setAnonymousStructOrUnion(true); |
4845 | |
4846 | // Add the anonymous struct/union object to the current |
4847 | // context. We'll be referencing this object when we refer to one of |
4848 | // its members. |
4849 | Owner->addDecl(Anon); |
4850 | |
4851 | // Inject the members of the anonymous struct/union into the owning |
4852 | // context and into the identifier resolver chain for name lookup |
4853 | // purposes. |
4854 | SmallVector<NamedDecl*, 2> Chain; |
4855 | Chain.push_back(Anon); |
4856 | |
4857 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) |
4858 | Invalid = true; |
4859 | |
4860 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { |
4861 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { |
4862 | Decl *ManglingContextDecl; |
4863 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( |
4864 | NewVD->getDeclContext(), ManglingContextDecl)) { |
4865 | Context.setManglingNumber( |
4866 | NewVD, MCtx->getManglingNumber( |
4867 | NewVD, getMSManglingNumber(getLangOpts(), S))); |
4868 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); |
4869 | } |
4870 | } |
4871 | } |
4872 | |
4873 | if (Invalid) |
4874 | Anon->setInvalidDecl(); |
4875 | |
4876 | return Anon; |
4877 | } |
4878 | |
4879 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an |
4880 | /// Microsoft C anonymous structure. |
4881 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx |
4882 | /// Example: |
4883 | /// |
4884 | /// struct A { int a; }; |
4885 | /// struct B { struct A; int b; }; |
4886 | /// |
4887 | /// void foo() { |
4888 | /// B var; |
4889 | /// var.a = 3; |
4890 | /// } |
4891 | /// |
4892 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, |
4893 | RecordDecl *Record) { |
4894 | assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void > (0) : __assert_fail ("Record && \"expected a record!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4894, __PRETTY_FUNCTION__)); |
4895 | |
4896 | // Mock up a declarator. |
4897 | Declarator Dc(DS, DeclaratorContext::TypeNameContext); |
4898 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); |
4899 | assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 4899, __PRETTY_FUNCTION__)); |
4900 | |
4901 | auto *ParentDecl = cast<RecordDecl>(CurContext); |
4902 | QualType RecTy = Context.getTypeDeclType(Record); |
4903 | |
4904 | // Create a declaration for this anonymous struct. |
4905 | NamedDecl *Anon = |
4906 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), |
4907 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, |
4908 | /*BitWidth=*/nullptr, /*Mutable=*/false, |
4909 | /*InitStyle=*/ICIS_NoInit); |
4910 | Anon->setImplicit(); |
4911 | |
4912 | // Add the anonymous struct object to the current context. |
4913 | CurContext->addDecl(Anon); |
4914 | |
4915 | // Inject the members of the anonymous struct into the current |
4916 | // context and into the identifier resolver chain for name lookup |
4917 | // purposes. |
4918 | SmallVector<NamedDecl*, 2> Chain; |
4919 | Chain.push_back(Anon); |
4920 | |
4921 | RecordDecl *RecordDef = Record->getDefinition(); |
4922 | if (RequireCompleteType(Anon->getLocation(), RecTy, |
4923 | diag::err_field_incomplete) || |
4924 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, |
4925 | AS_none, Chain)) { |
4926 | Anon->setInvalidDecl(); |
4927 | ParentDecl->setInvalidDecl(); |
4928 | } |
4929 | |
4930 | return Anon; |
4931 | } |
4932 | |
4933 | /// GetNameForDeclarator - Determine the full declaration name for the |
4934 | /// given Declarator. |
4935 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { |
4936 | return GetNameFromUnqualifiedId(D.getName()); |
4937 | } |
4938 | |
4939 | /// Retrieves the declaration name from a parsed unqualified-id. |
4940 | DeclarationNameInfo |
4941 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { |
4942 | DeclarationNameInfo NameInfo; |
4943 | NameInfo.setLoc(Name.StartLocation); |
4944 | |
4945 | switch (Name.getKind()) { |
4946 | |
4947 | case UnqualifiedIdKind::IK_ImplicitSelfParam: |
4948 | case UnqualifiedIdKind::IK_Identifier: |
4949 | NameInfo.setName(Name.Identifier); |
4950 | return NameInfo; |
4951 | |
4952 | case UnqualifiedIdKind::IK_DeductionGuideName: { |
4953 | // C++ [temp.deduct.guide]p3: |
4954 | // The simple-template-id shall name a class template specialization. |
4955 | // The template-name shall be the same identifier as the template-name |
4956 | // of the simple-template-id. |
4957 | // These together intend to imply that the template-name shall name a |
4958 | // class template. |
4959 | // FIXME: template<typename T> struct X {}; |
4960 | // template<typename T> using Y = X<T>; |
4961 | // Y(int) -> Y<int>; |
4962 | // satisfies these rules but does not name a class template. |
4963 | TemplateName TN = Name.TemplateName.get().get(); |
4964 | auto *Template = TN.getAsTemplateDecl(); |
4965 | if (!Template || !isa<ClassTemplateDecl>(Template)) { |
4966 | Diag(Name.StartLocation, |
4967 | diag::err_deduction_guide_name_not_class_template) |
4968 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; |
4969 | if (Template) |
4970 | Diag(Template->getLocation(), diag::note_template_decl_here); |
4971 | return DeclarationNameInfo(); |
4972 | } |
4973 | |
4974 | NameInfo.setName( |
4975 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); |
4976 | return NameInfo; |
4977 | } |
4978 | |
4979 | case UnqualifiedIdKind::IK_OperatorFunctionId: |
4980 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( |
4981 | Name.OperatorFunctionId.Operator)); |
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.setCXXLiteralOperatorNameLoc(Name.EndLocation); |
4992 | return NameInfo; |
4993 | |
4994 | case UnqualifiedIdKind::IK_ConversionFunctionId: { |
4995 | TypeSourceInfo *TInfo; |
4996 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); |
4997 | if (Ty.isNull()) |
4998 | return DeclarationNameInfo(); |
4999 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( |
5000 | Context.getCanonicalType(Ty))); |
5001 | NameInfo.setNamedTypeInfo(TInfo); |
5002 | return NameInfo; |
5003 | } |
5004 | |
5005 | case UnqualifiedIdKind::IK_ConstructorName: { |
5006 | TypeSourceInfo *TInfo; |
5007 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); |
5008 | if (Ty.isNull()) |
5009 | return DeclarationNameInfo(); |
5010 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( |
5011 | Context.getCanonicalType(Ty))); |
5012 | NameInfo.setNamedTypeInfo(TInfo); |
5013 | return NameInfo; |
5014 | } |
5015 | |
5016 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { |
5017 | // In well-formed code, we can only have a constructor |
5018 | // template-id that refers to the current context, so go there |
5019 | // to find the actual type being constructed. |
5020 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); |
5021 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) |
5022 | return DeclarationNameInfo(); |
5023 | |
5024 | // Determine the type of the class being constructed. |
5025 | QualType CurClassType = Context.getTypeDeclType(CurClass); |
5026 | |
5027 | // FIXME: Check two things: that the template-id names the same type as |
5028 | // CurClassType, and that the template-id does not occur when the name |
5029 | // was qualified. |
5030 | |
5031 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( |
5032 | Context.getCanonicalType(CurClassType))); |
5033 | // FIXME: should we retrieve TypeSourceInfo? |
5034 | NameInfo.setNamedTypeInfo(nullptr); |
5035 | return NameInfo; |
5036 | } |
5037 | |
5038 | case UnqualifiedIdKind::IK_DestructorName: { |
5039 | TypeSourceInfo *TInfo; |
5040 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); |
5041 | if (Ty.isNull()) |
5042 | return DeclarationNameInfo(); |
5043 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( |
5044 | Context.getCanonicalType(Ty))); |
5045 | NameInfo.setNamedTypeInfo(TInfo); |
5046 | return NameInfo; |
5047 | } |
5048 | |
5049 | case UnqualifiedIdKind::IK_TemplateId: { |
5050 | TemplateName TName = Name.TemplateId->Template.get(); |
5051 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; |
5052 | return Context.getNameForTemplate(TName, TNameLoc); |
5053 | } |
5054 | |
5055 | } // switch (Name.getKind()) |
5056 | |
5057 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 5057); |
5058 | } |
5059 | |
5060 | static QualType getCoreType(QualType Ty) { |
5061 | do { |
5062 | if (Ty->isPointerType() || Ty->isReferenceType()) |
5063 | Ty = Ty->getPointeeType(); |
5064 | else if (Ty->isArrayType()) |
5065 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); |
5066 | else |
5067 | return Ty.withoutLocalFastQualifiers(); |
5068 | } while (true); |
5069 | } |
5070 | |
5071 | /// hasSimilarParameters - Determine whether the C++ functions Declaration |
5072 | /// and Definition have "nearly" matching parameters. This heuristic is |
5073 | /// used to improve diagnostics in the case where an out-of-line function |
5074 | /// definition doesn't match any declaration within the class or namespace. |
5075 | /// Also sets Params to the list of indices to the parameters that differ |
5076 | /// between the declaration and the definition. If hasSimilarParameters |
5077 | /// returns true and Params is empty, then all of the parameters match. |
5078 | static bool hasSimilarParameters(ASTContext &Context, |
5079 | FunctionDecl *Declaration, |
5080 | FunctionDecl *Definition, |
5081 | SmallVectorImpl<unsigned> &Params) { |
5082 | Params.clear(); |
5083 | if (Declaration->param_size() != Definition->param_size()) |
5084 | return false; |
5085 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { |
5086 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); |
5087 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); |
5088 | |
5089 | // The parameter types are identical |
5090 | if (Context.hasSameType(DefParamTy, DeclParamTy)) |
5091 | continue; |
5092 | |
5093 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); |
5094 | QualType DefParamBaseTy = getCoreType(DefParamTy); |
5095 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); |
5096 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); |
5097 | |
5098 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || |
5099 | (DeclTyName && DeclTyName == DefTyName)) |
5100 | Params.push_back(Idx); |
5101 | else // The two parameters aren't even close |
5102 | return false; |
5103 | } |
5104 | |
5105 | return true; |
5106 | } |
5107 | |
5108 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given |
5109 | /// declarator needs to be rebuilt in the current instantiation. |
5110 | /// Any bits of declarator which appear before the name are valid for |
5111 | /// consideration here. That's specifically the type in the decl spec |
5112 | /// and the base type in any member-pointer chunks. |
5113 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, |
5114 | DeclarationName Name) { |
5115 | // The types we specifically need to rebuild are: |
5116 | // - typenames, typeofs, and decltypes |
5117 | // - types which will become injected class names |
5118 | // Of course, we also need to rebuild any type referencing such a |
5119 | // type. It's safest to just say "dependent", but we call out a |
5120 | // few cases here. |
5121 | |
5122 | DeclSpec &DS = D.getMutableDeclSpec(); |
5123 | switch (DS.getTypeSpecType()) { |
5124 | case DeclSpec::TST_typename: |
5125 | case DeclSpec::TST_typeofType: |
5126 | case DeclSpec::TST_underlyingType: |
5127 | case DeclSpec::TST_atomic: { |
5128 | // Grab the type from the parser. |
5129 | TypeSourceInfo *TSI = nullptr; |
5130 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); |
5131 | if (T.isNull() || !T->isDependentType()) break; |
5132 | |
5133 | // Make sure there's a type source info. This isn't really much |
5134 | // of a waste; most dependent types should have type source info |
5135 | // attached already. |
5136 | if (!TSI) |
5137 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); |
5138 | |
5139 | // Rebuild the type in the current instantiation. |
5140 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); |
5141 | if (!TSI) return true; |
5142 | |
5143 | // Store the new type back in the decl spec. |
5144 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); |
5145 | DS.UpdateTypeRep(LocType); |
5146 | break; |
5147 | } |
5148 | |
5149 | case DeclSpec::TST_decltype: |
5150 | case DeclSpec::TST_typeofExpr: { |
5151 | Expr *E = DS.getRepAsExpr(); |
5152 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); |
5153 | if (Result.isInvalid()) return true; |
5154 | DS.UpdateExprRep(Result.get()); |
5155 | break; |
5156 | } |
5157 | |
5158 | default: |
5159 | // Nothing to do for these decl specs. |
5160 | break; |
5161 | } |
5162 | |
5163 | // It doesn't matter what order we do this in. |
5164 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { |
5165 | DeclaratorChunk &Chunk = D.getTypeObject(I); |
5166 | |
5167 | // The only type information in the declarator which can come |
5168 | // before the declaration name is the base type of a member |
5169 | // pointer. |
5170 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) |
5171 | continue; |
5172 | |
5173 | // Rebuild the scope specifier in-place. |
5174 | CXXScopeSpec &SS = Chunk.Mem.Scope(); |
5175 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) |
5176 | return true; |
5177 | } |
5178 | |
5179 | return false; |
5180 | } |
5181 | |
5182 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { |
5183 | D.setFunctionDefinitionKind(FDK_Declaration); |
5184 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); |
5185 | |
5186 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && |
5187 | Dcl && Dcl->getDeclContext()->isFileContext()) |
5188 | Dcl->setTopLevelDeclInObjCContainer(); |
5189 | |
5190 | if (getLangOpts().OpenCL) |
5191 | setCurrentOpenCLExtensionForDecl(Dcl); |
5192 | |
5193 | return Dcl; |
5194 | } |
5195 | |
5196 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: |
5197 | /// If T is the name of a class, then each of the following shall have a |
5198 | /// name different from T: |
5199 | /// - every static data member of class T; |
5200 | /// - every member function of class T |
5201 | /// - every member of class T that is itself a type; |
5202 | /// \returns true if the declaration name violates these rules. |
5203 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, |
5204 | DeclarationNameInfo NameInfo) { |
5205 | DeclarationName Name = NameInfo.getName(); |
5206 | |
5207 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); |
5208 | while (Record && Record->isAnonymousStructOrUnion()) |
5209 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); |
5210 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { |
5211 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; |
5212 | return true; |
5213 | } |
5214 | |
5215 | return false; |
5216 | } |
5217 | |
5218 | /// Diagnose a declaration whose declarator-id has the given |
5219 | /// nested-name-specifier. |
5220 | /// |
5221 | /// \param SS The nested-name-specifier of the declarator-id. |
5222 | /// |
5223 | /// \param DC The declaration context to which the nested-name-specifier |
5224 | /// resolves. |
5225 | /// |
5226 | /// \param Name The name of the entity being declared. |
5227 | /// |
5228 | /// \param Loc The location of the name of the entity being declared. |
5229 | /// |
5230 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus |
5231 | /// we're declaring an explicit / partial specialization / instantiation. |
5232 | /// |
5233 | /// \returns true if we cannot safely recover from this error, false otherwise. |
5234 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, |
5235 | DeclarationName Name, |
5236 | SourceLocation Loc, bool IsTemplateId) { |
5237 | DeclContext *Cur = CurContext; |
5238 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) |
5239 | Cur = Cur->getParent(); |
5240 | |
5241 | // If the user provided a superfluous scope specifier that refers back to the |
5242 | // class in which the entity is already declared, diagnose and ignore it. |
5243 | // |
5244 | // class X { |
5245 | // void X::f(); |
5246 | // }; |
5247 | // |
5248 | // Note, it was once ill-formed to give redundant qualification in all |
5249 | // contexts, but that rule was removed by DR482. |
5250 | if (Cur->Equals(DC)) { |
5251 | if (Cur->isRecord()) { |
5252 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification |
5253 | : diag::err_member_extra_qualification) |
5254 | << Name << FixItHint::CreateRemoval(SS.getRange()); |
5255 | SS.clear(); |
5256 | } else { |
5257 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; |
5258 | } |
5259 | return false; |
5260 | } |
5261 | |
5262 | // Check whether the qualifying scope encloses the scope of the original |
5263 | // declaration. For a template-id, we perform the checks in |
5264 | // CheckTemplateSpecializationScope. |
5265 | if (!Cur->Encloses(DC) && !IsTemplateId) { |
5266 | if (Cur->isRecord()) |
5267 | Diag(Loc, diag::err_member_qualification) |
5268 | << Name << SS.getRange(); |
5269 | else if (isa<TranslationUnitDecl>(DC)) |
5270 | Diag(Loc, diag::err_invalid_declarator_global_scope) |
5271 | << Name << SS.getRange(); |
5272 | else if (isa<FunctionDecl>(Cur)) |
5273 | Diag(Loc, diag::err_invalid_declarator_in_function) |
5274 | << Name << SS.getRange(); |
5275 | else if (isa<BlockDecl>(Cur)) |
5276 | Diag(Loc, diag::err_invalid_declarator_in_block) |
5277 | << Name << SS.getRange(); |
5278 | else |
5279 | Diag(Loc, diag::err_invalid_declarator_scope) |
5280 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); |
5281 | |
5282 | return true; |
5283 | } |
5284 | |
5285 | if (Cur->isRecord()) { |
5286 | // Cannot qualify members within a class. |
5287 | Diag(Loc, diag::err_member_qualification) |
5288 | << Name << SS.getRange(); |
5289 | SS.clear(); |
5290 | |
5291 | // C++ constructors and destructors with incorrect scopes can break |
5292 | // our AST invariants by having the wrong underlying types. If |
5293 | // that's the case, then drop this declaration entirely. |
5294 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || |
5295 | Name.getNameKind() == DeclarationName::CXXDestructorName) && |
5296 | !Context.hasSameType(Name.getCXXNameType(), |
5297 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) |
5298 | return true; |
5299 | |
5300 | return false; |
5301 | } |
5302 | |
5303 | // C++11 [dcl.meaning]p1: |
5304 | // [...] "The nested-name-specifier of the qualified declarator-id shall |
5305 | // not begin with a decltype-specifer" |
5306 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); |
5307 | while (SpecLoc.getPrefix()) |
5308 | SpecLoc = SpecLoc.getPrefix(); |
5309 | if (dyn_cast_or_null<DecltypeType>( |
5310 | SpecLoc.getNestedNameSpecifier()->getAsType())) |
5311 | Diag(Loc, diag::err_decltype_in_declarator) |
5312 | << SpecLoc.getTypeLoc().getSourceRange(); |
5313 | |
5314 | return false; |
5315 | } |
5316 | |
5317 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, |
5318 | MultiTemplateParamsArg TemplateParamLists) { |
5319 | // TODO: consider using NameInfo for diagnostic. |
5320 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
5321 | DeclarationName Name = NameInfo.getName(); |
5322 | |
5323 | // All of these full declarators require an identifier. If it doesn't have |
5324 | // one, the ParsedFreeStandingDeclSpec action should be used. |
5325 | if (D.isDecompositionDeclarator()) { |
5326 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); |
5327 | } else if (!Name) { |
5328 | if (!D.isInvalidType()) // Reject this if we think it is valid. |
5329 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) |
5330 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); |
5331 | return nullptr; |
5332 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) |
5333 | return nullptr; |
5334 | |
5335 | // The scope passed in may not be a decl scope. Zip up the scope tree until |
5336 | // we find one that is. |
5337 | while ((S->getFlags() & Scope::DeclScope) == 0 || |
5338 | (S->getFlags() & Scope::TemplateParamScope) != 0) |
5339 | S = S->getParent(); |
5340 | |
5341 | DeclContext *DC = CurContext; |
5342 | if (D.getCXXScopeSpec().isInvalid()) |
5343 | D.setInvalidType(); |
5344 | else if (D.getCXXScopeSpec().isSet()) { |
5345 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), |
5346 | UPPC_DeclarationQualifier)) |
5347 | return nullptr; |
5348 | |
5349 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); |
5350 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); |
5351 | if (!DC || isa<EnumDecl>(DC)) { |
5352 | // If we could not compute the declaration context, it's because the |
5353 | // declaration context is dependent but does not refer to a class, |
5354 | // class template, or class template partial specialization. Complain |
5355 | // and return early, to avoid the coming semantic disaster. |
5356 | Diag(D.getIdentifierLoc(), |
5357 | diag::err_template_qualified_declarator_no_match) |
5358 | << D.getCXXScopeSpec().getScopeRep() |
5359 | << D.getCXXScopeSpec().getRange(); |
5360 | return nullptr; |
5361 | } |
5362 | bool IsDependentContext = DC->isDependentContext(); |
5363 | |
5364 | if (!IsDependentContext && |
5365 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) |
5366 | return nullptr; |
5367 | |
5368 | // If a class is incomplete, do not parse entities inside it. |
5369 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { |
5370 | Diag(D.getIdentifierLoc(), |
5371 | diag::err_member_def_undefined_record) |
5372 | << Name << DC << D.getCXXScopeSpec().getRange(); |
5373 | return nullptr; |
5374 | } |
5375 | if (!D.getDeclSpec().isFriendSpecified()) { |
5376 | if (diagnoseQualifiedDeclaration( |
5377 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), |
5378 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { |
5379 | if (DC->isRecord()) |
5380 | return nullptr; |
5381 | |
5382 | D.setInvalidType(); |
5383 | } |
5384 | } |
5385 | |
5386 | // Check whether we need to rebuild the type of the given |
5387 | // declaration in the current instantiation. |
5388 | if (EnteringContext && IsDependentContext && |
5389 | TemplateParamLists.size() != 0) { |
5390 | ContextRAII SavedContext(*this, DC); |
5391 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) |
5392 | D.setInvalidType(); |
5393 | } |
5394 | } |
5395 | |
5396 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
5397 | QualType R = TInfo->getType(); |
5398 | |
5399 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, |
5400 | UPPC_DeclarationType)) |
5401 | D.setInvalidType(); |
5402 | |
5403 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, |
5404 | forRedeclarationInCurContext()); |
5405 | |
5406 | // See if this is a redefinition of a variable in the same scope. |
5407 | if (!D.getCXXScopeSpec().isSet()) { |
5408 | bool IsLinkageLookup = false; |
5409 | bool CreateBuiltins = false; |
5410 | |
5411 | // If the declaration we're planning to build will be a function |
5412 | // or object with linkage, then look for another declaration with |
5413 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). |
5414 | // |
5415 | // If the declaration we're planning to build will be declared with |
5416 | // external linkage in the translation unit, create any builtin with |
5417 | // the same name. |
5418 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) |
5419 | /* Do nothing*/; |
5420 | else if (CurContext->isFunctionOrMethod() && |
5421 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || |
5422 | R->isFunctionType())) { |
5423 | IsLinkageLookup = true; |
5424 | CreateBuiltins = |
5425 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); |
5426 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && |
5427 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) |
5428 | CreateBuiltins = true; |
5429 | |
5430 | if (IsLinkageLookup) { |
5431 | Previous.clear(LookupRedeclarationWithLinkage); |
5432 | Previous.setRedeclarationKind(ForExternalRedeclaration); |
5433 | } |
5434 | |
5435 | LookupName(Previous, S, CreateBuiltins); |
5436 | } else { // Something like "int foo::x;" |
5437 | LookupQualifiedName(Previous, DC); |
5438 | |
5439 | // C++ [dcl.meaning]p1: |
5440 | // When the declarator-id is qualified, the declaration shall refer to a |
5441 | // previously declared member of the class or namespace to which the |
5442 | // qualifier refers (or, in the case of a namespace, of an element of the |
5443 | // inline namespace set of that namespace (7.3.1)) or to a specialization |
5444 | // thereof; [...] |
5445 | // |
5446 | // Note that we already checked the context above, and that we do not have |
5447 | // enough information to make sure that Previous contains the declaration |
5448 | // we want to match. For example, given: |
5449 | // |
5450 | // class X { |
5451 | // void f(); |
5452 | // void f(float); |
5453 | // }; |
5454 | // |
5455 | // void X::f(int) { } // ill-formed |
5456 | // |
5457 | // In this case, Previous will point to the overload set |
5458 | // containing the two f's declared in X, but neither of them |
5459 | // matches. |
5460 | |
5461 | // C++ [dcl.meaning]p1: |
5462 | // [...] the member shall not merely have been introduced by a |
5463 | // using-declaration in the scope of the class or namespace nominated by |
5464 | // the nested-name-specifier of the declarator-id. |
5465 | RemoveUsingDecls(Previous); |
5466 | } |
5467 | |
5468 | if (Previous.isSingleResult() && |
5469 | Previous.getFoundDecl()->isTemplateParameter()) { |
5470 | // Maybe we will complain about the shadowed template parameter. |
5471 | if (!D.isInvalidType()) |
5472 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), |
5473 | Previous.getFoundDecl()); |
5474 | |
5475 | // Just pretend that we didn't see the previous declaration. |
5476 | Previous.clear(); |
5477 | } |
5478 | |
5479 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) |
5480 | // Forget that the previous declaration is the injected-class-name. |
5481 | Previous.clear(); |
5482 | |
5483 | // In C++, the previous declaration we find might be a tag type |
5484 | // (class or enum). In this case, the new declaration will hide the |
5485 | // tag type. Note that this applies to functions, function templates, and |
5486 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. |
5487 | if (Previous.isSingleTagDecl() && |
5488 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && |
5489 | (TemplateParamLists.size() == 0 || R->isFunctionType())) |
5490 | Previous.clear(); |
5491 | |
5492 | // Check that there are no default arguments other than in the parameters |
5493 | // of a function declaration (C++ only). |
5494 | if (getLangOpts().CPlusPlus) |
5495 | CheckExtraCXXDefaultArguments(D); |
5496 | |
5497 | NamedDecl *New; |
5498 | |
5499 | bool AddToScope = true; |
5500 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { |
5501 | if (TemplateParamLists.size()) { |
5502 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); |
5503 | return nullptr; |
5504 | } |
5505 | |
5506 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); |
5507 | } else if (R->isFunctionType()) { |
5508 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, |
5509 | TemplateParamLists, |
5510 | AddToScope); |
5511 | } else { |
5512 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, |
5513 | AddToScope); |
5514 | } |
5515 | |
5516 | if (!New) |
5517 | return nullptr; |
5518 | |
5519 | // If this has an identifier and is not a function template specialization, |
5520 | // add it to the scope stack. |
5521 | if (New->getDeclName() && AddToScope) { |
5522 | // Only make a locally-scoped extern declaration visible if it is the first |
5523 | // declaration of this entity. Qualified lookup for such an entity should |
5524 | // only find this declaration if there is no visible declaration of it. |
5525 | bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); |
5526 | PushOnScopeChains(New, S, AddToContext); |
5527 | if (!AddToContext) |
5528 | CurContext->addHiddenDecl(New); |
5529 | } |
5530 | |
5531 | if (isInOpenMPDeclareTargetContext()) |
5532 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); |
5533 | |
5534 | return New; |
5535 | } |
5536 | |
5537 | /// Helper method to turn variable array types into constant array |
5538 | /// types in certain situations which would otherwise be errors (for |
5539 | /// GCC compatibility). |
5540 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, |
5541 | ASTContext &Context, |
5542 | bool &SizeIsNegative, |
5543 | llvm::APSInt &Oversized) { |
5544 | // This method tries to turn a variable array into a constant |
5545 | // array even when the size isn't an ICE. This is necessary |
5546 | // for compatibility with code that depends on gcc's buggy |
5547 | // constant expression folding, like struct {char x[(int)(char*)2];} |
5548 | SizeIsNegative = false; |
5549 | Oversized = 0; |
5550 | |
5551 | if (T->isDependentType()) |
5552 | return QualType(); |
5553 | |
5554 | QualifierCollector Qs; |
5555 | const Type *Ty = Qs.strip(T); |
5556 | |
5557 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { |
5558 | QualType Pointee = PTy->getPointeeType(); |
5559 | QualType FixedType = |
5560 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, |
5561 | Oversized); |
5562 | if (FixedType.isNull()) return FixedType; |
5563 | FixedType = Context.getPointerType(FixedType); |
5564 | return Qs.apply(Context, FixedType); |
5565 | } |
5566 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { |
5567 | QualType Inner = PTy->getInnerType(); |
5568 | QualType FixedType = |
5569 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, |
5570 | Oversized); |
5571 | if (FixedType.isNull()) return FixedType; |
5572 | FixedType = Context.getParenType(FixedType); |
5573 | return Qs.apply(Context, FixedType); |
5574 | } |
5575 | |
5576 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); |
5577 | if (!VLATy) |
5578 | return QualType(); |
5579 | // FIXME: We should probably handle this case |
5580 | if (VLATy->getElementType()->isVariablyModifiedType()) |
5581 | return QualType(); |
5582 | |
5583 | Expr::EvalResult Result; |
5584 | if (!VLATy->getSizeExpr() || |
5585 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) |
5586 | return QualType(); |
5587 | |
5588 | llvm::APSInt Res = Result.Val.getInt(); |
5589 | |
5590 | // Check whether the array size is negative. |
5591 | if (Res.isSigned() && Res.isNegative()) { |
5592 | SizeIsNegative = true; |
5593 | return QualType(); |
5594 | } |
5595 | |
5596 | // Check whether the array is too large to be addressed. |
5597 | unsigned ActiveSizeBits |
5598 | = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), |
5599 | Res); |
5600 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { |
5601 | Oversized = Res; |
5602 | return QualType(); |
5603 | } |
5604 | |
5605 | return Context.getConstantArrayType(VLATy->getElementType(), |
5606 | Res, ArrayType::Normal, 0); |
5607 | } |
5608 | |
5609 | static void |
5610 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { |
5611 | SrcTL = SrcTL.getUnqualifiedLoc(); |
5612 | DstTL = DstTL.getUnqualifiedLoc(); |
5613 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { |
5614 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); |
5615 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), |
5616 | DstPTL.getPointeeLoc()); |
5617 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); |
5618 | return; |
5619 | } |
5620 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { |
5621 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); |
5622 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), |
5623 | DstPTL.getInnerLoc()); |
5624 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); |
5625 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); |
5626 | return; |
5627 | } |
5628 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); |
5629 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); |
5630 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); |
5631 | TypeLoc DstElemTL = DstATL.getElementLoc(); |
5632 | DstElemTL.initializeFullCopy(SrcElemTL); |
5633 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); |
5634 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); |
5635 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); |
5636 | } |
5637 | |
5638 | /// Helper method to turn variable array types into constant array |
5639 | /// types in certain situations which would otherwise be errors (for |
5640 | /// GCC compatibility). |
5641 | static TypeSourceInfo* |
5642 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, |
5643 | ASTContext &Context, |
5644 | bool &SizeIsNegative, |
5645 | llvm::APSInt &Oversized) { |
5646 | QualType FixedTy |
5647 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, |
5648 | SizeIsNegative, Oversized); |
5649 | if (FixedTy.isNull()) |
5650 | return nullptr; |
5651 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); |
5652 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), |
5653 | FixedTInfo->getTypeLoc()); |
5654 | return FixedTInfo; |
5655 | } |
5656 | |
5657 | /// Register the given locally-scoped extern "C" declaration so |
5658 | /// that it can be found later for redeclarations. We include any extern "C" |
5659 | /// declaration that is not visible in the translation unit here, not just |
5660 | /// function-scope declarations. |
5661 | void |
5662 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { |
5663 | if (!getLangOpts().CPlusPlus && |
5664 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) |
5665 | // Don't need to track declarations in the TU in C. |
5666 | return; |
5667 | |
5668 | // Note that we have a locally-scoped external with this name. |
5669 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); |
5670 | } |
5671 | |
5672 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { |
5673 | // FIXME: We can have multiple results via __attribute__((overloadable)). |
5674 | auto Result = Context.getExternCContextDecl()->lookup(Name); |
5675 | return Result.empty() ? nullptr : *Result.begin(); |
5676 | } |
5677 | |
5678 | /// Diagnose function specifiers on a declaration of an identifier that |
5679 | /// does not identify a function. |
5680 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { |
5681 | // FIXME: We should probably indicate the identifier in question to avoid |
5682 | // confusion for constructs like "virtual int a(), b;" |
5683 | if (DS.isVirtualSpecified()) |
5684 | Diag(DS.getVirtualSpecLoc(), |
5685 | diag::err_virtual_non_function); |
5686 | |
5687 | if (DS.isExplicitSpecified()) |
5688 | Diag(DS.getExplicitSpecLoc(), |
5689 | diag::err_explicit_non_function); |
5690 | |
5691 | if (DS.isNoreturnSpecified()) |
5692 | Diag(DS.getNoreturnSpecLoc(), |
5693 | diag::err_noreturn_non_function); |
5694 | } |
5695 | |
5696 | NamedDecl* |
5697 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, |
5698 | TypeSourceInfo *TInfo, LookupResult &Previous) { |
5699 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). |
5700 | if (D.getCXXScopeSpec().isSet()) { |
5701 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) |
5702 | << D.getCXXScopeSpec().getRange(); |
5703 | D.setInvalidType(); |
5704 | // Pretend we didn't see the scope specifier. |
5705 | DC = CurContext; |
5706 | Previous.clear(); |
5707 | } |
5708 | |
5709 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); |
5710 | |
5711 | if (D.getDeclSpec().isInlineSpecified()) |
5712 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) |
5713 | << getLangOpts().CPlusPlus17; |
5714 | if (D.getDeclSpec().isConstexprSpecified()) |
5715 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) |
5716 | << 1; |
5717 | |
5718 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { |
5719 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) |
5720 | Diag(D.getName().StartLocation, |
5721 | diag::err_deduction_guide_invalid_specifier) |
5722 | << "typedef"; |
5723 | else |
5724 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) |
5725 | << D.getName().getSourceRange(); |
5726 | return nullptr; |
5727 | } |
5728 | |
5729 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); |
5730 | if (!NewTD) return nullptr; |
5731 | |
5732 | // Handle attributes prior to checking for duplicates in MergeVarDecl |
5733 | ProcessDeclAttributes(S, NewTD, D); |
5734 | |
5735 | CheckTypedefForVariablyModifiedType(S, NewTD); |
5736 | |
5737 | bool Redeclaration = D.isRedeclaration(); |
5738 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); |
5739 | D.setRedeclaration(Redeclaration); |
5740 | return ND; |
5741 | } |
5742 | |
5743 | void |
5744 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { |
5745 | // C99 6.7.7p2: If a typedef name specifies a variably modified type |
5746 | // then it shall have block scope. |
5747 | // Note that variably modified types must be fixed before merging the decl so |
5748 | // that redeclarations will match. |
5749 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); |
5750 | QualType T = TInfo->getType(); |
5751 | if (T->isVariablyModifiedType()) { |
5752 | setFunctionHasBranchProtectedScope(); |
5753 | |
5754 | if (S->getFnParent() == nullptr) { |
5755 | bool SizeIsNegative; |
5756 | llvm::APSInt Oversized; |
5757 | TypeSourceInfo *FixedTInfo = |
5758 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, |
5759 | SizeIsNegative, |
5760 | Oversized); |
5761 | if (FixedTInfo) { |
5762 | Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); |
5763 | NewTD->setTypeSourceInfo(FixedTInfo); |
5764 | } else { |
5765 | if (SizeIsNegative) |
5766 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); |
5767 | else if (T->isVariableArrayType()) |
5768 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); |
5769 | else if (Oversized.getBoolValue()) |
5770 | Diag(NewTD->getLocation(), diag::err_array_too_large) |
5771 | << Oversized.toString(10); |
5772 | else |
5773 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); |
5774 | NewTD->setInvalidDecl(); |
5775 | } |
5776 | } |
5777 | } |
5778 | } |
5779 | |
5780 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which |
5781 | /// declares a typedef-name, either using the 'typedef' type specifier or via |
5782 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. |
5783 | NamedDecl* |
5784 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, |
5785 | LookupResult &Previous, bool &Redeclaration) { |
5786 | |
5787 | // Find the shadowed declaration before filtering for scope. |
5788 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); |
5789 | |
5790 | // Merge the decl with the existing one if appropriate. If the decl is |
5791 | // in an outer scope, it isn't the same thing. |
5792 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, |
5793 | /*AllowInlineNamespace*/false); |
5794 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); |
5795 | if (!Previous.empty()) { |
5796 | Redeclaration = true; |
5797 | MergeTypedefNameDecl(S, NewTD, Previous); |
5798 | } |
5799 | |
5800 | if (ShadowedDecl && !Redeclaration) |
5801 | CheckShadow(NewTD, ShadowedDecl, Previous); |
5802 | |
5803 | // If this is the C FILE type, notify the AST context. |
5804 | if (IdentifierInfo *II = NewTD->getIdentifier()) |
5805 | if (!NewTD->isInvalidDecl() && |
5806 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { |
5807 | if (II->isStr("FILE")) |
5808 | Context.setFILEDecl(NewTD); |
5809 | else if (II->isStr("jmp_buf")) |
5810 | Context.setjmp_bufDecl(NewTD); |
5811 | else if (II->isStr("sigjmp_buf")) |
5812 | Context.setsigjmp_bufDecl(NewTD); |
5813 | else if (II->isStr("ucontext_t")) |
5814 | Context.setucontext_tDecl(NewTD); |
5815 | } |
5816 | |
5817 | return NewTD; |
5818 | } |
5819 | |
5820 | /// Determines whether the given declaration is an out-of-scope |
5821 | /// previous declaration. |
5822 | /// |
5823 | /// This routine should be invoked when name lookup has found a |
5824 | /// previous declaration (PrevDecl) that is not in the scope where a |
5825 | /// new declaration by the same name is being introduced. If the new |
5826 | /// declaration occurs in a local scope, previous declarations with |
5827 | /// linkage may still be considered previous declarations (C99 |
5828 | /// 6.2.2p4-5, C++ [basic.link]p6). |
5829 | /// |
5830 | /// \param PrevDecl the previous declaration found by name |
5831 | /// lookup |
5832 | /// |
5833 | /// \param DC the context in which the new declaration is being |
5834 | /// declared. |
5835 | /// |
5836 | /// \returns true if PrevDecl is an out-of-scope previous declaration |
5837 | /// for a new delcaration with the same name. |
5838 | static bool |
5839 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, |
5840 | ASTContext &Context) { |
5841 | if (!PrevDecl) |
5842 | return false; |
5843 | |
5844 | if (!PrevDecl->hasLinkage()) |
5845 | return false; |
5846 | |
5847 | if (Context.getLangOpts().CPlusPlus) { |
5848 | // C++ [basic.link]p6: |
5849 | // If there is a visible declaration of an entity with linkage |
5850 | // having the same name and type, ignoring entities declared |
5851 | // outside the innermost enclosing namespace scope, the block |
5852 | // scope declaration declares that same entity and receives the |
5853 | // linkage of the previous declaration. |
5854 | DeclContext *OuterContext = DC->getRedeclContext(); |
5855 | if (!OuterContext->isFunctionOrMethod()) |
5856 | // This rule only applies to block-scope declarations. |
5857 | return false; |
5858 | |
5859 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); |
5860 | if (PrevOuterContext->isRecord()) |
5861 | // We found a member function: ignore it. |
5862 | return false; |
5863 | |
5864 | // Find the innermost enclosing namespace for the new and |
5865 | // previous declarations. |
5866 | OuterContext = OuterContext->getEnclosingNamespaceContext(); |
5867 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); |
5868 | |
5869 | // The previous declaration is in a different namespace, so it |
5870 | // isn't the same function. |
5871 | if (!OuterContext->Equals(PrevOuterContext)) |
5872 | return false; |
5873 | } |
5874 | |
5875 | return true; |
5876 | } |
5877 | |
5878 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { |
5879 | CXXScopeSpec &SS = D.getCXXScopeSpec(); |
5880 | if (!SS.isSet()) return; |
5881 | DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); |
5882 | } |
5883 | |
5884 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { |
5885 | QualType type = decl->getType(); |
5886 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); |
5887 | if (lifetime == Qualifiers::OCL_Autoreleasing) { |
5888 | // Various kinds of declaration aren't allowed to be __autoreleasing. |
5889 | unsigned kind = -1U; |
5890 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { |
5891 | if (var->hasAttr<BlocksAttr>()) |
5892 | kind = 0; // __block |
5893 | else if (!var->hasLocalStorage()) |
5894 | kind = 1; // global |
5895 | } else if (isa<ObjCIvarDecl>(decl)) { |
5896 | kind = 3; // ivar |
5897 | } else if (isa<FieldDecl>(decl)) { |
5898 | kind = 2; // field |
5899 | } |
5900 | |
5901 | if (kind != -1U) { |
5902 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) |
5903 | << kind; |
5904 | } |
5905 | } else if (lifetime == Qualifiers::OCL_None) { |
5906 | // Try to infer lifetime. |
5907 | if (!type->isObjCLifetimeType()) |
5908 | return false; |
5909 | |
5910 | lifetime = type->getObjCARCImplicitLifetime(); |
5911 | type = Context.getLifetimeQualifiedType(type, lifetime); |
5912 | decl->setType(type); |
5913 | } |
5914 | |
5915 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { |
5916 | // Thread-local variables cannot have lifetime. |
5917 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && |
5918 | var->getTLSKind()) { |
5919 | Diag(var->getLocation(), diag::err_arc_thread_ownership) |
5920 | << var->getType(); |
5921 | return true; |
5922 | } |
5923 | } |
5924 | |
5925 | return false; |
5926 | } |
5927 | |
5928 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { |
5929 | // Ensure that an auto decl is deduced otherwise the checks below might cache |
5930 | // the wrong linkage. |
5931 | assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast <void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 5931, __PRETTY_FUNCTION__)); |
5932 | |
5933 | // 'weak' only applies to declarations with external linkage. |
5934 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { |
5935 | if (!ND.isExternallyVisible()) { |
5936 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); |
5937 | ND.dropAttr<WeakAttr>(); |
5938 | } |
5939 | } |
5940 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { |
5941 | if (ND.isExternallyVisible()) { |
5942 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); |
5943 | ND.dropAttr<WeakRefAttr>(); |
5944 | ND.dropAttr<AliasAttr>(); |
5945 | } |
5946 | } |
5947 | |
5948 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { |
5949 | if (VD->hasInit()) { |
5950 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { |
5951 | assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 5952, __PRETTY_FUNCTION__)) |
5952 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 5952, __PRETTY_FUNCTION__)); |
5953 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; |
5954 | VD->dropAttr<AliasAttr>(); |
5955 | } |
5956 | } |
5957 | } |
5958 | |
5959 | // 'selectany' only applies to externally visible variable declarations. |
5960 | // It does not apply to functions. |
5961 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { |
5962 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { |
5963 | S.Diag(Attr->getLocation(), |
5964 | diag::err_attribute_selectany_non_extern_data); |
5965 | ND.dropAttr<SelectAnyAttr>(); |
5966 | } |
5967 | } |
5968 | |
5969 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { |
5970 | // dll attributes require external linkage. Static locals may have external |
5971 | // linkage but still cannot be explicitly imported or exported. |
5972 | auto *VD = dyn_cast<VarDecl>(&ND); |
5973 | if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { |
5974 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) |
5975 | << &ND << Attr; |
5976 | ND.setInvalidDecl(); |
5977 | } |
5978 | } |
5979 | |
5980 | // Virtual functions cannot be marked as 'notail'. |
5981 | if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) |
5982 | if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) |
5983 | if (MD->isVirtual()) { |
5984 | S.Diag(ND.getLocation(), |
5985 | diag::err_invalid_attribute_on_virtual_function) |
5986 | << Attr; |
5987 | ND.dropAttr<NotTailCalledAttr>(); |
5988 | } |
5989 | |
5990 | // Check the attributes on the function type, if any. |
5991 | if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { |
5992 | // Don't declare this variable in the second operand of the for-statement; |
5993 | // GCC miscompiles that by ending its lifetime before evaluating the |
5994 | // third operand. See gcc.gnu.org/PR86769. |
5995 | AttributedTypeLoc ATL; |
5996 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); |
5997 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); |
5998 | TL = ATL.getModifiedLoc()) { |
5999 | // The [[lifetimebound]] attribute can be applied to the implicit object |
6000 | // parameter of a non-static member function (other than a ctor or dtor) |
6001 | // by applying it to the function type. |
6002 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { |
6003 | const auto *MD = dyn_cast<CXXMethodDecl>(FD); |
6004 | if (!MD || MD->isStatic()) { |
6005 | S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) |
6006 | << !MD << A->getRange(); |
6007 | } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { |
6008 | S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) |
6009 | << isa<CXXDestructorDecl>(MD) << A->getRange(); |
6010 | } |
6011 | } |
6012 | } |
6013 | } |
6014 | } |
6015 | |
6016 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, |
6017 | NamedDecl *NewDecl, |
6018 | bool IsSpecialization, |
6019 | bool IsDefinition) { |
6020 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) |
6021 | return; |
6022 | |
6023 | bool IsTemplate = false; |
6024 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { |
6025 | OldDecl = OldTD->getTemplatedDecl(); |
6026 | IsTemplate = true; |
6027 | if (!IsSpecialization) |
6028 | IsDefinition = false; |
6029 | } |
6030 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { |
6031 | NewDecl = NewTD->getTemplatedDecl(); |
6032 | IsTemplate = true; |
6033 | } |
6034 | |
6035 | if (!OldDecl || !NewDecl) |
6036 | return; |
6037 | |
6038 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); |
6039 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); |
6040 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); |
6041 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); |
6042 | |
6043 | // dllimport and dllexport are inheritable attributes so we have to exclude |
6044 | // inherited attribute instances. |
6045 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || |
6046 | (NewExportAttr && !NewExportAttr->isInherited()); |
6047 | |
6048 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, |
6049 | // the only exception being explicit specializations. |
6050 | // Implicitly generated declarations are also excluded for now because there |
6051 | // is no other way to switch these to use dllimport or dllexport. |
6052 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; |
6053 | |
6054 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { |
6055 | // Allow with a warning for free functions and global variables. |
6056 | bool JustWarn = false; |
6057 | if (!OldDecl->isCXXClassMember()) { |
6058 | auto *VD = dyn_cast<VarDecl>(OldDecl); |
6059 | if (VD && !VD->getDescribedVarTemplate()) |
6060 | JustWarn = true; |
6061 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); |
6062 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) |
6063 | JustWarn = true; |
6064 | } |
6065 | |
6066 | // We cannot change a declaration that's been used because IR has already |
6067 | // been emitted. Dllimported functions will still work though (modulo |
6068 | // address equality) as they can use the thunk. |
6069 | if (OldDecl->isUsed()) |
6070 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) |
6071 | JustWarn = false; |
6072 | |
6073 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration |
6074 | : diag::err_attribute_dll_redeclaration; |
6075 | S.Diag(NewDecl->getLocation(), DiagID) |
6076 | << NewDecl |
6077 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); |
6078 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); |
6079 | if (!JustWarn) { |
6080 | NewDecl->setInvalidDecl(); |
6081 | return; |
6082 | } |
6083 | } |
6084 | |
6085 | // A redeclaration is not allowed to drop a dllimport attribute, the only |
6086 | // exceptions being inline function definitions (except for function |
6087 | // templates), local extern declarations, qualified friend declarations or |
6088 | // special MSVC extension: in the last case, the declaration is treated as if |
6089 | // it were marked dllexport. |
6090 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; |
6091 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); |
6092 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { |
6093 | // Ignore static data because out-of-line definitions are diagnosed |
6094 | // separately. |
6095 | IsStaticDataMember = VD->isStaticDataMember(); |
6096 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != |
6097 | VarDecl::DeclarationOnly; |
6098 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { |
6099 | IsInline = FD->isInlined(); |
6100 | IsQualifiedFriend = FD->getQualifier() && |
6101 | FD->getFriendObjectKind() == Decl::FOK_Declared; |
6102 | } |
6103 | |
6104 | if (OldImportAttr && !HasNewAttr && |
6105 | (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && |
6106 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { |
6107 | if (IsMicrosoft && IsDefinition) { |
6108 | S.Diag(NewDecl->getLocation(), |
6109 | diag::warn_redeclaration_without_import_attribute) |
6110 | << NewDecl; |
6111 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); |
6112 | NewDecl->dropAttr<DLLImportAttr>(); |
6113 | NewDecl->addAttr(::new (S.Context) DLLExportAttr( |
6114 | NewImportAttr->getRange(), S.Context, |
6115 | NewImportAttr->getSpellingListIndex())); |
6116 | } else { |
6117 | S.Diag(NewDecl->getLocation(), |
6118 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) |
6119 | << NewDecl << OldImportAttr; |
6120 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); |
6121 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); |
6122 | OldDecl->dropAttr<DLLImportAttr>(); |
6123 | NewDecl->dropAttr<DLLImportAttr>(); |
6124 | } |
6125 | } else if (IsInline && OldImportAttr && !IsMicrosoft) { |
6126 | // In MinGW, seeing a function declared inline drops the dllimport |
6127 | // attribute. |
6128 | OldDecl->dropAttr<DLLImportAttr>(); |
6129 | NewDecl->dropAttr<DLLImportAttr>(); |
6130 | S.Diag(NewDecl->getLocation(), |
6131 | diag::warn_dllimport_dropped_from_inline_function) |
6132 | << NewDecl << OldImportAttr; |
6133 | } |
6134 | |
6135 | // A specialization of a class template member function is processed here |
6136 | // since it's a redeclaration. If the parent class is dllexport, the |
6137 | // specialization inherits that attribute. This doesn't happen automatically |
6138 | // since the parent class isn't instantiated until later. |
6139 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { |
6140 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && |
6141 | !NewImportAttr && !NewExportAttr) { |
6142 | if (const DLLExportAttr *ParentExportAttr = |
6143 | MD->getParent()->getAttr<DLLExportAttr>()) { |
6144 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); |
6145 | NewAttr->setInherited(true); |
6146 | NewDecl->addAttr(NewAttr); |
6147 | } |
6148 | } |
6149 | } |
6150 | } |
6151 | |
6152 | /// Given that we are within the definition of the given function, |
6153 | /// will that definition behave like C99's 'inline', where the |
6154 | /// definition is discarded except for optimization purposes? |
6155 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { |
6156 | // Try to avoid calling GetGVALinkageForFunction. |
6157 | |
6158 | // All cases of this require the 'inline' keyword. |
6159 | if (!FD->isInlined()) return false; |
6160 | |
6161 | // This is only possible in C++ with the gnu_inline attribute. |
6162 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) |
6163 | return false; |
6164 | |
6165 | // Okay, go ahead and call the relatively-more-expensive function. |
6166 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; |
6167 | } |
6168 | |
6169 | /// Determine whether a variable is extern "C" prior to attaching |
6170 | /// an initializer. We can't just call isExternC() here, because that |
6171 | /// will also compute and cache whether the declaration is externally |
6172 | /// visible, which might change when we attach the initializer. |
6173 | /// |
6174 | /// This can only be used if the declaration is known to not be a |
6175 | /// redeclaration of an internal linkage declaration. |
6176 | /// |
6177 | /// For instance: |
6178 | /// |
6179 | /// auto x = []{}; |
6180 | /// |
6181 | /// Attaching the initializer here makes this declaration not externally |
6182 | /// visible, because its type has internal linkage. |
6183 | /// |
6184 | /// FIXME: This is a hack. |
6185 | template<typename T> |
6186 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { |
6187 | if (S.getLangOpts().CPlusPlus) { |
6188 | // In C++, the overloadable attribute negates the effects of extern "C". |
6189 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) |
6190 | return false; |
6191 | |
6192 | // So do CUDA's host/device attributes. |
6193 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || |
6194 | D->template hasAttr<CUDAHostAttr>())) |
6195 | return false; |
6196 | } |
6197 | return D->isExternC(); |
6198 | } |
6199 | |
6200 | static bool shouldConsiderLinkage(const VarDecl *VD) { |
6201 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); |
6202 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) |
6203 | return VD->hasExternalStorage(); |
6204 | if (DC->isFileContext()) |
6205 | return true; |
6206 | if (DC->isRecord()) |
6207 | return false; |
6208 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6208); |
6209 | } |
6210 | |
6211 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { |
6212 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); |
6213 | if (DC->isFileContext() || DC->isFunctionOrMethod() || |
6214 | isa<OMPDeclareReductionDecl>(DC)) |
6215 | return true; |
6216 | if (DC->isRecord()) |
6217 | return false; |
6218 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6218); |
6219 | } |
6220 | |
6221 | static bool hasParsedAttr(Scope *S, const Declarator &PD, |
6222 | ParsedAttr::Kind Kind) { |
6223 | // Check decl attributes on the DeclSpec. |
6224 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) |
6225 | return true; |
6226 | |
6227 | // Walk the declarator structure, checking decl attributes that were in a type |
6228 | // position to the decl itself. |
6229 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { |
6230 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) |
6231 | return true; |
6232 | } |
6233 | |
6234 | // Finally, check attributes on the decl itself. |
6235 | return PD.getAttributes().hasAttribute(Kind); |
6236 | } |
6237 | |
6238 | /// Adjust the \c DeclContext for a function or variable that might be a |
6239 | /// function-local external declaration. |
6240 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { |
6241 | if (!DC->isFunctionOrMethod()) |
6242 | return false; |
6243 | |
6244 | // If this is a local extern function or variable declared within a function |
6245 | // template, don't add it into the enclosing namespace scope until it is |
6246 | // instantiated; it might have a dependent type right now. |
6247 | if (DC->isDependentContext()) |
6248 | return true; |
6249 | |
6250 | // C++11 [basic.link]p7: |
6251 | // When a block scope declaration of an entity with linkage is not found to |
6252 | // refer to some other declaration, then that entity is a member of the |
6253 | // innermost enclosing namespace. |
6254 | // |
6255 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a |
6256 | // semantically-enclosing namespace, not a lexically-enclosing one. |
6257 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) |
6258 | DC = DC->getParent(); |
6259 | return true; |
6260 | } |
6261 | |
6262 | /// Returns true if given declaration has external C language linkage. |
6263 | static bool isDeclExternC(const Decl *D) { |
6264 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) |
6265 | return FD->isExternC(); |
6266 | if (const auto *VD = dyn_cast<VarDecl>(D)) |
6267 | return VD->isExternC(); |
6268 | |
6269 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6269); |
6270 | } |
6271 | |
6272 | NamedDecl *Sema::ActOnVariableDeclarator( |
6273 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, |
6274 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, |
6275 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { |
6276 | QualType R = TInfo->getType(); |
6277 | DeclarationName Name = GetNameForDeclarator(D).getName(); |
6278 | |
6279 | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
6280 | |
6281 | if (D.isDecompositionDeclarator()) { |
6282 | // Take the name of the first declarator as our name for diagnostic |
6283 | // purposes. |
6284 | auto &Decomp = D.getDecompositionDeclarator(); |
6285 | if (!Decomp.bindings().empty()) { |
6286 | II = Decomp.bindings()[0].Name; |
6287 | Name = II; |
6288 | } |
6289 | } else if (!II) { |
6290 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; |
6291 | return nullptr; |
6292 | } |
6293 | |
6294 | if (getLangOpts().OpenCL) { |
6295 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. |
6296 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function |
6297 | // argument. |
6298 | if (R->isImageType() || R->isPipeType()) { |
6299 | Diag(D.getIdentifierLoc(), |
6300 | diag::err_opencl_type_can_only_be_used_as_function_parameter) |
6301 | << R; |
6302 | D.setInvalidType(); |
6303 | return nullptr; |
6304 | } |
6305 | |
6306 | // OpenCL v1.2 s6.9.r: |
6307 | // The event type cannot be used to declare a program scope variable. |
6308 | // OpenCL v2.0 s6.9.q: |
6309 | // The clk_event_t and reserve_id_t types cannot be declared in program scope. |
6310 | if (NULL__null == S->getParent()) { |
6311 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { |
6312 | Diag(D.getIdentifierLoc(), |
6313 | diag::err_invalid_type_for_program_scope_var) << R; |
6314 | D.setInvalidType(); |
6315 | return nullptr; |
6316 | } |
6317 | } |
6318 | |
6319 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. |
6320 | QualType NR = R; |
6321 | while (NR->isPointerType()) { |
6322 | if (NR->isFunctionPointerType()) { |
6323 | Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); |
6324 | D.setInvalidType(); |
6325 | break; |
6326 | } |
6327 | NR = NR->getPointeeType(); |
6328 | } |
6329 | |
6330 | if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { |
6331 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and |
6332 | // half array type (unless the cl_khr_fp16 extension is enabled). |
6333 | if (Context.getBaseElementType(R)->isHalfType()) { |
6334 | Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; |
6335 | D.setInvalidType(); |
6336 | } |
6337 | } |
6338 | |
6339 | if (R->isSamplerT()) { |
6340 | // OpenCL v1.2 s6.9.b p4: |
6341 | // The sampler type cannot be used with the __local and __global address |
6342 | // space qualifiers. |
6343 | if (R.getAddressSpace() == LangAS::opencl_local || |
6344 | R.getAddressSpace() == LangAS::opencl_global) { |
6345 | Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); |
6346 | } |
6347 | |
6348 | // OpenCL v1.2 s6.12.14.1: |
6349 | // A global sampler must be declared with either the constant address |
6350 | // space qualifier or with the const qualifier. |
6351 | if (DC->isTranslationUnit() && |
6352 | !(R.getAddressSpace() == LangAS::opencl_constant || |
6353 | R.isConstQualified())) { |
6354 | Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); |
6355 | D.setInvalidType(); |
6356 | } |
6357 | } |
6358 | |
6359 | // OpenCL v1.2 s6.9.r: |
6360 | // The event type cannot be used with the __local, __constant and __global |
6361 | // address space qualifiers. |
6362 | if (R->isEventT()) { |
6363 | if (R.getAddressSpace() != LangAS::opencl_private) { |
6364 | Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); |
6365 | D.setInvalidType(); |
6366 | } |
6367 | } |
6368 | |
6369 | // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not |
6370 | // supported. OpenCL C does not support thread_local either, and |
6371 | // also reject all other thread storage class specifiers. |
6372 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); |
6373 | if (TSC != TSCS_unspecified) { |
6374 | bool IsCXX = getLangOpts().OpenCLCPlusPlus; |
6375 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), |
6376 | diag::err_opencl_unknown_type_specifier) |
6377 | << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() |
6378 | << DeclSpec::getSpecifierName(TSC) << 1; |
6379 | D.setInvalidType(); |
6380 | return nullptr; |
6381 | } |
6382 | } |
6383 | |
6384 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); |
6385 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); |
6386 | |
6387 | // dllimport globals without explicit storage class are treated as extern. We |
6388 | // have to change the storage class this early to get the right DeclContext. |
6389 | if (SC == SC_None && !DC->isRecord() && |
6390 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && |
6391 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) |
6392 | SC = SC_Extern; |
6393 | |
6394 | DeclContext *OriginalDC = DC; |
6395 | bool IsLocalExternDecl = SC == SC_Extern && |
6396 | adjustContextForLocalExternDecl(DC); |
6397 | |
6398 | if (SCSpec == DeclSpec::SCS_mutable) { |
6399 | // mutable can only appear on non-static class members, so it's always |
6400 | // an error here |
6401 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); |
6402 | D.setInvalidType(); |
6403 | SC = SC_None; |
6404 | } |
6405 | |
6406 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && |
6407 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( |
6408 | D.getDeclSpec().getStorageClassSpecLoc())) { |
6409 | // In C++11, the 'register' storage class specifier is deprecated. |
6410 | // Suppress the warning in system macros, it's used in macros in some |
6411 | // popular C system headers, such as in glibc's htonl() macro. |
6412 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), |
6413 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class |
6414 | : diag::warn_deprecated_register) |
6415 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); |
6416 | } |
6417 | |
6418 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); |
6419 | |
6420 | if (!DC->isRecord() && S->getFnParent() == nullptr) { |
6421 | // C99 6.9p2: The storage-class specifiers auto and register shall not |
6422 | // appear in the declaration specifiers in an external declaration. |
6423 | // Global Register+Asm is a GNU extension we support. |
6424 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { |
6425 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); |
6426 | D.setInvalidType(); |
6427 | } |
6428 | } |
6429 | |
6430 | bool IsMemberSpecialization = false; |
6431 | bool IsVariableTemplateSpecialization = false; |
6432 | bool IsPartialSpecialization = false; |
6433 | bool IsVariableTemplate = false; |
6434 | VarDecl *NewVD = nullptr; |
6435 | VarTemplateDecl *NewTemplate = nullptr; |
6436 | TemplateParameterList *TemplateParams = nullptr; |
6437 | if (!getLangOpts().CPlusPlus) { |
6438 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), |
6439 | II, R, TInfo, SC); |
6440 | |
6441 | if (R->getContainedDeducedType()) |
6442 | ParsingInitForAutoVars.insert(NewVD); |
6443 | |
6444 | if (D.isInvalidType()) |
6445 | NewVD->setInvalidDecl(); |
6446 | } else { |
6447 | bool Invalid = false; |
6448 | |
6449 | if (DC->isRecord() && !CurContext->isRecord()) { |
6450 | // This is an out-of-line definition of a static data member. |
6451 | switch (SC) { |
6452 | case SC_None: |
6453 | break; |
6454 | case SC_Static: |
6455 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), |
6456 | diag::err_static_out_of_line) |
6457 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); |
6458 | break; |
6459 | case SC_Auto: |
6460 | case SC_Register: |
6461 | case SC_Extern: |
6462 | // [dcl.stc] p2: The auto or register specifiers shall be applied only |
6463 | // to names of variables declared in a block or to function parameters. |
6464 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration |
6465 | // of class members |
6466 | |
6467 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), |
6468 | diag::err_storage_class_for_static_member) |
6469 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); |
6470 | break; |
6471 | case SC_PrivateExtern: |
6472 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6472); |
6473 | } |
6474 | } |
6475 | |
6476 | if (SC == SC_Static && CurContext->isRecord()) { |
6477 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { |
6478 | if (RD->isLocalClass()) |
6479 | Diag(D.getIdentifierLoc(), |
6480 | diag::err_static_data_member_not_allowed_in_local_class) |
6481 | << Name << RD->getDeclName(); |
6482 | |
6483 | // C++98 [class.union]p1: If a union contains a static data member, |
6484 | // the program is ill-formed. C++11 drops this restriction. |
6485 | if (RD->isUnion()) |
6486 | Diag(D.getIdentifierLoc(), |
6487 | getLangOpts().CPlusPlus11 |
6488 | ? diag::warn_cxx98_compat_static_data_member_in_union |
6489 | : diag::ext_static_data_member_in_union) << Name; |
6490 | // We conservatively disallow static data members in anonymous structs. |
6491 | else if (!RD->getDeclName()) |
6492 | Diag(D.getIdentifierLoc(), |
6493 | diag::err_static_data_member_not_allowed_in_anon_struct) |
6494 | << Name << RD->isUnion(); |
6495 | } |
6496 | } |
6497 | |
6498 | // Match up the template parameter lists with the scope specifier, then |
6499 | // determine whether we have a template or a template specialization. |
6500 | TemplateParams = MatchTemplateParametersToScopeSpecifier( |
6501 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), |
6502 | D.getCXXScopeSpec(), |
6503 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId |
6504 | ? D.getName().TemplateId |
6505 | : nullptr, |
6506 | TemplateParamLists, |
6507 | /*never a friend*/ false, IsMemberSpecialization, Invalid); |
6508 | |
6509 | if (TemplateParams) { |
6510 | if (!TemplateParams->size() && |
6511 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { |
6512 | // There is an extraneous 'template<>' for this variable. Complain |
6513 | // about it, but allow the declaration of the variable. |
6514 | Diag(TemplateParams->getTemplateLoc(), |
6515 | diag::err_template_variable_noparams) |
6516 | << II |
6517 | << SourceRange(TemplateParams->getTemplateLoc(), |
6518 | TemplateParams->getRAngleLoc()); |
6519 | TemplateParams = nullptr; |
6520 | } else { |
6521 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { |
6522 | // This is an explicit specialization or a partial specialization. |
6523 | // FIXME: Check that we can declare a specialization here. |
6524 | IsVariableTemplateSpecialization = true; |
6525 | IsPartialSpecialization = TemplateParams->size() > 0; |
6526 | } else { // if (TemplateParams->size() > 0) |
6527 | // This is a template declaration. |
6528 | IsVariableTemplate = true; |
6529 | |
6530 | // Check that we can declare a template here. |
6531 | if (CheckTemplateDeclScope(S, TemplateParams)) |
6532 | return nullptr; |
6533 | |
6534 | // Only C++1y supports variable templates (N3651). |
6535 | Diag(D.getIdentifierLoc(), |
6536 | getLangOpts().CPlusPlus14 |
6537 | ? diag::warn_cxx11_compat_variable_template |
6538 | : diag::ext_variable_template); |
6539 | } |
6540 | } |
6541 | } else { |
6542 | assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6544, __PRETTY_FUNCTION__)) |
6543 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6544, __PRETTY_FUNCTION__)) |
6544 | "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6544, __PRETTY_FUNCTION__)); |
6545 | } |
6546 | |
6547 | if (IsVariableTemplateSpecialization) { |
6548 | SourceLocation TemplateKWLoc = |
6549 | TemplateParamLists.size() > 0 |
6550 | ? TemplateParamLists[0]->getTemplateLoc() |
6551 | : SourceLocation(); |
6552 | DeclResult Res = ActOnVarTemplateSpecialization( |
6553 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, |
6554 | IsPartialSpecialization); |
6555 | if (Res.isInvalid()) |
6556 | return nullptr; |
6557 | NewVD = cast<VarDecl>(Res.get()); |
6558 | AddToScope = false; |
6559 | } else if (D.isDecompositionDeclarator()) { |
6560 | NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), |
6561 | D.getIdentifierLoc(), R, TInfo, SC, |
6562 | Bindings); |
6563 | } else |
6564 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), |
6565 | D.getIdentifierLoc(), II, R, TInfo, SC); |
6566 | |
6567 | // If this is supposed to be a variable template, create it as such. |
6568 | if (IsVariableTemplate) { |
6569 | NewTemplate = |
6570 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, |
6571 | TemplateParams, NewVD); |
6572 | NewVD->setDescribedVarTemplate(NewTemplate); |
6573 | } |
6574 | |
6575 | // If this decl has an auto type in need of deduction, make a note of the |
6576 | // Decl so we can diagnose uses of it in its own initializer. |
6577 | if (R->getContainedDeducedType()) |
6578 | ParsingInitForAutoVars.insert(NewVD); |
6579 | |
6580 | if (D.isInvalidType() || Invalid) { |
6581 | NewVD->setInvalidDecl(); |
6582 | if (NewTemplate) |
6583 | NewTemplate->setInvalidDecl(); |
6584 | } |
6585 | |
6586 | SetNestedNameSpecifier(*this, NewVD, D); |
6587 | |
6588 | // If we have any template parameter lists that don't directly belong to |
6589 | // the variable (matching the scope specifier), store them. |
6590 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; |
6591 | if (TemplateParamLists.size() > VDTemplateParamLists) |
6592 | NewVD->setTemplateParameterListsInfo( |
6593 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); |
6594 | |
6595 | if (D.getDeclSpec().isConstexprSpecified()) { |
6596 | NewVD->setConstexpr(true); |
6597 | // C++1z [dcl.spec.constexpr]p1: |
6598 | // A static data member declared with the constexpr specifier is |
6599 | // implicitly an inline variable. |
6600 | if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) |
6601 | NewVD->setImplicitlyInline(); |
6602 | } |
6603 | } |
6604 | |
6605 | if (D.getDeclSpec().isInlineSpecified()) { |
6606 | if (!getLangOpts().CPlusPlus) { |
6607 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) |
6608 | << 0; |
6609 | } else if (CurContext->isFunctionOrMethod()) { |
6610 | // 'inline' is not allowed on block scope variable declaration. |
6611 | Diag(D.getDeclSpec().getInlineSpecLoc(), |
6612 | diag::err_inline_declaration_block_scope) << Name |
6613 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); |
6614 | } else { |
6615 | Diag(D.getDeclSpec().getInlineSpecLoc(), |
6616 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable |
6617 | : diag::ext_inline_variable); |
6618 | NewVD->setInlineSpecified(); |
6619 | } |
6620 | } |
6621 | |
6622 | // Set the lexical context. If the declarator has a C++ scope specifier, the |
6623 | // lexical context will be different from the semantic context. |
6624 | NewVD->setLexicalDeclContext(CurContext); |
6625 | if (NewTemplate) |
6626 | NewTemplate->setLexicalDeclContext(CurContext); |
6627 | |
6628 | if (IsLocalExternDecl) { |
6629 | if (D.isDecompositionDeclarator()) |
6630 | for (auto *B : Bindings) |
6631 | B->setLocalExternDecl(); |
6632 | else |
6633 | NewVD->setLocalExternDecl(); |
6634 | } |
6635 | |
6636 | bool EmitTLSUnsupportedError = false; |
6637 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { |
6638 | // C++11 [dcl.stc]p4: |
6639 | // When thread_local is applied to a variable of block scope the |
6640 | // storage-class-specifier static is implied if it does not appear |
6641 | // explicitly. |
6642 | // Core issue: 'static' is not implied if the variable is declared |
6643 | // 'extern'. |
6644 | if (NewVD->hasLocalStorage() && |
6645 | (SCSpec != DeclSpec::SCS_unspecified || |
6646 | TSCS != DeclSpec::TSCS_thread_local || |
6647 | !DC->isFunctionOrMethod())) |
6648 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), |
6649 | diag::err_thread_non_global) |
6650 | << DeclSpec::getSpecifierName(TSCS); |
6651 | else if (!Context.getTargetInfo().isTLSSupported()) { |
6652 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { |
6653 | // Postpone error emission until we've collected attributes required to |
6654 | // figure out whether it's a host or device variable and whether the |
6655 | // error should be ignored. |
6656 | EmitTLSUnsupportedError = true; |
6657 | // We still need to mark the variable as TLS so it shows up in AST with |
6658 | // proper storage class for other tools to use even if we're not going |
6659 | // to emit any code for it. |
6660 | NewVD->setTSCSpec(TSCS); |
6661 | } else |
6662 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), |
6663 | diag::err_thread_unsupported); |
6664 | } else |
6665 | NewVD->setTSCSpec(TSCS); |
6666 | } |
6667 | |
6668 | // C99 6.7.4p3 |
6669 | // An inline definition of a function with external linkage shall |
6670 | // not contain a definition of a modifiable object with static or |
6671 | // thread storage duration... |
6672 | // We only apply this when the function is required to be defined |
6673 | // elsewhere, i.e. when the function is not 'extern inline'. Note |
6674 | // that a local variable with thread storage duration still has to |
6675 | // be marked 'static'. Also note that it's possible to get these |
6676 | // semantics in C++ using __attribute__((gnu_inline)). |
6677 | if (SC == SC_Static && S->getFnParent() != nullptr && |
6678 | !NewVD->getType().isConstQualified()) { |
6679 | FunctionDecl *CurFD = getCurFunctionDecl(); |
6680 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { |
6681 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), |
6682 | diag::warn_static_local_in_extern_inline); |
6683 | MaybeSuggestAddingStaticToDecl(CurFD); |
6684 | } |
6685 | } |
6686 | |
6687 | if (D.getDeclSpec().isModulePrivateSpecified()) { |
6688 | if (IsVariableTemplateSpecialization) |
6689 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) |
6690 | << (IsPartialSpecialization ? 1 : 0) |
6691 | << FixItHint::CreateRemoval( |
6692 | D.getDeclSpec().getModulePrivateSpecLoc()); |
6693 | else if (IsMemberSpecialization) |
6694 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) |
6695 | << 2 |
6696 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); |
6697 | else if (NewVD->hasLocalStorage()) |
6698 | Diag(NewVD->getLocation(), diag::err_module_private_local) |
6699 | << 0 << NewVD->getDeclName() |
6700 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) |
6701 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); |
6702 | else { |
6703 | NewVD->setModulePrivate(); |
6704 | if (NewTemplate) |
6705 | NewTemplate->setModulePrivate(); |
6706 | for (auto *B : Bindings) |
6707 | B->setModulePrivate(); |
6708 | } |
6709 | } |
6710 | |
6711 | // Handle attributes prior to checking for duplicates in MergeVarDecl |
6712 | ProcessDeclAttributes(S, NewVD, D); |
6713 | |
6714 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { |
6715 | if (EmitTLSUnsupportedError && |
6716 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || |
6717 | (getLangOpts().OpenMPIsDevice && |
6718 | NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) |
6719 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), |
6720 | diag::err_thread_unsupported); |
6721 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static |
6722 | // storage [duration]." |
6723 | if (SC == SC_None && S->getFnParent() != nullptr && |
6724 | (NewVD->hasAttr<CUDASharedAttr>() || |
6725 | NewVD->hasAttr<CUDAConstantAttr>())) { |
6726 | NewVD->setStorageClass(SC_Static); |
6727 | } |
6728 | } |
6729 | |
6730 | // Ensure that dllimport globals without explicit storage class are treated as |
6731 | // extern. The storage class is set above using parsed attributes. Now we can |
6732 | // check the VarDecl itself. |
6733 | assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6735, __PRETTY_FUNCTION__)) |
6734 | NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6735, __PRETTY_FUNCTION__)) |
6735 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 6735, __PRETTY_FUNCTION__)); |
6736 | |
6737 | // In auto-retain/release, infer strong retension for variables of |
6738 | // retainable type. |
6739 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) |
6740 | NewVD->setInvalidDecl(); |
6741 | |
6742 | // Handle GNU asm-label extension (encoded as an attribute). |
6743 | if (Expr *E = (Expr*)D.getAsmLabel()) { |
6744 | // The parser guarantees this is a string. |
6745 | StringLiteral *SE = cast<StringLiteral>(E); |
6746 | StringRef Label = SE->getString(); |
6747 | if (S->getFnParent() != nullptr) { |
6748 | switch (SC) { |
6749 | case SC_None: |
6750 | case SC_Auto: |
6751 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; |
6752 | break; |
6753 | case SC_Register: |
6754 | // Local Named register |
6755 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && |
6756 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) |
6757 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; |
6758 | break; |
6759 | case SC_Static: |
6760 | case SC_Extern: |
6761 | case SC_PrivateExtern: |
6762 | break; |
6763 | } |
6764 | } else if (SC == SC_Register) { |
6765 | // Global Named register |
6766 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { |
6767 | const auto &TI = Context.getTargetInfo(); |
6768 | bool HasSizeMismatch; |
6769 | |
6770 | if (!TI.isValidGCCRegisterName(Label)) |
6771 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; |
6772 | else if (!TI.validateGlobalRegisterVariable(Label, |
6773 | Context.getTypeSize(R), |
6774 | HasSizeMismatch)) |
6775 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; |
6776 | else if (HasSizeMismatch) |
6777 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; |
6778 | } |
6779 | |
6780 | if (!R->isIntegralType(Context) && !R->isPointerType()) { |
6781 | Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); |
6782 | NewVD->setInvalidDecl(true); |
6783 | } |
6784 | } |
6785 | |
6786 | NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), |
6787 | Context, Label, 0)); |
6788 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { |
6789 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = |
6790 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); |
6791 | if (I != ExtnameUndeclaredIdentifiers.end()) { |
6792 | if (isDeclExternC(NewVD)) { |
6793 | NewVD->addAttr(I->second); |
6794 | ExtnameUndeclaredIdentifiers.erase(I); |
6795 | } else |
6796 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) |
6797 | << /*Variable*/1 << NewVD; |
6798 | } |
6799 | } |
6800 | |
6801 | // Find the shadowed declaration before filtering for scope. |
6802 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() |
6803 | ? getShadowedDeclaration(NewVD, Previous) |
6804 | : nullptr; |
6805 | |
6806 | // Don't consider existing declarations that are in a different |
6807 | // scope and are out-of-semantic-context declarations (if the new |
6808 | // declaration has linkage). |
6809 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), |
6810 | D.getCXXScopeSpec().isNotEmpty() || |
6811 | IsMemberSpecialization || |
6812 | IsVariableTemplateSpecialization); |
6813 | |
6814 | // Check whether the previous declaration is in the same block scope. This |
6815 | // affects whether we merge types with it, per C++11 [dcl.array]p3. |
6816 | if (getLangOpts().CPlusPlus && |
6817 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) |
6818 | NewVD->setPreviousDeclInSameBlockScope( |
6819 | Previous.isSingleResult() && !Previous.isShadowed() && |
6820 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); |
6821 | |
6822 | if (!getLangOpts().CPlusPlus) { |
6823 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); |
6824 | } else { |
6825 | // If this is an explicit specialization of a static data member, check it. |
6826 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && |
6827 | CheckMemberSpecialization(NewVD, Previous)) |
6828 | NewVD->setInvalidDecl(); |
6829 | |
6830 | // Merge the decl with the existing one if appropriate. |
6831 | if (!Previous.empty()) { |
6832 | if (Previous.isSingleResult() && |
6833 | isa<FieldDecl>(Previous.getFoundDecl()) && |
6834 | D.getCXXScopeSpec().isSet()) { |
6835 | // The user tried to define a non-static data member |
6836 | // out-of-line (C++ [dcl.meaning]p1). |
6837 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) |
6838 | << D.getCXXScopeSpec().getRange(); |
6839 | Previous.clear(); |
6840 | NewVD->setInvalidDecl(); |
6841 | } |
6842 | } else if (D.getCXXScopeSpec().isSet()) { |
6843 | // No previous declaration in the qualifying scope. |
6844 | Diag(D.getIdentifierLoc(), diag::err_no_member) |
6845 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) |
6846 | << D.getCXXScopeSpec().getRange(); |
6847 | NewVD->setInvalidDecl(); |
6848 | } |
6849 | |
6850 | if (!IsVariableTemplateSpecialization) |
6851 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); |
6852 | |
6853 | if (NewTemplate) { |
6854 | VarTemplateDecl *PrevVarTemplate = |
6855 | NewVD->getPreviousDecl() |
6856 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() |
6857 | : nullptr; |
6858 | |
6859 | // Check the template parameter list of this declaration, possibly |
6860 | // merging in the template parameter list from the previous variable |
6861 | // template declaration. |
6862 | if (CheckTemplateParameterList( |
6863 | TemplateParams, |
6864 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() |
6865 | : nullptr, |
6866 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && |
6867 | DC->isDependentContext()) |
6868 | ? TPC_ClassTemplateMember |
6869 | : TPC_VarTemplate)) |
6870 | NewVD->setInvalidDecl(); |
6871 | |
6872 | // If we are providing an explicit specialization of a static variable |
6873 | // template, make a note of that. |
6874 | if (PrevVarTemplate && |
6875 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) |
6876 | PrevVarTemplate->setMemberSpecialization(); |
6877 | } |
6878 | } |
6879 | |
6880 | // Diagnose shadowed variables iff this isn't a redeclaration. |
6881 | if (ShadowedDecl && !D.isRedeclaration()) |
6882 | CheckShadow(NewVD, ShadowedDecl, Previous); |
6883 | |
6884 | ProcessPragmaWeak(S, NewVD); |
6885 | |
6886 | // If this is the first declaration of an extern C variable, update |
6887 | // the map of such variables. |
6888 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && |
6889 | isIncompleteDeclExternC(*this, NewVD)) |
6890 | RegisterLocallyScopedExternCDecl(NewVD, S); |
6891 | |
6892 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { |
6893 | Decl *ManglingContextDecl; |
6894 | if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( |
6895 | NewVD->getDeclContext(), ManglingContextDecl)) { |
6896 | Context.setManglingNumber( |
6897 | NewVD, MCtx->getManglingNumber( |
6898 | NewVD, getMSManglingNumber(getLangOpts(), S))); |
6899 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); |
6900 | } |
6901 | } |
6902 | |
6903 | // Special handling of variable named 'main'. |
6904 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && |
6905 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && |
6906 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { |
6907 | |
6908 | // C++ [basic.start.main]p3 |
6909 | // A program that declares a variable main at global scope is ill-formed. |
6910 | if (getLangOpts().CPlusPlus) |
6911 | Diag(D.getBeginLoc(), diag::err_main_global_variable); |
6912 | |
6913 | // In C, and external-linkage variable named main results in undefined |
6914 | // behavior. |
6915 | else if (NewVD->hasExternalFormalLinkage()) |
6916 | Diag(D.getBeginLoc(), diag::warn_main_redefined); |
6917 | } |
6918 | |
6919 | if (D.isRedeclaration() && !Previous.empty()) { |
6920 | NamedDecl *Prev = Previous.getRepresentativeDecl(); |
6921 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, |
6922 | D.isFunctionDefinition()); |
6923 | } |
6924 | |
6925 | if (NewTemplate) { |
6926 | if (NewVD->isInvalidDecl()) |
6927 | NewTemplate->setInvalidDecl(); |
6928 | ActOnDocumentableDecl(NewTemplate); |
6929 | return NewTemplate; |
6930 | } |
6931 | |
6932 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) |
6933 | CompleteMemberSpecialization(NewVD, Previous); |
6934 | |
6935 | return NewVD; |
6936 | } |
6937 | |
6938 | /// Enum describing the %select options in diag::warn_decl_shadow. |
6939 | enum ShadowedDeclKind { |
6940 | SDK_Local, |
6941 | SDK_Global, |
6942 | SDK_StaticMember, |
6943 | SDK_Field, |
6944 | SDK_Typedef, |
6945 | SDK_Using |
6946 | }; |
6947 | |
6948 | /// Determine what kind of declaration we're shadowing. |
6949 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, |
6950 | const DeclContext *OldDC) { |
6951 | if (isa<TypeAliasDecl>(ShadowedDecl)) |
6952 | return SDK_Using; |
6953 | else if (isa<TypedefDecl>(ShadowedDecl)) |
6954 | return SDK_Typedef; |
6955 | else if (isa<RecordDecl>(OldDC)) |
6956 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; |
6957 | |
6958 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; |
6959 | } |
6960 | |
6961 | /// Return the location of the capture if the given lambda captures the given |
6962 | /// variable \p VD, or an invalid source location otherwise. |
6963 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, |
6964 | const VarDecl *VD) { |
6965 | for (const Capture &Capture : LSI->Captures) { |
6966 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) |
6967 | return Capture.getLocation(); |
6968 | } |
6969 | return SourceLocation(); |
6970 | } |
6971 | |
6972 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, |
6973 | const LookupResult &R) { |
6974 | // Only diagnose if we're shadowing an unambiguous field or variable. |
6975 | if (R.getResultKind() != LookupResult::Found) |
6976 | return false; |
6977 | |
6978 | // Return false if warning is ignored. |
6979 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); |
6980 | } |
6981 | |
6982 | /// Return the declaration shadowed by the given variable \p D, or null |
6983 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. |
6984 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, |
6985 | const LookupResult &R) { |
6986 | if (!shouldWarnIfShadowedDecl(Diags, R)) |
6987 | return nullptr; |
6988 | |
6989 | // Don't diagnose declarations at file scope. |
6990 | if (D->hasGlobalStorage()) |
6991 | return nullptr; |
6992 | |
6993 | NamedDecl *ShadowedDecl = R.getFoundDecl(); |
6994 | return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) |
6995 | ? ShadowedDecl |
6996 | : nullptr; |
6997 | } |
6998 | |
6999 | /// Return the declaration shadowed by the given typedef \p D, or null |
7000 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. |
7001 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, |
7002 | const LookupResult &R) { |
7003 | // Don't warn if typedef declaration is part of a class |
7004 | if (D->getDeclContext()->isRecord()) |
7005 | return nullptr; |
7006 | |
7007 | if (!shouldWarnIfShadowedDecl(Diags, R)) |
7008 | return nullptr; |
7009 | |
7010 | NamedDecl *ShadowedDecl = R.getFoundDecl(); |
7011 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; |
7012 | } |
7013 | |
7014 | /// Diagnose variable or built-in function shadowing. Implements |
7015 | /// -Wshadow. |
7016 | /// |
7017 | /// This method is called whenever a VarDecl is added to a "useful" |
7018 | /// scope. |
7019 | /// |
7020 | /// \param ShadowedDecl the declaration that is shadowed by the given variable |
7021 | /// \param R the lookup of the name |
7022 | /// |
7023 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, |
7024 | const LookupResult &R) { |
7025 | DeclContext *NewDC = D->getDeclContext(); |
7026 | |
7027 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { |
7028 | // Fields are not shadowed by variables in C++ static methods. |
7029 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) |
7030 | if (MD->isStatic()) |
7031 | return; |
7032 | |
7033 | // Fields shadowed by constructor parameters are a special case. Usually |
7034 | // the constructor initializes the field with the parameter. |
7035 | if (isa<CXXConstructorDecl>(NewDC)) |
7036 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { |
7037 | // Remember that this was shadowed so we can either warn about its |
7038 | // modification or its existence depending on warning settings. |
7039 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); |
7040 | return; |
7041 | } |
7042 | } |
7043 | |
7044 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) |
7045 | if (shadowedVar->isExternC()) { |
7046 | // For shadowing external vars, make sure that we point to the global |
7047 | // declaration, not a locally scoped extern declaration. |
7048 | for (auto I : shadowedVar->redecls()) |
7049 | if (I->isFileVarDecl()) { |
7050 | ShadowedDecl = I; |
7051 | break; |
7052 | } |
7053 | } |
7054 | |
7055 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); |
7056 | |
7057 | unsigned WarningDiag = diag::warn_decl_shadow; |
7058 | SourceLocation CaptureLoc; |
7059 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && |
7060 | isa<CXXMethodDecl>(NewDC)) { |
7061 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { |
7062 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { |
7063 | if (RD->getLambdaCaptureDefault() == LCD_None) { |
7064 | // Try to avoid warnings for lambdas with an explicit capture list. |
7065 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); |
7066 | // Warn only when the lambda captures the shadowed decl explicitly. |
7067 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); |
7068 | if (CaptureLoc.isInvalid()) |
7069 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; |
7070 | } else { |
7071 | // Remember that this was shadowed so we can avoid the warning if the |
7072 | // shadowed decl isn't captured and the warning settings allow it. |
7073 | cast<LambdaScopeInfo>(getCurFunction()) |
7074 | ->ShadowingDecls.push_back( |
7075 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); |
7076 | return; |
7077 | } |
7078 | } |
7079 | |
7080 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { |
7081 | // A variable can't shadow a local variable in an enclosing scope, if |
7082 | // they are separated by a non-capturing declaration context. |
7083 | for (DeclContext *ParentDC = NewDC; |
7084 | ParentDC && !ParentDC->Equals(OldDC); |
7085 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { |
7086 | // Only block literals, captured statements, and lambda expressions |
7087 | // can capture; other scopes don't. |
7088 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && |
7089 | !isLambdaCallOperator(ParentDC)) { |
7090 | return; |
7091 | } |
7092 | } |
7093 | } |
7094 | } |
7095 | } |
7096 | |
7097 | // Only warn about certain kinds of shadowing for class members. |
7098 | if (NewDC && NewDC->isRecord()) { |
7099 | // In particular, don't warn about shadowing non-class members. |
7100 | if (!OldDC->isRecord()) |
7101 | return; |
7102 | |
7103 | // TODO: should we warn about static data members shadowing |
7104 | // static data members from base classes? |
7105 | |
7106 | // TODO: don't diagnose for inaccessible shadowed members. |
7107 | // This is hard to do perfectly because we might friend the |
7108 | // shadowing context, but that's just a false negative. |
7109 | } |
7110 | |
7111 | |
7112 | DeclarationName Name = R.getLookupName(); |
7113 | |
7114 | // Emit warning and note. |
7115 | if (getSourceManager().isInSystemMacro(R.getNameLoc())) |
7116 | return; |
7117 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); |
7118 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; |
7119 | if (!CaptureLoc.isInvalid()) |
7120 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) |
7121 | << Name << /*explicitly*/ 1; |
7122 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); |
7123 | } |
7124 | |
7125 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD |
7126 | /// when these variables are captured by the lambda. |
7127 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { |
7128 | for (const auto &Shadow : LSI->ShadowingDecls) { |
7129 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; |
7130 | // Try to avoid the warning when the shadowed decl isn't captured. |
7131 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); |
7132 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); |
7133 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() |
7134 | ? diag::warn_decl_shadow_uncaptured_local |
7135 | : diag::warn_decl_shadow) |
7136 | << Shadow.VD->getDeclName() |
7137 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; |
7138 | if (!CaptureLoc.isInvalid()) |
7139 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) |
7140 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; |
7141 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); |
7142 | } |
7143 | } |
7144 | |
7145 | /// Check -Wshadow without the advantage of a previous lookup. |
7146 | void Sema::CheckShadow(Scope *S, VarDecl *D) { |
7147 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) |
7148 | return; |
7149 | |
7150 | LookupResult R(*this, D->getDeclName(), D->getLocation(), |
7151 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); |
7152 | LookupName(R, S); |
7153 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) |
7154 | CheckShadow(D, ShadowedDecl, R); |
7155 | } |
7156 | |
7157 | /// Check if 'E', which is an expression that is about to be modified, refers |
7158 | /// to a constructor parameter that shadows a field. |
7159 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { |
7160 | // Quickly ignore expressions that can't be shadowing ctor parameters. |
7161 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) |
7162 | return; |
7163 | E = E->IgnoreParenImpCasts(); |
7164 | auto *DRE = dyn_cast<DeclRefExpr>(E); |
7165 | if (!DRE) |
7166 | return; |
7167 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); |
7168 | auto I = ShadowingDecls.find(D); |
7169 | if (I == ShadowingDecls.end()) |
7170 | return; |
7171 | const NamedDecl *ShadowedDecl = I->second; |
7172 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); |
7173 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; |
7174 | Diag(D->getLocation(), diag::note_var_declared_here) << D; |
7175 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); |
7176 | |
7177 | // Avoid issuing multiple warnings about the same decl. |
7178 | ShadowingDecls.erase(I); |
7179 | } |
7180 | |
7181 | /// Check for conflict between this global or extern "C" declaration and |
7182 | /// previous global or extern "C" declarations. This is only used in C++. |
7183 | template<typename T> |
7184 | static bool checkGlobalOrExternCConflict( |
7185 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { |
7186 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 7186, __PRETTY_FUNCTION__)); |
7187 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); |
7188 | |
7189 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { |
7190 | // The common case: this global doesn't conflict with any extern "C" |
7191 | // declaration. |
7192 | return false; |
7193 | } |
7194 | |
7195 | if (Prev) { |
7196 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { |
7197 | // Both the old and new declarations have C language linkage. This is a |
7198 | // redeclaration. |
7199 | Previous.clear(); |
7200 | Previous.addDecl(Prev); |
7201 | return true; |
7202 | } |
7203 | |
7204 | // This is a global, non-extern "C" declaration, and there is a previous |
7205 | // non-global extern "C" declaration. Diagnose if this is a variable |
7206 | // declaration. |
7207 | if (!isa<VarDecl>(ND)) |
7208 | return false; |
7209 | } else { |
7210 | // The declaration is extern "C". Check for any declaration in the |
7211 | // translation unit which might conflict. |
7212 | if (IsGlobal) { |
7213 | // We have already performed the lookup into the translation unit. |
7214 | IsGlobal = false; |
7215 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
7216 | I != E; ++I) { |
7217 | if (isa<VarDecl>(*I)) { |
7218 | Prev = *I; |
7219 | break; |
7220 | } |
7221 | } |
7222 | } else { |
7223 | DeclContext::lookup_result R = |
7224 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); |
7225 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); |
7226 | I != E; ++I) { |
7227 | if (isa<VarDecl>(*I)) { |
7228 | Prev = *I; |
7229 | break; |
7230 | } |
7231 | // FIXME: If we have any other entity with this name in global scope, |
7232 | // the declaration is ill-formed, but that is a defect: it breaks the |
7233 | // 'stat' hack, for instance. Only variables can have mangled name |
7234 | // clashes with extern "C" declarations, so only they deserve a |
7235 | // diagnostic. |
7236 | } |
7237 | } |
7238 | |
7239 | if (!Prev) |
7240 | return false; |
7241 | } |
7242 | |
7243 | // Use the first declaration's location to ensure we point at something which |
7244 | // is lexically inside an extern "C" linkage-spec. |
7245 | assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose" ) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 7245, __PRETTY_FUNCTION__)); |
7246 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) |
7247 | Prev = FD->getFirstDecl(); |
7248 | else |
7249 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); |
7250 | |
7251 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) |
7252 | << IsGlobal << ND; |
7253 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) |
7254 | << IsGlobal; |
7255 | return false; |
7256 | } |
7257 | |
7258 | /// Apply special rules for handling extern "C" declarations. Returns \c true |
7259 | /// if we have found that this is a redeclaration of some prior entity. |
7260 | /// |
7261 | /// Per C++ [dcl.link]p6: |
7262 | /// Two declarations [for a function or variable] with C language linkage |
7263 | /// with the same name that appear in different scopes refer to the same |
7264 | /// [entity]. An entity with C language linkage shall not be declared with |
7265 | /// the same name as an entity in global scope. |
7266 | template<typename T> |
7267 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, |
7268 | LookupResult &Previous) { |
7269 | if (!S.getLangOpts().CPlusPlus) { |
7270 | // In C, when declaring a global variable, look for a corresponding 'extern' |
7271 | // variable declared in function scope. We don't need this in C++, because |
7272 | // we find local extern decls in the surrounding file-scope DeclContext. |
7273 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { |
7274 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { |
7275 | Previous.clear(); |
7276 | Previous.addDecl(Prev); |
7277 | return true; |
7278 | } |
7279 | } |
7280 | return false; |
7281 | } |
7282 | |
7283 | // A declaration in the translation unit can conflict with an extern "C" |
7284 | // declaration. |
7285 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) |
7286 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); |
7287 | |
7288 | // An extern "C" declaration can conflict with a declaration in the |
7289 | // translation unit or can be a redeclaration of an extern "C" declaration |
7290 | // in another scope. |
7291 | if (isIncompleteDeclExternC(S,ND)) |
7292 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); |
7293 | |
7294 | // Neither global nor extern "C": nothing to do. |
7295 | return false; |
7296 | } |
7297 | |
7298 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { |
7299 | // If the decl is already known invalid, don't check it. |
7300 | if (NewVD->isInvalidDecl()) |
7301 | return; |
7302 | |
7303 | QualType T = NewVD->getType(); |
7304 | |
7305 | // Defer checking an 'auto' type until its initializer is attached. |
7306 | if (T->isUndeducedType()) |
7307 | return; |
7308 | |
7309 | if (NewVD->hasAttrs()) |
7310 | CheckAlignasUnderalignment(NewVD); |
7311 | |
7312 | if (T->isObjCObjectType()) { |
7313 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) |
7314 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); |
7315 | T = Context.getObjCObjectPointerType(T); |
7316 | NewVD->setType(T); |
7317 | } |
7318 | |
7319 | // Emit an error if an address space was applied to decl with local storage. |
7320 | // This includes arrays of objects with address space qualifiers, but not |
7321 | // automatic variables that point to other address spaces. |
7322 | // ISO/IEC TR 18037 S5.1.2 |
7323 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && |
7324 | T.getAddressSpace() != LangAS::Default) { |
7325 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; |
7326 | NewVD->setInvalidDecl(); |
7327 | return; |
7328 | } |
7329 | |
7330 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program |
7331 | // scope. |
7332 | if (getLangOpts().OpenCLVersion == 120 && |
7333 | !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && |
7334 | NewVD->isStaticLocal()) { |
7335 | Diag(NewVD->getLocation(), diag::err_static_function_scope); |
7336 | NewVD->setInvalidDecl(); |
7337 | return; |
7338 | } |
7339 | |
7340 | if (getLangOpts().OpenCL) { |
7341 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. |
7342 | if (NewVD->hasAttr<BlocksAttr>()) { |
7343 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); |
7344 | return; |
7345 | } |
7346 | |
7347 | if (T->isBlockPointerType()) { |
7348 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and |
7349 | // can't use 'extern' storage class. |
7350 | if (!T.isConstQualified()) { |
7351 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) |
7352 | << 0 /*const*/; |
7353 | NewVD->setInvalidDecl(); |
7354 | return; |
7355 | } |
7356 | if (NewVD->hasExternalStorage()) { |
7357 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); |
7358 | NewVD->setInvalidDecl(); |
7359 | return; |
7360 | } |
7361 | } |
7362 | // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the |
7363 | // __constant address space. |
7364 | // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static |
7365 | // variables inside a function can also be declared in the global |
7366 | // address space. |
7367 | // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local |
7368 | // address space additionally. |
7369 | // FIXME: Add local AS for OpenCL C++. |
7370 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || |
7371 | NewVD->hasExternalStorage()) { |
7372 | if (!T->isSamplerT() && |
7373 | !(T.getAddressSpace() == LangAS::opencl_constant || |
7374 | (T.getAddressSpace() == LangAS::opencl_global && |
7375 | (getLangOpts().OpenCLVersion == 200 || |
7376 | getLangOpts().OpenCLCPlusPlus)))) { |
7377 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; |
7378 | if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) |
7379 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) |
7380 | << Scope << "global or constant"; |
7381 | else |
7382 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) |
7383 | << Scope << "constant"; |
7384 | NewVD->setInvalidDecl(); |
7385 | return; |
7386 | } |
7387 | } else { |
7388 | if (T.getAddressSpace() == LangAS::opencl_global) { |
7389 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) |
7390 | << 1 /*is any function*/ << "global"; |
7391 | NewVD->setInvalidDecl(); |
7392 | return; |
7393 | } |
7394 | if (T.getAddressSpace() == LangAS::opencl_constant || |
7395 | T.getAddressSpace() == LangAS::opencl_local) { |
7396 | FunctionDecl *FD = getCurFunctionDecl(); |
7397 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables |
7398 | // in functions. |
7399 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { |
7400 | if (T.getAddressSpace() == LangAS::opencl_constant) |
7401 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) |
7402 | << 0 /*non-kernel only*/ << "constant"; |
7403 | else |
7404 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) |
7405 | << 0 /*non-kernel only*/ << "local"; |
7406 | NewVD->setInvalidDecl(); |
7407 | return; |
7408 | } |
7409 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be |
7410 | // in the outermost scope of a kernel function. |
7411 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { |
7412 | if (!getCurScope()->isFunctionScope()) { |
7413 | if (T.getAddressSpace() == LangAS::opencl_constant) |
7414 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) |
7415 | << "constant"; |
7416 | else |
7417 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) |
7418 | << "local"; |
7419 | NewVD->setInvalidDecl(); |
7420 | return; |
7421 | } |
7422 | } |
7423 | } else if (T.getAddressSpace() != LangAS::opencl_private) { |
7424 | // Do not allow other address spaces on automatic variable. |
7425 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; |
7426 | NewVD->setInvalidDecl(); |
7427 | return; |
7428 | } |
7429 | } |
7430 | } |
7431 | |
7432 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() |
7433 | && !NewVD->hasAttr<BlocksAttr>()) { |
7434 | if (getLangOpts().getGC() != LangOptions::NonGC) |
7435 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); |
7436 | else { |
7437 | assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> ( 0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 7437, __PRETTY_FUNCTION__)); |
7438 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); |
7439 | } |
7440 | } |
7441 | |
7442 | bool isVM = T->isVariablyModifiedType(); |
7443 | if (isVM || NewVD->hasAttr<CleanupAttr>() || |
7444 | NewVD->hasAttr<BlocksAttr>()) |
7445 | setFunctionHasBranchProtectedScope(); |
7446 | |
7447 | if ((isVM && NewVD->hasLinkage()) || |
7448 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { |
7449 | bool SizeIsNegative; |
7450 | llvm::APSInt Oversized; |
7451 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( |
7452 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); |
7453 | QualType FixedT; |
7454 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) |
7455 | FixedT = FixedTInfo->getType(); |
7456 | else if (FixedTInfo) { |
7457 | // Type and type-as-written are canonically different. We need to fix up |
7458 | // both types separately. |
7459 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, |
7460 | Oversized); |
7461 | } |
7462 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { |
7463 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); |
7464 | // FIXME: This won't give the correct result for |
7465 | // int a[10][n]; |
7466 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); |
7467 | |
7468 | if (NewVD->isFileVarDecl()) |
7469 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) |
7470 | << SizeRange; |
7471 | else if (NewVD->isStaticLocal()) |
7472 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) |
7473 | << SizeRange; |
7474 | else |
7475 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) |
7476 | << SizeRange; |
7477 | NewVD->setInvalidDecl(); |
7478 | return; |
7479 | } |
7480 | |
7481 | if (!FixedTInfo) { |
7482 | if (NewVD->isFileVarDecl()) |
7483 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); |
7484 | else |
7485 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); |
7486 | NewVD->setInvalidDecl(); |
7487 | return; |
7488 | } |
7489 | |
7490 | Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); |
7491 | NewVD->setType(FixedT); |
7492 | NewVD->setTypeSourceInfo(FixedTInfo); |
7493 | } |
7494 | |
7495 | if (T->isVoidType()) { |
7496 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names |
7497 | // of objects and functions. |
7498 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { |
7499 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) |
7500 | << T; |
7501 | NewVD->setInvalidDecl(); |
7502 | return; |
7503 | } |
7504 | } |
7505 | |
7506 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { |
7507 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); |
7508 | NewVD->setInvalidDecl(); |
7509 | return; |
7510 | } |
7511 | |
7512 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { |
7513 | Diag(NewVD->getLocation(), diag::err_block_on_vm); |
7514 | NewVD->setInvalidDecl(); |
7515 | return; |
7516 | } |
7517 | |
7518 | if (NewVD->isConstexpr() && !T->isDependentType() && |
7519 | RequireLiteralType(NewVD->getLocation(), T, |
7520 | diag::err_constexpr_var_non_literal)) { |
7521 | NewVD->setInvalidDecl(); |
7522 | return; |
7523 | } |
7524 | } |
7525 | |
7526 | /// Perform semantic checking on a newly-created variable |
7527 | /// declaration. |
7528 | /// |
7529 | /// This routine performs all of the type-checking required for a |
7530 | /// variable declaration once it has been built. It is used both to |
7531 | /// check variables after they have been parsed and their declarators |
7532 | /// have been translated into a declaration, and to check variables |
7533 | /// that have been instantiated from a template. |
7534 | /// |
7535 | /// Sets NewVD->isInvalidDecl() if an error was encountered. |
7536 | /// |
7537 | /// Returns true if the variable declaration is a redeclaration. |
7538 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { |
7539 | CheckVariableDeclarationType(NewVD); |
7540 | |
7541 | // If the decl is already known invalid, don't check it. |
7542 | if (NewVD->isInvalidDecl()) |
7543 | return false; |
7544 | |
7545 | // If we did not find anything by this name, look for a non-visible |
7546 | // extern "C" declaration with the same name. |
7547 | if (Previous.empty() && |
7548 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) |
7549 | Previous.setShadowed(); |
7550 | |
7551 | if (!Previous.empty()) { |
7552 | MergeVarDecl(NewVD, Previous); |
7553 | return true; |
7554 | } |
7555 | return false; |
7556 | } |
7557 | |
7558 | namespace { |
7559 | struct FindOverriddenMethod { |
7560 | Sema *S; |
7561 | CXXMethodDecl *Method; |
7562 | |
7563 | /// Member lookup function that determines whether a given C++ |
7564 | /// method overrides a method in a base class, to be used with |
7565 | /// CXXRecordDecl::lookupInBases(). |
7566 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { |
7567 | RecordDecl *BaseRecord = |
7568 | Specifier->getType()->getAs<RecordType>()->getDecl(); |
7569 | |
7570 | DeclarationName Name = Method->getDeclName(); |
7571 | |
7572 | // FIXME: Do we care about other names here too? |
7573 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { |
7574 | // We really want to find the base class destructor here. |
7575 | QualType T = S->Context.getTypeDeclType(BaseRecord); |
7576 | CanQualType CT = S->Context.getCanonicalType(T); |
7577 | |
7578 | Name = S->Context.DeclarationNames.getCXXDestructorName(CT); |
7579 | } |
7580 | |
7581 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); |
7582 | Path.Decls = Path.Decls.slice(1)) { |
7583 | NamedDecl *D = Path.Decls.front(); |
7584 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { |
7585 | if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) |
7586 | return true; |
7587 | } |
7588 | } |
7589 | |
7590 | return false; |
7591 | } |
7592 | }; |
7593 | |
7594 | enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; |
7595 | } // end anonymous namespace |
7596 | |
7597 | /// Report an error regarding overriding, along with any relevant |
7598 | /// overridden methods. |
7599 | /// |
7600 | /// \param DiagID the primary error to report. |
7601 | /// \param MD the overriding method. |
7602 | /// \param OEK which overrides to include as notes. |
7603 | static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, |
7604 | OverrideErrorKind OEK = OEK_All) { |
7605 | S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); |
7606 | for (const CXXMethodDecl *O : MD->overridden_methods()) { |
7607 | // This check (& the OEK parameter) could be replaced by a predicate, but |
7608 | // without lambdas that would be overkill. This is still nicer than writing |
7609 | // out the diag loop 3 times. |
7610 | if ((OEK == OEK_All) || |
7611 | (OEK == OEK_NonDeleted && !O->isDeleted()) || |
7612 | (OEK == OEK_Deleted && O->isDeleted())) |
7613 | S.Diag(O->getLocation(), diag::note_overridden_virtual_function); |
7614 | } |
7615 | } |
7616 | |
7617 | /// AddOverriddenMethods - See if a method overrides any in the base classes, |
7618 | /// and if so, check that it's a valid override and remember it. |
7619 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { |
7620 | // Look for methods in base classes that this method might override. |
7621 | CXXBasePaths Paths; |
7622 | FindOverriddenMethod FOM; |
7623 | FOM.Method = MD; |
7624 | FOM.S = this; |
7625 | bool hasDeletedOverridenMethods = false; |
7626 | bool hasNonDeletedOverridenMethods = false; |
7627 | bool AddedAny = false; |
7628 | if (DC->lookupInBases(FOM, Paths)) { |
7629 | for (auto *I : Paths.found_decls()) { |
7630 | if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { |
7631 | MD->addOverriddenMethod(OldMD->getCanonicalDecl()); |
7632 | if (!CheckOverridingFunctionReturnType(MD, OldMD) && |
7633 | !CheckOverridingFunctionAttributes(MD, OldMD) && |
7634 | !CheckOverridingFunctionExceptionSpec(MD, OldMD) && |
7635 | !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { |
7636 | hasDeletedOverridenMethods |= OldMD->isDeleted(); |
7637 | hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); |
7638 | AddedAny = true; |
7639 | } |
7640 | } |
7641 | } |
7642 | } |
7643 | |
7644 | if (hasDeletedOverridenMethods && !MD->isDeleted()) { |
7645 | ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); |
7646 | } |
7647 | if (hasNonDeletedOverridenMethods && MD->isDeleted()) { |
7648 | ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); |
7649 | } |
7650 | |
7651 | return AddedAny; |
7652 | } |
7653 | |
7654 | namespace { |
7655 | // Struct for holding all of the extra arguments needed by |
7656 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. |
7657 | struct ActOnFDArgs { |
7658 | Scope *S; |
7659 | Declarator &D; |
7660 | MultiTemplateParamsArg TemplateParamLists; |
7661 | bool AddToScope; |
7662 | }; |
7663 | } // end anonymous namespace |
7664 | |
7665 | namespace { |
7666 | |
7667 | // Callback to only accept typo corrections that have a non-zero edit distance. |
7668 | // Also only accept corrections that have the same parent decl. |
7669 | class DifferentNameValidatorCCC : public CorrectionCandidateCallback { |
7670 | public: |
7671 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, |
7672 | CXXRecordDecl *Parent) |
7673 | : Context(Context), OriginalFD(TypoFD), |
7674 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} |
7675 | |
7676 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
7677 | if (candidate.getEditDistance() == 0) |
7678 | return false; |
7679 | |
7680 | SmallVector<unsigned, 1> MismatchedParams; |
7681 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), |
7682 | CDeclEnd = candidate.end(); |
7683 | CDecl != CDeclEnd; ++CDecl) { |
7684 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); |
7685 | |
7686 | if (FD && !FD->hasBody() && |
7687 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { |
7688 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { |
7689 | CXXRecordDecl *Parent = MD->getParent(); |
7690 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) |
7691 | return true; |
7692 | } else if (!ExpectedParent) { |
7693 | return true; |
7694 | } |
7695 | } |
7696 | } |
7697 | |
7698 | return false; |
7699 | } |
7700 | |
7701 | private: |
7702 | ASTContext &Context; |
7703 | FunctionDecl *OriginalFD; |
7704 | CXXRecordDecl *ExpectedParent; |
7705 | }; |
7706 | |
7707 | } // end anonymous namespace |
7708 | |
7709 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { |
7710 | TypoCorrectedFunctionDefinitions.insert(F); |
7711 | } |
7712 | |
7713 | /// Generate diagnostics for an invalid function redeclaration. |
7714 | /// |
7715 | /// This routine handles generating the diagnostic messages for an invalid |
7716 | /// function redeclaration, including finding possible similar declarations |
7717 | /// or performing typo correction if there are no previous declarations with |
7718 | /// the same name. |
7719 | /// |
7720 | /// Returns a NamedDecl iff typo correction was performed and substituting in |
7721 | /// the new declaration name does not cause new errors. |
7722 | static NamedDecl *DiagnoseInvalidRedeclaration( |
7723 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, |
7724 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { |
7725 | DeclarationName Name = NewFD->getDeclName(); |
7726 | DeclContext *NewDC = NewFD->getDeclContext(); |
7727 | SmallVector<unsigned, 1> MismatchedParams; |
7728 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; |
7729 | TypoCorrection Correction; |
7730 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); |
7731 | unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend |
7732 | : diag::err_member_decl_does_not_match; |
7733 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), |
7734 | IsLocalFriend ? Sema::LookupLocalFriendName |
7735 | : Sema::LookupOrdinaryName, |
7736 | Sema::ForVisibleRedeclaration); |
7737 | |
7738 | NewFD->setInvalidDecl(); |
7739 | if (IsLocalFriend) |
7740 | SemaRef.LookupName(Prev, S); |
7741 | else |
7742 | SemaRef.LookupQualifiedName(Prev, NewDC); |
7743 | assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 7744, __PRETTY_FUNCTION__)) |
7744 | "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 7744, __PRETTY_FUNCTION__)); |
7745 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); |
7746 | if (!Prev.empty()) { |
7747 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); |
7748 | Func != FuncEnd; ++Func) { |
7749 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); |
7750 | if (FD && |
7751 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { |
7752 | // Add 1 to the index so that 0 can mean the mismatch didn't |
7753 | // involve a parameter |
7754 | unsigned ParamNum = |
7755 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; |
7756 | NearMatches.push_back(std::make_pair(FD, ParamNum)); |
7757 | } |
7758 | } |
7759 | // If the qualified name lookup yielded nothing, try typo correction |
7760 | } else if ((Correction = SemaRef.CorrectTypo( |
7761 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, |
7762 | &ExtraArgs.D.getCXXScopeSpec(), |
7763 | llvm::make_unique<DifferentNameValidatorCCC>( |
7764 | SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), |
7765 | Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { |
7766 | // Set up everything for the call to ActOnFunctionDeclarator |
7767 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), |
7768 | ExtraArgs.D.getIdentifierLoc()); |
7769 | Previous.clear(); |
7770 | Previous.setLookupName(Correction.getCorrection()); |
7771 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), |
7772 | CDeclEnd = Correction.end(); |
7773 | CDecl != CDeclEnd; ++CDecl) { |
7774 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); |
7775 | if (FD && !FD->hasBody() && |
7776 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { |
7777 | Previous.addDecl(FD); |
7778 | } |
7779 | } |
7780 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); |
7781 | |
7782 | NamedDecl *Result; |
7783 | // Retry building the function declaration with the new previous |
7784 | // declarations, and with errors suppressed. |
7785 | { |
7786 | // Trap errors. |
7787 | Sema::SFINAETrap Trap(SemaRef); |
7788 | |
7789 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the |
7790 | // pieces need to verify the typo-corrected C++ declaration and hopefully |
7791 | // eliminate the need for the parameter pack ExtraArgs. |
7792 | Result = SemaRef.ActOnFunctionDeclarator( |
7793 | ExtraArgs.S, ExtraArgs.D, |
7794 | Correction.getCorrectionDecl()->getDeclContext(), |
7795 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, |
7796 | ExtraArgs.AddToScope); |
7797 | |
7798 | if (Trap.hasErrorOccurred()) |
7799 | Result = nullptr; |
7800 | } |
7801 | |
7802 | if (Result) { |
7803 | // Determine which correction we picked. |
7804 | Decl *Canonical = Result->getCanonicalDecl(); |
7805 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); |
7806 | I != E; ++I) |
7807 | if ((*I)->getCanonicalDecl() == Canonical) |
7808 | Correction.setCorrectionDecl(*I); |
7809 | |
7810 | // Let Sema know about the correction. |
7811 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); |
7812 | SemaRef.diagnoseTypo( |
7813 | Correction, |
7814 | SemaRef.PDiag(IsLocalFriend |
7815 | ? diag::err_no_matching_local_friend_suggest |
7816 | : diag::err_member_decl_does_not_match_suggest) |
7817 | << Name << NewDC << IsDefinition); |
7818 | return Result; |
7819 | } |
7820 | |
7821 | // Pretend the typo correction never occurred |
7822 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), |
7823 | ExtraArgs.D.getIdentifierLoc()); |
7824 | ExtraArgs.D.setRedeclaration(wasRedeclaration); |
7825 | Previous.clear(); |
7826 | Previous.setLookupName(Name); |
7827 | } |
7828 | |
7829 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) |
7830 | << Name << NewDC << IsDefinition << NewFD->getLocation(); |
7831 | |
7832 | bool NewFDisConst = false; |
7833 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) |
7834 | NewFDisConst = NewMD->isConst(); |
7835 | |
7836 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator |
7837 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); |
7838 | NearMatch != NearMatchEnd; ++NearMatch) { |
7839 | FunctionDecl *FD = NearMatch->first; |
7840 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); |
7841 | bool FDisConst = MD && MD->isConst(); |
7842 | bool IsMember = MD || !IsLocalFriend; |
7843 | |
7844 | // FIXME: These notes are poorly worded for the local friend case. |
7845 | if (unsigned Idx = NearMatch->second) { |
7846 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); |
7847 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); |
7848 | if (Loc.isInvalid()) Loc = FD->getLocation(); |
7849 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match |
7850 | : diag::note_local_decl_close_param_match) |
7851 | << Idx << FDParam->getType() |
7852 | << NewFD->getParamDecl(Idx - 1)->getType(); |
7853 | } else if (FDisConst != NewFDisConst) { |
7854 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) |
7855 | << NewFDisConst << FD->getSourceRange().getEnd(); |
7856 | } else |
7857 | SemaRef.Diag(FD->getLocation(), |
7858 | IsMember ? diag::note_member_def_close_match |
7859 | : diag::note_local_decl_close_match); |
7860 | } |
7861 | return nullptr; |
7862 | } |
7863 | |
7864 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { |
7865 | switch (D.getDeclSpec().getStorageClassSpec()) { |
7866 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 7866); |
7867 | case DeclSpec::SCS_auto: |
7868 | case DeclSpec::SCS_register: |
7869 | case DeclSpec::SCS_mutable: |
7870 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), |
7871 | diag::err_typecheck_sclass_func); |
7872 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
7873 | D.setInvalidType(); |
7874 | break; |
7875 | case DeclSpec::SCS_unspecified: break; |
7876 | case DeclSpec::SCS_extern: |
7877 | if (D.getDeclSpec().isExternInLinkageSpec()) |
7878 | return SC_None; |
7879 | return SC_Extern; |
7880 | case DeclSpec::SCS_static: { |
7881 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { |
7882 | // C99 6.7.1p5: |
7883 | // The declaration of an identifier for a function that has |
7884 | // block scope shall have no explicit storage-class specifier |
7885 | // other than extern |
7886 | // See also (C++ [dcl.stc]p4). |
7887 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), |
7888 | diag::err_static_block_func); |
7889 | break; |
7890 | } else |
7891 | return SC_Static; |
7892 | } |
7893 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; |
7894 | } |
7895 | |
7896 | // No explicit storage class has already been returned |
7897 | return SC_None; |
7898 | } |
7899 | |
7900 | static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, |
7901 | DeclContext *DC, QualType &R, |
7902 | TypeSourceInfo *TInfo, |
7903 | StorageClass SC, |
7904 | bool &IsVirtualOkay) { |
7905 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); |
7906 | DeclarationName Name = NameInfo.getName(); |
7907 | |
7908 | FunctionDecl *NewFD = nullptr; |
7909 | bool isInline = D.getDeclSpec().isInlineSpecified(); |
7910 | |
7911 | if (!SemaRef.getLangOpts().CPlusPlus) { |
7912 | // Determine whether the function was written with a |
7913 | // prototype. This true when: |
7914 | // - there is a prototype in the declarator, or |
7915 | // - the type R of the function is some kind of typedef or other non- |
7916 | // attributed reference to a type name (which eventually refers to a |
7917 | // function type). |
7918 | bool HasPrototype = |
7919 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || |
7920 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); |
7921 | |
7922 | NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, |
7923 | R, TInfo, SC, isInline, HasPrototype, false); |
7924 | if (D.isInvalidType()) |
7925 | NewFD->setInvalidDecl(); |
7926 | |
7927 | return NewFD; |
7928 | } |
7929 | |
7930 | bool isExplicit = D.getDeclSpec().isExplicitSpecified(); |
7931 | bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); |
7932 | |
7933 | // Check that the return type is not an abstract class type. |
7934 | // For record types, this is done by the AbstractClassUsageDiagnoser once |
7935 | // the class has been completely parsed. |
7936 | if (!DC->isRecord() && |
7937 | SemaRef.RequireNonAbstractType( |
7938 | D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), |
7939 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) |
7940 | D.setInvalidType(); |
7941 | |
7942 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { |
7943 | // This is a C++ constructor declaration. |
7944 | assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 7945, __PRETTY_FUNCTION__)) |
7945 | "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 7945, __PRETTY_FUNCTION__)); |
7946 | |
7947 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); |
7948 | return CXXConstructorDecl::Create( |
7949 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, |
7950 | TInfo, isExplicit, isInline, |
7951 | /*isImplicitlyDeclared=*/false, isConstexpr); |
7952 | |
7953 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { |
7954 | // This is a C++ destructor declaration. |
7955 | if (DC->isRecord()) { |
7956 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); |
7957 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); |
7958 | CXXDestructorDecl *NewDD = |
7959 | CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(), |
7960 | NameInfo, R, TInfo, isInline, |
7961 | /*isImplicitlyDeclared=*/false); |
7962 | |
7963 | // If the destructor needs an implicit exception specification, set it |
7964 | // now. FIXME: It'd be nice to be able to create the right type to start |
7965 | // with, but the type needs to reference the destructor declaration. |
7966 | if (SemaRef.getLangOpts().CPlusPlus11) |
7967 | SemaRef.AdjustDestructorExceptionSpec(NewDD); |
7968 | |
7969 | IsVirtualOkay = true; |
7970 | return NewDD; |
7971 | |
7972 | } else { |
7973 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); |
7974 | D.setInvalidType(); |
7975 | |
7976 | // Create a FunctionDecl to satisfy the function definition parsing |
7977 | // code path. |
7978 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), |
7979 | D.getIdentifierLoc(), Name, R, TInfo, SC, |
7980 | isInline, |
7981 | /*hasPrototype=*/true, isConstexpr); |
7982 | } |
7983 | |
7984 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { |
7985 | if (!DC->isRecord()) { |
7986 | SemaRef.Diag(D.getIdentifierLoc(), |
7987 | diag::err_conv_function_not_member); |
7988 | return nullptr; |
7989 | } |
7990 | |
7991 | SemaRef.CheckConversionDeclarator(D, R, SC); |
7992 | IsVirtualOkay = true; |
7993 | return CXXConversionDecl::Create( |
7994 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, |
7995 | TInfo, isInline, isExplicit, isConstexpr, SourceLocation()); |
7996 | |
7997 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { |
7998 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); |
7999 | |
8000 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), |
8001 | isExplicit, NameInfo, R, TInfo, |
8002 | D.getEndLoc()); |
8003 | } else if (DC->isRecord()) { |
8004 | // If the name of the function is the same as the name of the record, |
8005 | // then this must be an invalid constructor that has a return type. |
8006 | // (The parser checks for a return type and makes the declarator a |
8007 | // constructor if it has no return type). |
8008 | if (Name.getAsIdentifierInfo() && |
8009 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ |
8010 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) |
8011 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) |
8012 | << SourceRange(D.getIdentifierLoc()); |
8013 | return nullptr; |
8014 | } |
8015 | |
8016 | // This is a C++ method declaration. |
8017 | CXXMethodDecl *Ret = CXXMethodDecl::Create( |
8018 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, |
8019 | TInfo, SC, isInline, isConstexpr, SourceLocation()); |
8020 | IsVirtualOkay = !Ret->isStatic(); |
8021 | return Ret; |
8022 | } else { |
8023 | bool isFriend = |
8024 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); |
8025 | if (!isFriend && SemaRef.CurContext->isRecord()) |
8026 | return nullptr; |
8027 | |
8028 | // Determine whether the function was written with a |
8029 | // prototype. This true when: |
8030 | // - we're in C++ (where every function has a prototype), |
8031 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, |
8032 | R, TInfo, SC, isInline, true /*HasPrototype*/, |
8033 | isConstexpr); |
8034 | } |
8035 | } |
8036 | |
8037 | enum OpenCLParamType { |
8038 | ValidKernelParam, |
8039 | PtrPtrKernelParam, |
8040 | PtrKernelParam, |
8041 | InvalidAddrSpacePtrKernelParam, |
8042 | InvalidKernelParam, |
8043 | RecordKernelParam |
8044 | }; |
8045 | |
8046 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { |
8047 | // Size dependent types are just typedefs to normal integer types |
8048 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to |
8049 | // integers other than by their names. |
8050 | StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; |
8051 | |
8052 | // Remove typedefs one by one until we reach a typedef |
8053 | // for a size dependent type. |
8054 | QualType DesugaredTy = Ty; |
8055 | do { |
8056 | ArrayRef<StringRef> Names(SizeTypeNames); |
8057 | auto Match = |
8058 | std::find(Names.begin(), Names.end(), DesugaredTy.getAsString()); |
8059 | if (Names.end() != Match) |
8060 | return true; |
8061 | |
8062 | Ty = DesugaredTy; |
8063 | DesugaredTy = Ty.getSingleStepDesugaredType(C); |
8064 | } while (DesugaredTy != Ty); |
8065 | |
8066 | return false; |
8067 | } |
8068 | |
8069 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { |
8070 | if (PT->isPointerType()) { |
8071 | QualType PointeeType = PT->getPointeeType(); |
8072 | if (PointeeType->isPointerType()) |
8073 | return PtrPtrKernelParam; |
8074 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || |
8075 | PointeeType.getAddressSpace() == LangAS::opencl_private || |
8076 | PointeeType.getAddressSpace() == LangAS::Default) |
8077 | return InvalidAddrSpacePtrKernelParam; |
8078 | return PtrKernelParam; |
8079 | } |
8080 | |
8081 | // OpenCL v1.2 s6.9.k: |
8082 | // Arguments to kernel functions in a program cannot be declared with the |
8083 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and |
8084 | // uintptr_t or a struct and/or union that contain fields declared to be one |
8085 | // of these built-in scalar types. |
8086 | if (isOpenCLSizeDependentType(S.getASTContext(), PT)) |
8087 | return InvalidKernelParam; |
8088 | |
8089 | if (PT->isImageType()) |
8090 | return PtrKernelParam; |
8091 | |
8092 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) |
8093 | return InvalidKernelParam; |
8094 | |
8095 | // OpenCL extension spec v1.2 s9.5: |
8096 | // This extension adds support for half scalar and vector types as built-in |
8097 | // types that can be used for arithmetic operations, conversions etc. |
8098 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) |
8099 | return InvalidKernelParam; |
8100 | |
8101 | if (PT->isRecordType()) |
8102 | return RecordKernelParam; |
8103 | |
8104 | // Look into an array argument to check if it has a forbidden type. |
8105 | if (PT->isArrayType()) { |
8106 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); |
8107 | // Call ourself to check an underlying type of an array. Since the |
8108 | // getPointeeOrArrayElementType returns an innermost type which is not an |
8109 | // array, this recursive call only happens once. |
8110 | return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); |
8111 | } |
8112 | |
8113 | return ValidKernelParam; |
8114 | } |
8115 | |
8116 | static void checkIsValidOpenCLKernelParameter( |
8117 | Sema &S, |
8118 | Declarator &D, |
8119 | ParmVarDecl *Param, |
8120 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { |
8121 | QualType PT = Param->getType(); |
8122 | |
8123 | // Cache the valid types we encounter to avoid rechecking structs that are |
8124 | // used again |
8125 | if (ValidTypes.count(PT.getTypePtr())) |
8126 | return; |
8127 | |
8128 | switch (getOpenCLKernelParameterType(S, PT)) { |
8129 | case PtrPtrKernelParam: |
8130 | // OpenCL v1.2 s6.9.a: |
8131 | // A kernel function argument cannot be declared as a |
8132 | // pointer to a pointer type. |
8133 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); |
8134 | D.setInvalidType(); |
8135 | return; |
8136 | |
8137 | case InvalidAddrSpacePtrKernelParam: |
8138 | // OpenCL v1.0 s6.5: |
8139 | // __kernel function arguments declared to be a pointer of a type can point |
8140 | // to one of the following address spaces only : __global, __local or |
8141 | // __constant. |
8142 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); |
8143 | D.setInvalidType(); |
8144 | return; |
8145 | |
8146 | // OpenCL v1.2 s6.9.k: |
8147 | // Arguments to kernel functions in a program cannot be declared with the |
8148 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and |
8149 | // uintptr_t or a struct and/or union that contain fields declared to be |
8150 | // one of these built-in scalar types. |
8151 | |
8152 | case InvalidKernelParam: |
8153 | // OpenCL v1.2 s6.8 n: |
8154 | // A kernel function argument cannot be declared |
8155 | // of event_t type. |
8156 | // Do not diagnose half type since it is diagnosed as invalid argument |
8157 | // type for any function elsewhere. |
8158 | if (!PT->isHalfType()) { |
8159 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; |
8160 | |
8161 | // Explain what typedefs are involved. |
8162 | const TypedefType *Typedef = nullptr; |
8163 | while ((Typedef = PT->getAs<TypedefType>())) { |
8164 | SourceLocation Loc = Typedef->getDecl()->getLocation(); |
8165 | // SourceLocation may be invalid for a built-in type. |
8166 | if (Loc.isValid()) |
8167 | S.Diag(Loc, diag::note_entity_declared_at) << PT; |
8168 | PT = Typedef->desugar(); |
8169 | } |
8170 | } |
8171 | |
8172 | D.setInvalidType(); |
8173 | return; |
8174 | |
8175 | case PtrKernelParam: |
8176 | case ValidKernelParam: |
8177 | ValidTypes.insert(PT.getTypePtr()); |
8178 | return; |
8179 | |
8180 | case RecordKernelParam: |
8181 | break; |
8182 | } |
8183 | |
8184 | // Track nested structs we will inspect |
8185 | SmallVector<const Decl *, 4> VisitStack; |
8186 | |
8187 | // Track where we are in the nested structs. Items will migrate from |
8188 | // VisitStack to HistoryStack as we do the DFS for bad field. |
8189 | SmallVector<const FieldDecl *, 4> HistoryStack; |
8190 | HistoryStack.push_back(nullptr); |
8191 | |
8192 | // At this point we already handled everything except of a RecordType or |
8193 | // an ArrayType of a RecordType. |
8194 | assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type." ) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8194, __PRETTY_FUNCTION__)); |
8195 | const RecordType *RecTy = |
8196 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); |
8197 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); |
8198 | |
8199 | VisitStack.push_back(RecTy->getDecl()); |
8200 | assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast <void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8200, __PRETTY_FUNCTION__)); |
8201 | |
8202 | do { |
8203 | const Decl *Next = VisitStack.pop_back_val(); |
8204 | if (!Next) { |
8205 | assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8205, __PRETTY_FUNCTION__)); |
8206 | // Found a marker, we have gone up a level |
8207 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) |
8208 | ValidTypes.insert(Hist->getType().getTypePtr()); |
8209 | |
8210 | continue; |
8211 | } |
8212 | |
8213 | // Adds everything except the original parameter declaration (which is not a |
8214 | // field itself) to the history stack. |
8215 | const RecordDecl *RD; |
8216 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { |
8217 | HistoryStack.push_back(Field); |
8218 | |
8219 | QualType FieldTy = Field->getType(); |
8220 | // Other field types (known to be valid or invalid) are handled while we |
8221 | // walk around RecordDecl::fields(). |
8222 | assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8223, __PRETTY_FUNCTION__)) |
8223 | "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8223, __PRETTY_FUNCTION__)); |
8224 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); |
8225 | |
8226 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); |
8227 | } else { |
8228 | RD = cast<RecordDecl>(Next); |
8229 | } |
8230 | |
8231 | // Add a null marker so we know when we've gone back up a level |
8232 | VisitStack.push_back(nullptr); |
8233 | |
8234 | for (const auto *FD : RD->fields()) { |
8235 | QualType QT = FD->getType(); |
8236 | |
8237 | if (ValidTypes.count(QT.getTypePtr())) |
8238 | continue; |
8239 | |
8240 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); |
8241 | if (ParamType == ValidKernelParam) |
8242 | continue; |
8243 | |
8244 | if (ParamType == RecordKernelParam) { |
8245 | VisitStack.push_back(FD); |
8246 | continue; |
8247 | } |
8248 | |
8249 | // OpenCL v1.2 s6.9.p: |
8250 | // Arguments to kernel functions that are declared to be a struct or union |
8251 | // do not allow OpenCL objects to be passed as elements of the struct or |
8252 | // union. |
8253 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || |
8254 | ParamType == InvalidAddrSpacePtrKernelParam) { |
8255 | S.Diag(Param->getLocation(), |
8256 | diag::err_record_with_pointers_kernel_param) |
8257 | << PT->isUnionType() |
8258 | << PT; |
8259 | } else { |
8260 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; |
8261 | } |
8262 | |
8263 | S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) |
8264 | << OrigRecDecl->getDeclName(); |
8265 | |
8266 | // We have an error, now let's go back up through history and show where |
8267 | // the offending field came from |
8268 | for (ArrayRef<const FieldDecl *>::const_iterator |
8269 | I = HistoryStack.begin() + 1, |
8270 | E = HistoryStack.end(); |
8271 | I != E; ++I) { |
8272 | const FieldDecl *OuterField = *I; |
8273 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) |
8274 | << OuterField->getType(); |
8275 | } |
8276 | |
8277 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) |
8278 | << QT->isPointerType() |
8279 | << QT; |
8280 | D.setInvalidType(); |
8281 | return; |
8282 | } |
8283 | } while (!VisitStack.empty()); |
8284 | } |
8285 | |
8286 | /// Find the DeclContext in which a tag is implicitly declared if we see an |
8287 | /// elaborated type specifier in the specified context, and lookup finds |
8288 | /// nothing. |
8289 | static DeclContext *getTagInjectionContext(DeclContext *DC) { |
8290 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) |
8291 | DC = DC->getParent(); |
8292 | return DC; |
8293 | } |
8294 | |
8295 | /// Find the Scope in which a tag is implicitly declared if we see an |
8296 | /// elaborated type specifier in the specified context, and lookup finds |
8297 | /// nothing. |
8298 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { |
8299 | while (S->isClassScope() || |
8300 | (LangOpts.CPlusPlus && |
8301 | S->isFunctionPrototypeScope()) || |
8302 | ((S->getFlags() & Scope::DeclScope) == 0) || |
8303 | (S->getEntity() && S->getEntity()->isTransparentContext())) |
8304 | S = S->getParent(); |
8305 | return S; |
8306 | } |
8307 | |
8308 | NamedDecl* |
8309 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, |
8310 | TypeSourceInfo *TInfo, LookupResult &Previous, |
8311 | MultiTemplateParamsArg TemplateParamLists, |
8312 | bool &AddToScope) { |
8313 | QualType R = TInfo->getType(); |
8314 | |
8315 | assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8315, __PRETTY_FUNCTION__)); |
8316 | |
8317 | // TODO: consider using NameInfo for diagnostic. |
8318 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); |
8319 | DeclarationName Name = NameInfo.getName(); |
8320 | StorageClass SC = getFunctionStorageClass(*this, D); |
8321 | |
8322 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) |
8323 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), |
8324 | diag::err_invalid_thread) |
8325 | << DeclSpec::getSpecifierName(TSCS); |
8326 | |
8327 | if (D.isFirstDeclarationOfMember()) |
8328 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), |
8329 | D.getIdentifierLoc()); |
8330 | |
8331 | bool isFriend = false; |
8332 | FunctionTemplateDecl *FunctionTemplate = nullptr; |
8333 | bool isMemberSpecialization = false; |
8334 | bool isFunctionTemplateSpecialization = false; |
8335 | |
8336 | bool isDependentClassScopeExplicitSpecialization = false; |
8337 | bool HasExplicitTemplateArgs = false; |
8338 | TemplateArgumentListInfo TemplateArgs; |
8339 | |
8340 | bool isVirtualOkay = false; |
8341 | |
8342 | DeclContext *OriginalDC = DC; |
8343 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); |
8344 | |
8345 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, |
8346 | isVirtualOkay); |
8347 | if (!NewFD) return nullptr; |
8348 | |
8349 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) |
8350 | NewFD->setTopLevelDeclInObjCContainer(); |
8351 | |
8352 | // Set the lexical context. If this is a function-scope declaration, or has a |
8353 | // C++ scope specifier, or is the object of a friend declaration, the lexical |
8354 | // context will be different from the semantic context. |
8355 | NewFD->setLexicalDeclContext(CurContext); |
8356 | |
8357 | if (IsLocalExternDecl) |
8358 | NewFD->setLocalExternDecl(); |
8359 | |
8360 | if (getLangOpts().CPlusPlus) { |
8361 | bool isInline = D.getDeclSpec().isInlineSpecified(); |
8362 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); |
8363 | bool isExplicit = D.getDeclSpec().isExplicitSpecified(); |
8364 | bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); |
8365 | isFriend = D.getDeclSpec().isFriendSpecified(); |
8366 | if (isFriend && !isInline && D.isFunctionDefinition()) { |
8367 | // C++ [class.friend]p5 |
8368 | // A function can be defined in a friend declaration of a |
8369 | // class . . . . Such a function is implicitly inline. |
8370 | NewFD->setImplicitlyInline(); |
8371 | } |
8372 | |
8373 | // If this is a method defined in an __interface, and is not a constructor |
8374 | // or an overloaded operator, then set the pure flag (isVirtual will already |
8375 | // return true). |
8376 | if (const CXXRecordDecl *Parent = |
8377 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { |
8378 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) |
8379 | NewFD->setPure(true); |
8380 | |
8381 | // C++ [class.union]p2 |
8382 | // A union can have member functions, but not virtual functions. |
8383 | if (isVirtual && Parent->isUnion()) |
8384 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); |
8385 | } |
8386 | |
8387 | SetNestedNameSpecifier(*this, NewFD, D); |
8388 | isMemberSpecialization = false; |
8389 | isFunctionTemplateSpecialization = false; |
8390 | if (D.isInvalidType()) |
8391 | NewFD->setInvalidDecl(); |
8392 | |
8393 | // Match up the template parameter lists with the scope specifier, then |
8394 | // determine whether we have a template or a template specialization. |
8395 | bool Invalid = false; |
8396 | if (TemplateParameterList *TemplateParams = |
8397 | MatchTemplateParametersToScopeSpecifier( |
8398 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), |
8399 | D.getCXXScopeSpec(), |
8400 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId |
8401 | ? D.getName().TemplateId |
8402 | : nullptr, |
8403 | TemplateParamLists, isFriend, isMemberSpecialization, |
8404 | Invalid)) { |
8405 | if (TemplateParams->size() > 0) { |
8406 | // This is a function template |
8407 | |
8408 | // Check that we can declare a template here. |
8409 | if (CheckTemplateDeclScope(S, TemplateParams)) |
8410 | NewFD->setInvalidDecl(); |
8411 | |
8412 | // A destructor cannot be a template. |
8413 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { |
8414 | Diag(NewFD->getLocation(), diag::err_destructor_template); |
8415 | NewFD->setInvalidDecl(); |
8416 | } |
8417 | |
8418 | // If we're adding a template to a dependent context, we may need to |
8419 | // rebuilding some of the types used within the template parameter list, |
8420 | // now that we know what the current instantiation is. |
8421 | if (DC->isDependentContext()) { |
8422 | ContextRAII SavedContext(*this, DC); |
8423 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) |
8424 | Invalid = true; |
8425 | } |
8426 | |
8427 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, |
8428 | NewFD->getLocation(), |
8429 | Name, TemplateParams, |
8430 | NewFD); |
8431 | FunctionTemplate->setLexicalDeclContext(CurContext); |
8432 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); |
8433 | |
8434 | // For source fidelity, store the other template param lists. |
8435 | if (TemplateParamLists.size() > 1) { |
8436 | NewFD->setTemplateParameterListsInfo(Context, |
8437 | TemplateParamLists.drop_back(1)); |
8438 | } |
8439 | } else { |
8440 | // This is a function template specialization. |
8441 | isFunctionTemplateSpecialization = true; |
8442 | // For source fidelity, store all the template param lists. |
8443 | if (TemplateParamLists.size() > 0) |
8444 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); |
8445 | |
8446 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". |
8447 | if (isFriend) { |
8448 | // We want to remove the "template<>", found here. |
8449 | SourceRange RemoveRange = TemplateParams->getSourceRange(); |
8450 | |
8451 | // If we remove the template<> and the name is not a |
8452 | // template-id, we're actually silently creating a problem: |
8453 | // the friend declaration will refer to an untemplated decl, |
8454 | // and clearly the user wants a template specialization. So |
8455 | // we need to insert '<>' after the name. |
8456 | SourceLocation InsertLoc; |
8457 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { |
8458 | InsertLoc = D.getName().getSourceRange().getEnd(); |
8459 | InsertLoc = getLocForEndOfToken(InsertLoc); |
8460 | } |
8461 | |
8462 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) |
8463 | << Name << RemoveRange |
8464 | << FixItHint::CreateRemoval(RemoveRange) |
8465 | << FixItHint::CreateInsertion(InsertLoc, "<>"); |
8466 | } |
8467 | } |
8468 | } else { |
8469 | // All template param lists were matched against the scope specifier: |
8470 | // this is NOT (an explicit specialization of) a template. |
8471 | if (TemplateParamLists.size() > 0) |
8472 | // For source fidelity, store all the template param lists. |
8473 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); |
8474 | } |
8475 | |
8476 | if (Invalid) { |
8477 | NewFD->setInvalidDecl(); |
8478 | if (FunctionTemplate) |
8479 | FunctionTemplate->setInvalidDecl(); |
8480 | } |
8481 | |
8482 | // C++ [dcl.fct.spec]p5: |
8483 | // The virtual specifier shall only be used in declarations of |
8484 | // nonstatic class member functions that appear within a |
8485 | // member-specification of a class declaration; see 10.3. |
8486 | // |
8487 | if (isVirtual && !NewFD->isInvalidDecl()) { |
8488 | if (!isVirtualOkay) { |
8489 | Diag(D.getDeclSpec().getVirtualSpecLoc(), |
8490 | diag::err_virtual_non_function); |
8491 | } else if (!CurContext->isRecord()) { |
8492 | // 'virtual' was specified outside of the class. |
8493 | Diag(D.getDeclSpec().getVirtualSpecLoc(), |
8494 | diag::err_virtual_out_of_class) |
8495 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); |
8496 | } else if (NewFD->getDescribedFunctionTemplate()) { |
8497 | // C++ [temp.mem]p3: |
8498 | // A member function template shall not be virtual. |
8499 | Diag(D.getDeclSpec().getVirtualSpecLoc(), |
8500 | diag::err_virtual_member_function_template) |
8501 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); |
8502 | } else { |
8503 | // Okay: Add virtual to the method. |
8504 | NewFD->setVirtualAsWritten(true); |
8505 | } |
8506 | |
8507 | if (getLangOpts().CPlusPlus14 && |
8508 | NewFD->getReturnType()->isUndeducedType()) |
8509 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); |
8510 | } |
8511 | |
8512 | if (getLangOpts().CPlusPlus14 && |
8513 | (NewFD->isDependentContext() || |
8514 | (isFriend && CurContext->isDependentContext())) && |
8515 | NewFD->getReturnType()->isUndeducedType()) { |
8516 | // If the function template is referenced directly (for instance, as a |
8517 | // member of the current instantiation), pretend it has a dependent type. |
8518 | // This is not really justified by the standard, but is the only sane |
8519 | // thing to do. |
8520 | // FIXME: For a friend function, we have not marked the function as being |
8521 | // a friend yet, so 'isDependentContext' on the FD doesn't work. |
8522 | const FunctionProtoType *FPT = |
8523 | NewFD->getType()->castAs<FunctionProtoType>(); |
8524 | QualType Result = |
8525 | SubstAutoType(FPT->getReturnType(), Context.DependentTy); |
8526 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), |
8527 | FPT->getExtProtoInfo())); |
8528 | } |
8529 | |
8530 | // C++ [dcl.fct.spec]p3: |
8531 | // The inline specifier shall not appear on a block scope function |
8532 | // declaration. |
8533 | if (isInline && !NewFD->isInvalidDecl()) { |
8534 | if (CurContext->isFunctionOrMethod()) { |
8535 | // 'inline' is not allowed on block scope function declaration. |
8536 | Diag(D.getDeclSpec().getInlineSpecLoc(), |
8537 | diag::err_inline_declaration_block_scope) << Name |
8538 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); |
8539 | } |
8540 | } |
8541 | |
8542 | // C++ [dcl.fct.spec]p6: |
8543 | // The explicit specifier shall be used only in the declaration of a |
8544 | // constructor or conversion function within its class definition; |
8545 | // see 12.3.1 and 12.3.2. |
8546 | if (isExplicit && !NewFD->isInvalidDecl() && |
8547 | !isa<CXXDeductionGuideDecl>(NewFD)) { |
8548 | if (!CurContext->isRecord()) { |
8549 | // 'explicit' was specified outside of the class. |
8550 | Diag(D.getDeclSpec().getExplicitSpecLoc(), |
8551 | diag::err_explicit_out_of_class) |
8552 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); |
8553 | } else if (!isa<CXXConstructorDecl>(NewFD) && |
8554 | !isa<CXXConversionDecl>(NewFD)) { |
8555 | // 'explicit' was specified on a function that wasn't a constructor |
8556 | // or conversion function. |
8557 | Diag(D.getDeclSpec().getExplicitSpecLoc(), |
8558 | diag::err_explicit_non_ctor_or_conv_function) |
8559 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); |
8560 | } |
8561 | } |
8562 | |
8563 | if (isConstexpr) { |
8564 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors |
8565 | // are implicitly inline. |
8566 | NewFD->setImplicitlyInline(); |
8567 | |
8568 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to |
8569 | // be either constructors or to return a literal type. Therefore, |
8570 | // destructors cannot be declared constexpr. |
8571 | if (isa<CXXDestructorDecl>(NewFD)) |
8572 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); |
8573 | } |
8574 | |
8575 | // If __module_private__ was specified, mark the function accordingly. |
8576 | if (D.getDeclSpec().isModulePrivateSpecified()) { |
8577 | if (isFunctionTemplateSpecialization) { |
8578 | SourceLocation ModulePrivateLoc |
8579 | = D.getDeclSpec().getModulePrivateSpecLoc(); |
8580 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) |
8581 | << 0 |
8582 | << FixItHint::CreateRemoval(ModulePrivateLoc); |
8583 | } else { |
8584 | NewFD->setModulePrivate(); |
8585 | if (FunctionTemplate) |
8586 | FunctionTemplate->setModulePrivate(); |
8587 | } |
8588 | } |
8589 | |
8590 | if (isFriend) { |
8591 | if (FunctionTemplate) { |
8592 | FunctionTemplate->setObjectOfFriendDecl(); |
8593 | FunctionTemplate->setAccess(AS_public); |
8594 | } |
8595 | NewFD->setObjectOfFriendDecl(); |
8596 | NewFD->setAccess(AS_public); |
8597 | } |
8598 | |
8599 | // If a function is defined as defaulted or deleted, mark it as such now. |
8600 | // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function |
8601 | // definition kind to FDK_Definition. |
8602 | switch (D.getFunctionDefinitionKind()) { |
8603 | case FDK_Declaration: |
8604 | case FDK_Definition: |
8605 | break; |
8606 | |
8607 | case FDK_Defaulted: |
8608 | NewFD->setDefaulted(); |
8609 | break; |
8610 | |
8611 | case FDK_Deleted: |
8612 | NewFD->setDeletedAsWritten(); |
8613 | break; |
8614 | } |
8615 | |
8616 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && |
8617 | D.isFunctionDefinition()) { |
8618 | // C++ [class.mfct]p2: |
8619 | // A member function may be defined (8.4) in its class definition, in |
8620 | // which case it is an inline member function (7.1.2) |
8621 | NewFD->setImplicitlyInline(); |
8622 | } |
8623 | |
8624 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && |
8625 | !CurContext->isRecord()) { |
8626 | // C++ [class.static]p1: |
8627 | // A data or function member of a class may be declared static |
8628 | // in a class definition, in which case it is a static member of |
8629 | // the class. |
8630 | |
8631 | // Complain about the 'static' specifier if it's on an out-of-line |
8632 | // member function definition. |
8633 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), |
8634 | diag::err_static_out_of_line) |
8635 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); |
8636 | } |
8637 | |
8638 | // C++11 [except.spec]p15: |
8639 | // A deallocation function with no exception-specification is treated |
8640 | // as if it were specified with noexcept(true). |
8641 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); |
8642 | if ((Name.getCXXOverloadedOperator() == OO_Delete || |
8643 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && |
8644 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) |
8645 | NewFD->setType(Context.getFunctionType( |
8646 | FPT->getReturnType(), FPT->getParamTypes(), |
8647 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); |
8648 | } |
8649 | |
8650 | // Filter out previous declarations that don't match the scope. |
8651 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), |
8652 | D.getCXXScopeSpec().isNotEmpty() || |
8653 | isMemberSpecialization || |
8654 | isFunctionTemplateSpecialization); |
8655 | |
8656 | // Handle GNU asm-label extension (encoded as an attribute). |
8657 | if (Expr *E = (Expr*) D.getAsmLabel()) { |
8658 | // The parser guarantees this is a string. |
8659 | StringLiteral *SE = cast<StringLiteral>(E); |
8660 | NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, |
8661 | SE->getString(), 0)); |
8662 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { |
8663 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = |
8664 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); |
8665 | if (I != ExtnameUndeclaredIdentifiers.end()) { |
8666 | if (isDeclExternC(NewFD)) { |
8667 | NewFD->addAttr(I->second); |
8668 | ExtnameUndeclaredIdentifiers.erase(I); |
8669 | } else |
8670 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) |
8671 | << /*Variable*/0 << NewFD; |
8672 | } |
8673 | } |
8674 | |
8675 | // Copy the parameter declarations from the declarator D to the function |
8676 | // declaration NewFD, if they are available. First scavenge them into Params. |
8677 | SmallVector<ParmVarDecl*, 16> Params; |
8678 | unsigned FTIIdx; |
8679 | if (D.isFunctionDeclarator(FTIIdx)) { |
8680 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; |
8681 | |
8682 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs |
8683 | // function that takes no arguments, not a function that takes a |
8684 | // single void argument. |
8685 | // We let through "const void" here because Sema::GetTypeForDeclarator |
8686 | // already checks for that case. |
8687 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { |
8688 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { |
8689 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); |
8690 | assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?" ) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8690, __PRETTY_FUNCTION__)); |
8691 | Param->setDeclContext(NewFD); |
8692 | Params.push_back(Param); |
8693 | |
8694 | if (Param->isInvalidDecl()) |
8695 | NewFD->setInvalidDecl(); |
8696 | } |
8697 | } |
8698 | |
8699 | if (!getLangOpts().CPlusPlus) { |
8700 | // In C, find all the tag declarations from the prototype and move them |
8701 | // into the function DeclContext. Remove them from the surrounding tag |
8702 | // injection context of the function, which is typically but not always |
8703 | // the TU. |
8704 | DeclContext *PrototypeTagContext = |
8705 | getTagInjectionContext(NewFD->getLexicalDeclContext()); |
8706 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { |
8707 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); |
8708 | |
8709 | // We don't want to reparent enumerators. Look at their parent enum |
8710 | // instead. |
8711 | if (!TD) { |
8712 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) |
8713 | TD = cast<EnumDecl>(ECD->getDeclContext()); |
8714 | } |
8715 | if (!TD) |
8716 | continue; |
8717 | DeclContext *TagDC = TD->getLexicalDeclContext(); |
8718 | if (!TagDC->containsDecl(TD)) |
8719 | continue; |
8720 | TagDC->removeDecl(TD); |
8721 | TD->setDeclContext(NewFD); |
8722 | NewFD->addDecl(TD); |
8723 | |
8724 | // Preserve the lexical DeclContext if it is not the surrounding tag |
8725 | // injection context of the FD. In this example, the semantic context of |
8726 | // E will be f and the lexical context will be S, while both the |
8727 | // semantic and lexical contexts of S will be f: |
8728 | // void f(struct S { enum E { a } f; } s); |
8729 | if (TagDC != PrototypeTagContext) |
8730 | TD->setLexicalDeclContext(TagDC); |
8731 | } |
8732 | } |
8733 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { |
8734 | // When we're declaring a function with a typedef, typeof, etc as in the |
8735 | // following example, we'll need to synthesize (unnamed) |
8736 | // parameters for use in the declaration. |
8737 | // |
8738 | // @code |
8739 | // typedef void fn(int); |
8740 | // fn f; |
8741 | // @endcode |
8742 | |
8743 | // Synthesize a parameter for each argument type. |
8744 | for (const auto &AI : FT->param_types()) { |
8745 | ParmVarDecl *Param = |
8746 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); |
8747 | Param->setScopeInfo(0, Params.size()); |
8748 | Params.push_back(Param); |
8749 | } |
8750 | } else { |
8751 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8752, __PRETTY_FUNCTION__)) |
8752 | "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8752, __PRETTY_FUNCTION__)); |
8753 | } |
8754 | |
8755 | // Finally, we know we have the right number of parameters, install them. |
8756 | NewFD->setParams(Params); |
8757 | |
8758 | if (D.getDeclSpec().isNoreturnSpecified()) |
8759 | NewFD->addAttr( |
8760 | ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), |
8761 | Context, 0)); |
8762 | |
8763 | // Functions returning a variably modified type violate C99 6.7.5.2p2 |
8764 | // because all functions have linkage. |
8765 | if (!NewFD->isInvalidDecl() && |
8766 | NewFD->getReturnType()->isVariablyModifiedType()) { |
8767 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); |
8768 | NewFD->setInvalidDecl(); |
8769 | } |
8770 | |
8771 | // Apply an implicit SectionAttr if '#pragma clang section text' is active |
8772 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && |
8773 | !NewFD->hasAttr<SectionAttr>()) { |
8774 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, |
8775 | PragmaClangTextSection.SectionName, |
8776 | PragmaClangTextSection.PragmaLocation)); |
8777 | } |
8778 | |
8779 | // Apply an implicit SectionAttr if #pragma code_seg is active. |
8780 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && |
8781 | !NewFD->hasAttr<SectionAttr>()) { |
8782 | NewFD->addAttr( |
8783 | SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, |
8784 | CodeSegStack.CurrentValue->getString(), |
8785 | CodeSegStack.CurrentPragmaLocation)); |
8786 | if (UnifySection(CodeSegStack.CurrentValue->getString(), |
8787 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | |
8788 | ASTContext::PSF_Read, |
8789 | NewFD)) |
8790 | NewFD->dropAttr<SectionAttr>(); |
8791 | } |
8792 | |
8793 | // Apply an implicit CodeSegAttr from class declspec or |
8794 | // apply an implicit SectionAttr from #pragma code_seg if active. |
8795 | if (!NewFD->hasAttr<CodeSegAttr>()) { |
8796 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, |
8797 | D.isFunctionDefinition())) { |
8798 | NewFD->addAttr(SAttr); |
8799 | } |
8800 | } |
8801 | |
8802 | // Handle attributes. |
8803 | ProcessDeclAttributes(S, NewFD, D); |
8804 | |
8805 | if (getLangOpts().OpenCL) { |
8806 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return |
8807 | // type declaration will generate a compilation error. |
8808 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); |
8809 | if (AddressSpace != LangAS::Default) { |
8810 | Diag(NewFD->getLocation(), |
8811 | diag::err_opencl_return_value_with_address_space); |
8812 | NewFD->setInvalidDecl(); |
8813 | } |
8814 | } |
8815 | |
8816 | if (!getLangOpts().CPlusPlus) { |
8817 | // Perform semantic checking on the function declaration. |
8818 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) |
8819 | CheckMain(NewFD, D.getDeclSpec()); |
8820 | |
8821 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) |
8822 | CheckMSVCRTEntryPoint(NewFD); |
8823 | |
8824 | if (!NewFD->isInvalidDecl()) |
8825 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, |
8826 | isMemberSpecialization)); |
8827 | else if (!Previous.empty()) |
8828 | // Recover gracefully from an invalid redeclaration. |
8829 | D.setRedeclaration(true); |
8830 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8832, __PRETTY_FUNCTION__)) |
8831 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8832, __PRETTY_FUNCTION__)) |
8832 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8832, __PRETTY_FUNCTION__)); |
8833 | |
8834 | // Diagnose no-prototype function declarations with calling conventions that |
8835 | // don't support variadic calls. Only do this in C and do it after merging |
8836 | // possibly prototyped redeclarations. |
8837 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); |
8838 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { |
8839 | CallingConv CC = FT->getExtInfo().getCC(); |
8840 | if (!supportsVariadicCall(CC)) { |
8841 | // Windows system headers sometimes accidentally use stdcall without |
8842 | // (void) parameters, so we relax this to a warning. |
8843 | int DiagID = |
8844 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; |
8845 | Diag(NewFD->getLocation(), DiagID) |
8846 | << FunctionType::getNameForCallConv(CC); |
8847 | } |
8848 | } |
8849 | } else { |
8850 | // C++11 [replacement.functions]p3: |
8851 | // The program's definitions shall not be specified as inline. |
8852 | // |
8853 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. |
8854 | // |
8855 | // Suppress the diagnostic if the function is __attribute__((used)), since |
8856 | // that forces an external definition to be emitted. |
8857 | if (D.getDeclSpec().isInlineSpecified() && |
8858 | NewFD->isReplaceableGlobalAllocationFunction() && |
8859 | !NewFD->hasAttr<UsedAttr>()) |
8860 | Diag(D.getDeclSpec().getInlineSpecLoc(), |
8861 | diag::ext_operator_new_delete_declared_inline) |
8862 | << NewFD->getDeclName(); |
8863 | |
8864 | // If the declarator is a template-id, translate the parser's template |
8865 | // argument list into our AST format. |
8866 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { |
8867 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; |
8868 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); |
8869 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); |
8870 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
8871 | TemplateId->NumArgs); |
8872 | translateTemplateArguments(TemplateArgsPtr, |
8873 | TemplateArgs); |
8874 | |
8875 | HasExplicitTemplateArgs = true; |
8876 | |
8877 | if (NewFD->isInvalidDecl()) { |
8878 | HasExplicitTemplateArgs = false; |
8879 | } else if (FunctionTemplate) { |
8880 | // Function template with explicit template arguments. |
8881 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) |
8882 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); |
8883 | |
8884 | HasExplicitTemplateArgs = false; |
8885 | } else { |
8886 | assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8888, __PRETTY_FUNCTION__)) |
8887 | D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8888, __PRETTY_FUNCTION__)) |
8888 | "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8888, __PRETTY_FUNCTION__)); |
8889 | // "friend void foo<>(int);" is an implicit specialization decl. |
8890 | isFunctionTemplateSpecialization = true; |
8891 | } |
8892 | } else if (isFriend && isFunctionTemplateSpecialization) { |
8893 | // This combination is only possible in a recovery case; the user |
8894 | // wrote something like: |
8895 | // template <> friend void foo(int); |
8896 | // which we're recovering from as if the user had written: |
8897 | // friend void foo<>(int); |
8898 | // Go ahead and fake up a template id. |
8899 | HasExplicitTemplateArgs = true; |
8900 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); |
8901 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); |
8902 | } |
8903 | |
8904 | // We do not add HD attributes to specializations here because |
8905 | // they may have different constexpr-ness compared to their |
8906 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, |
8907 | // may end up with different effective targets. Instead, a |
8908 | // specialization inherits its target attributes from its template |
8909 | // in the CheckFunctionTemplateSpecialization() call below. |
8910 | if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) |
8911 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); |
8912 | |
8913 | // If it's a friend (and only if it's a friend), it's possible |
8914 | // that either the specialized function type or the specialized |
8915 | // template is dependent, and therefore matching will fail. In |
8916 | // this case, don't check the specialization yet. |
8917 | bool InstantiationDependent = false; |
8918 | if (isFunctionTemplateSpecialization && isFriend && |
8919 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || |
8920 | TemplateSpecializationType::anyDependentTemplateArguments( |
8921 | TemplateArgs, |
8922 | InstantiationDependent))) { |
8923 | assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8924, __PRETTY_FUNCTION__)) |
8924 | "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8924, __PRETTY_FUNCTION__)); |
8925 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, |
8926 | Previous)) |
8927 | NewFD->setInvalidDecl(); |
8928 | } else if (isFunctionTemplateSpecialization) { |
8929 | if (CurContext->isDependentContext() && CurContext->isRecord() |
8930 | && !isFriend) { |
8931 | isDependentClassScopeExplicitSpecialization = true; |
8932 | } else if (!NewFD->isInvalidDecl() && |
8933 | CheckFunctionTemplateSpecialization( |
8934 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), |
8935 | Previous)) |
8936 | NewFD->setInvalidDecl(); |
8937 | |
8938 | // C++ [dcl.stc]p1: |
8939 | // A storage-class-specifier shall not be specified in an explicit |
8940 | // specialization (14.7.3) |
8941 | FunctionTemplateSpecializationInfo *Info = |
8942 | NewFD->getTemplateSpecializationInfo(); |
8943 | if (Info && SC != SC_None) { |
8944 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) |
8945 | Diag(NewFD->getLocation(), |
8946 | diag::err_explicit_specialization_inconsistent_storage_class) |
8947 | << SC |
8948 | << FixItHint::CreateRemoval( |
8949 | D.getDeclSpec().getStorageClassSpecLoc()); |
8950 | |
8951 | else |
8952 | Diag(NewFD->getLocation(), |
8953 | diag::ext_explicit_specialization_storage_class) |
8954 | << FixItHint::CreateRemoval( |
8955 | D.getDeclSpec().getStorageClassSpecLoc()); |
8956 | } |
8957 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { |
8958 | if (CheckMemberSpecialization(NewFD, Previous)) |
8959 | NewFD->setInvalidDecl(); |
8960 | } |
8961 | |
8962 | // Perform semantic checking on the function declaration. |
8963 | if (!isDependentClassScopeExplicitSpecialization) { |
8964 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) |
8965 | CheckMain(NewFD, D.getDeclSpec()); |
8966 | |
8967 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) |
8968 | CheckMSVCRTEntryPoint(NewFD); |
8969 | |
8970 | if (!NewFD->isInvalidDecl()) |
8971 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, |
8972 | isMemberSpecialization)); |
8973 | else if (!Previous.empty()) |
8974 | // Recover gracefully from an invalid redeclaration. |
8975 | D.setRedeclaration(true); |
8976 | } |
8977 | |
8978 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8980, __PRETTY_FUNCTION__)) |
8979 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8980, __PRETTY_FUNCTION__)) |
8980 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 8980, __PRETTY_FUNCTION__)); |
8981 | |
8982 | NamedDecl *PrincipalDecl = (FunctionTemplate |
8983 | ? cast<NamedDecl>(FunctionTemplate) |
8984 | : NewFD); |
8985 | |
8986 | if (isFriend && NewFD->getPreviousDecl()) { |
8987 | AccessSpecifier Access = AS_public; |
8988 | if (!NewFD->isInvalidDecl()) |
8989 | Access = NewFD->getPreviousDecl()->getAccess(); |
8990 | |
8991 | NewFD->setAccess(Access); |
8992 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); |
8993 | } |
8994 | |
8995 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && |
8996 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) |
8997 | PrincipalDecl->setNonMemberOperator(); |
8998 | |
8999 | // If we have a function template, check the template parameter |
9000 | // list. This will check and merge default template arguments. |
9001 | if (FunctionTemplate) { |
9002 | FunctionTemplateDecl *PrevTemplate = |
9003 | FunctionTemplate->getPreviousDecl(); |
9004 | CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), |
9005 | PrevTemplate ? PrevTemplate->getTemplateParameters() |
9006 | : nullptr, |
9007 | D.getDeclSpec().isFriendSpecified() |
9008 | ? (D.isFunctionDefinition() |
9009 | ? TPC_FriendFunctionTemplateDefinition |
9010 | : TPC_FriendFunctionTemplate) |
9011 | : (D.getCXXScopeSpec().isSet() && |
9012 | DC && DC->isRecord() && |
9013 | DC->isDependentContext()) |
9014 | ? TPC_ClassTemplateMember |
9015 | : TPC_FunctionTemplate); |
9016 | } |
9017 | |
9018 | if (NewFD->isInvalidDecl()) { |
9019 | // Ignore all the rest of this. |
9020 | } else if (!D.isRedeclaration()) { |
9021 | struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, |
9022 | AddToScope }; |
9023 | // Fake up an access specifier if it's supposed to be a class member. |
9024 | if (isa<CXXRecordDecl>(NewFD->getDeclContext())) |
9025 | NewFD->setAccess(AS_public); |
9026 | |
9027 | // Qualified decls generally require a previous declaration. |
9028 | if (D.getCXXScopeSpec().isSet()) { |
9029 | // ...with the major exception of templated-scope or |
9030 | // dependent-scope friend declarations. |
9031 | |
9032 | // TODO: we currently also suppress this check in dependent |
9033 | // contexts because (1) the parameter depth will be off when |
9034 | // matching friend templates and (2) we might actually be |
9035 | // selecting a friend based on a dependent factor. But there |
9036 | // are situations where these conditions don't apply and we |
9037 | // can actually do this check immediately. |
9038 | if (isFriend && |
9039 | (TemplateParamLists.size() || |
9040 | D.getCXXScopeSpec().getScopeRep()->isDependent() || |
9041 | CurContext->isDependentContext())) { |
9042 | // ignore these |
9043 | } else { |
9044 | // The user tried to provide an out-of-line definition for a |
9045 | // function that is a member of a class or namespace, but there |
9046 | // was no such member function declared (C++ [class.mfct]p2, |
9047 | // C++ [namespace.memdef]p2). For example: |
9048 | // |
9049 | // class X { |
9050 | // void f() const; |
9051 | // }; |
9052 | // |
9053 | // void X::f() { } // ill-formed |
9054 | // |
9055 | // Complain about this problem, and attempt to suggest close |
9056 | // matches (e.g., those that differ only in cv-qualifiers and |
9057 | // whether the parameter types are references). |
9058 | |
9059 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( |
9060 | *this, Previous, NewFD, ExtraArgs, false, nullptr)) { |
9061 | AddToScope = ExtraArgs.AddToScope; |
9062 | return Result; |
9063 | } |
9064 | } |
9065 | |
9066 | // Unqualified local friend declarations are required to resolve |
9067 | // to something. |
9068 | } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { |
9069 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( |
9070 | *this, Previous, NewFD, ExtraArgs, true, S)) { |
9071 | AddToScope = ExtraArgs.AddToScope; |
9072 | return Result; |
9073 | } |
9074 | } |
9075 | } else if (!D.isFunctionDefinition() && |
9076 | isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && |
9077 | !isFriend && !isFunctionTemplateSpecialization && |
9078 | !isMemberSpecialization) { |
9079 | // An out-of-line member function declaration must also be a |
9080 | // definition (C++ [class.mfct]p2). |
9081 | // Note that this is not the case for explicit specializations of |
9082 | // function templates or member functions of class templates, per |
9083 | // C++ [temp.expl.spec]p2. We also allow these declarations as an |
9084 | // extension for compatibility with old SWIG code which likes to |
9085 | // generate them. |
9086 | Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) |
9087 | << D.getCXXScopeSpec().getRange(); |
9088 | } |
9089 | } |
9090 | |
9091 | ProcessPragmaWeak(S, NewFD); |
9092 | checkAttributesAfterMerging(*this, *NewFD); |
9093 | |
9094 | AddKnownFunctionAttributes(NewFD); |
9095 | |
9096 | if (NewFD->hasAttr<OverloadableAttr>() && |
9097 | !NewFD->getType()->getAs<FunctionProtoType>()) { |
9098 | Diag(NewFD->getLocation(), |
9099 | diag::err_attribute_overloadable_no_prototype) |
9100 | << NewFD; |
9101 | |
9102 | // Turn this into a variadic function with no parameters. |
9103 | const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); |
9104 | FunctionProtoType::ExtProtoInfo EPI( |
9105 | Context.getDefaultCallingConvention(true, false)); |
9106 | EPI.Variadic = true; |
9107 | EPI.ExtInfo = FT->getExtInfo(); |
9108 | |
9109 | QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); |
9110 | NewFD->setType(R); |
9111 | } |
9112 | |
9113 | // If there's a #pragma GCC visibility in scope, and this isn't a class |
9114 | // member, set the visibility of this function. |
9115 | if (!DC->isRecord() && NewFD->isExternallyVisible()) |
9116 | AddPushedVisibilityAttribute(NewFD); |
9117 | |
9118 | // If there's a #pragma clang arc_cf_code_audited in scope, consider |
9119 | // marking the function. |
9120 | AddCFAuditedAttribute(NewFD); |
9121 | |
9122 | // If this is a function definition, check if we have to apply optnone due to |
9123 | // a pragma. |
9124 | if(D.isFunctionDefinition()) |
9125 | AddRangeBasedOptnone(NewFD); |
9126 | |
9127 | // If this is the first declaration of an extern C variable, update |
9128 | // the map of such variables. |
9129 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && |
9130 | isIncompleteDeclExternC(*this, NewFD)) |
9131 | RegisterLocallyScopedExternCDecl(NewFD, S); |
9132 | |
9133 | // Set this FunctionDecl's range up to the right paren. |
9134 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); |
9135 | |
9136 | if (D.isRedeclaration() && !Previous.empty()) { |
9137 | NamedDecl *Prev = Previous.getRepresentativeDecl(); |
9138 | checkDLLAttributeRedeclaration(*this, Prev, NewFD, |
9139 | isMemberSpecialization || |
9140 | isFunctionTemplateSpecialization, |
9141 | D.isFunctionDefinition()); |
9142 | } |
9143 | |
9144 | if (getLangOpts().CUDA) { |
9145 | IdentifierInfo *II = NewFD->getIdentifier(); |
9146 | if (II && |
9147 | II->isStr(getLangOpts().HIP ? "hipConfigureCall" |
9148 | : "cudaConfigureCall") && |
9149 | !NewFD->isInvalidDecl() && |
9150 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { |
9151 | if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) |
9152 | Diag(NewFD->getLocation(), diag::err_config_scalar_return); |
9153 | Context.setcudaConfigureCallDecl(NewFD); |
9154 | } |
9155 | |
9156 | // Variadic functions, other than a *declaration* of printf, are not allowed |
9157 | // in device-side CUDA code, unless someone passed |
9158 | // -fcuda-allow-variadic-functions. |
9159 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && |
9160 | (NewFD->hasAttr<CUDADeviceAttr>() || |
9161 | NewFD->hasAttr<CUDAGlobalAttr>()) && |
9162 | !(II && II->isStr("printf") && NewFD->isExternC() && |
9163 | !D.isFunctionDefinition())) { |
9164 | Diag(NewFD->getLocation(), diag::err_variadic_device_fn); |
9165 | } |
9166 | } |
9167 | |
9168 | MarkUnusedFileScopedDecl(NewFD); |
9169 | |
9170 | if (getLangOpts().CPlusPlus) { |
9171 | if (FunctionTemplate) { |
9172 | if (NewFD->isInvalidDecl()) |
9173 | FunctionTemplate->setInvalidDecl(); |
9174 | return FunctionTemplate; |
9175 | } |
9176 | |
9177 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) |
9178 | CompleteMemberSpecialization(NewFD, Previous); |
9179 | } |
9180 | |
9181 | if (NewFD->hasAttr<OpenCLKernelAttr>()) { |
9182 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. |
9183 | if ((getLangOpts().OpenCLVersion >= 120) |
9184 | && (SC == SC_Static)) { |
9185 | Diag(D.getIdentifierLoc(), diag::err_static_kernel); |
9186 | D.setInvalidType(); |
9187 | } |
9188 | |
9189 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. |
9190 | if (!NewFD->getReturnType()->isVoidType()) { |
9191 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); |
9192 | Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) |
9193 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") |
9194 | : FixItHint()); |
9195 | D.setInvalidType(); |
9196 | } |
9197 | |
9198 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; |
9199 | for (auto Param : NewFD->parameters()) |
9200 | checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); |
9201 | } |
9202 | for (const ParmVarDecl *Param : NewFD->parameters()) { |
9203 | QualType PT = Param->getType(); |
9204 | |
9205 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value |
9206 | // types. |
9207 | if (getLangOpts().OpenCLVersion >= 200) { |
9208 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { |
9209 | QualType ElemTy = PipeTy->getElementType(); |
9210 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { |
9211 | Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); |
9212 | D.setInvalidType(); |
9213 | } |
9214 | } |
9215 | } |
9216 | } |
9217 | |
9218 | // Here we have an function template explicit specialization at class scope. |
9219 | // The actual specialization will be postponed to template instatiation |
9220 | // time via the ClassScopeFunctionSpecializationDecl node. |
9221 | if (isDependentClassScopeExplicitSpecialization) { |
9222 | ClassScopeFunctionSpecializationDecl *NewSpec = |
9223 | ClassScopeFunctionSpecializationDecl::Create( |
9224 | Context, CurContext, NewFD->getLocation(), |
9225 | cast<CXXMethodDecl>(NewFD), |
9226 | HasExplicitTemplateArgs, TemplateArgs); |
9227 | CurContext->addDecl(NewSpec); |
9228 | AddToScope = false; |
9229 | } |
9230 | |
9231 | // Diagnose availability attributes. Availability cannot be used on functions |
9232 | // that are run during load/unload. |
9233 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { |
9234 | if (NewFD->hasAttr<ConstructorAttr>()) { |
9235 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) |
9236 | << 1; |
9237 | NewFD->dropAttr<AvailabilityAttr>(); |
9238 | } |
9239 | if (NewFD->hasAttr<DestructorAttr>()) { |
9240 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) |
9241 | << 2; |
9242 | NewFD->dropAttr<AvailabilityAttr>(); |
9243 | } |
9244 | } |
9245 | |
9246 | return NewFD; |
9247 | } |
9248 | |
9249 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say |
9250 | /// when __declspec(code_seg) "is applied to a class, all member functions of |
9251 | /// the class and nested classes -- this includes compiler-generated special |
9252 | /// member functions -- are put in the specified segment." |
9253 | /// The actual behavior is a little more complicated. The Microsoft compiler |
9254 | /// won't check outer classes if there is an active value from #pragma code_seg. |
9255 | /// The CodeSeg is always applied from the direct parent but only from outer |
9256 | /// classes when the #pragma code_seg stack is empty. See: |
9257 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer |
9258 | /// available since MS has removed the page. |
9259 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { |
9260 | const auto *Method = dyn_cast<CXXMethodDecl>(FD); |
9261 | if (!Method) |
9262 | return nullptr; |
9263 | const CXXRecordDecl *Parent = Method->getParent(); |
9264 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { |
9265 | Attr *NewAttr = SAttr->clone(S.getASTContext()); |
9266 | NewAttr->setImplicit(true); |
9267 | return NewAttr; |
9268 | } |
9269 | |
9270 | // The Microsoft compiler won't check outer classes for the CodeSeg |
9271 | // when the #pragma code_seg stack is active. |
9272 | if (S.CodeSegStack.CurrentValue) |
9273 | return nullptr; |
9274 | |
9275 | while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { |
9276 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { |
9277 | Attr *NewAttr = SAttr->clone(S.getASTContext()); |
9278 | NewAttr->setImplicit(true); |
9279 | return NewAttr; |
9280 | } |
9281 | } |
9282 | return nullptr; |
9283 | } |
9284 | |
9285 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a |
9286 | /// containing class. Otherwise it will return implicit SectionAttr if the |
9287 | /// function is a definition and there is an active value on CodeSegStack |
9288 | /// (from the current #pragma code-seg value). |
9289 | /// |
9290 | /// \param FD Function being declared. |
9291 | /// \param IsDefinition Whether it is a definition or just a declarartion. |
9292 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or |
9293 | /// nullptr if no attribute should be added. |
9294 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, |
9295 | bool IsDefinition) { |
9296 | if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) |
9297 | return A; |
9298 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && |
9299 | CodeSegStack.CurrentValue) { |
9300 | return SectionAttr::CreateImplicit(getASTContext(), |
9301 | SectionAttr::Declspec_allocate, |
9302 | CodeSegStack.CurrentValue->getString(), |
9303 | CodeSegStack.CurrentPragmaLocation); |
9304 | } |
9305 | return nullptr; |
9306 | } |
9307 | |
9308 | /// Determines if we can perform a correct type check for \p D as a |
9309 | /// redeclaration of \p PrevDecl. If not, we can generally still perform a |
9310 | /// best-effort check. |
9311 | /// |
9312 | /// \param NewD The new declaration. |
9313 | /// \param OldD The old declaration. |
9314 | /// \param NewT The portion of the type of the new declaration to check. |
9315 | /// \param OldT The portion of the type of the old declaration to check. |
9316 | bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, |
9317 | QualType NewT, QualType OldT) { |
9318 | if (!NewD->getLexicalDeclContext()->isDependentContext()) |
9319 | return true; |
9320 | |
9321 | // For dependently-typed local extern declarations and friends, we can't |
9322 | // perform a correct type check in general until instantiation: |
9323 | // |
9324 | // int f(); |
9325 | // template<typename T> void g() { T f(); } |
9326 | // |
9327 | // (valid if g() is only instantiated with T = int). |
9328 | if (NewT->isDependentType() && |
9329 | (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) |
9330 | return false; |
9331 | |
9332 | // Similarly, if the previous declaration was a dependent local extern |
9333 | // declaration, we don't really know its type yet. |
9334 | if (OldT->isDependentType() && OldD->isLocalExternDecl()) |
9335 | return false; |
9336 | |
9337 | return true; |
9338 | } |
9339 | |
9340 | /// Checks if the new declaration declared in dependent context must be |
9341 | /// put in the same redeclaration chain as the specified declaration. |
9342 | /// |
9343 | /// \param D Declaration that is checked. |
9344 | /// \param PrevDecl Previous declaration found with proper lookup method for the |
9345 | /// same declaration name. |
9346 | /// \returns True if D must be added to the redeclaration chain which PrevDecl |
9347 | /// belongs to. |
9348 | /// |
9349 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { |
9350 | if (!D->getLexicalDeclContext()->isDependentContext()) |
9351 | return true; |
9352 | |
9353 | // Don't chain dependent friend function definitions until instantiation, to |
9354 | // permit cases like |
9355 | // |
9356 | // void func(); |
9357 | // template<typename T> class C1 { friend void func() {} }; |
9358 | // template<typename T> class C2 { friend void func() {} }; |
9359 | // |
9360 | // ... which is valid if only one of C1 and C2 is ever instantiated. |
9361 | // |
9362 | // FIXME: This need only apply to function definitions. For now, we proxy |
9363 | // this by checking for a file-scope function. We do not want this to apply |
9364 | // to friend declarations nominating member functions, because that gets in |
9365 | // the way of access checks. |
9366 | if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) |
9367 | return false; |
9368 | |
9369 | auto *VD = dyn_cast<ValueDecl>(D); |
9370 | auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); |
9371 | return !VD || !PrevVD || |
9372 | canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), |
9373 | PrevVD->getType()); |
9374 | } |
9375 | |
9376 | /// Check the target attribute of the function for MultiVersion |
9377 | /// validity. |
9378 | /// |
9379 | /// Returns true if there was an error, false otherwise. |
9380 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { |
9381 | const auto *TA = FD->getAttr<TargetAttr>(); |
9382 | assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute" ) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 9382, __PRETTY_FUNCTION__)); |
9383 | TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); |
9384 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); |
9385 | enum ErrType { Feature = 0, Architecture = 1 }; |
9386 | |
9387 | if (!ParseInfo.Architecture.empty() && |
9388 | !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { |
9389 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) |
9390 | << Architecture << ParseInfo.Architecture; |
9391 | return true; |
9392 | } |
9393 | |
9394 | for (const auto &Feat : ParseInfo.Features) { |
9395 | auto BareFeat = StringRef{Feat}.substr(1); |
9396 | if (Feat[0] == '-') { |
9397 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) |
9398 | << Feature << ("no-" + BareFeat).str(); |
9399 | return true; |
9400 | } |
9401 | |
9402 | if (!TargetInfo.validateCpuSupports(BareFeat) || |
9403 | !TargetInfo.isValidFeatureName(BareFeat)) { |
9404 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) |
9405 | << Feature << BareFeat; |
9406 | return true; |
9407 | } |
9408 | } |
9409 | return false; |
9410 | } |
9411 | |
9412 | static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, |
9413 | MultiVersionKind MVType) { |
9414 | for (const Attr *A : FD->attrs()) { |
9415 | switch (A->getKind()) { |
9416 | case attr::CPUDispatch: |
9417 | case attr::CPUSpecific: |
9418 | if (MVType != MultiVersionKind::CPUDispatch && |
9419 | MVType != MultiVersionKind::CPUSpecific) |
9420 | return true; |
9421 | break; |
9422 | case attr::Target: |
9423 | if (MVType != MultiVersionKind::Target) |
9424 | return true; |
9425 | break; |
9426 | default: |
9427 | return true; |
9428 | } |
9429 | } |
9430 | return false; |
9431 | } |
9432 | |
9433 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, |
9434 | const FunctionDecl *NewFD, |
9435 | bool CausesMV, |
9436 | MultiVersionKind MVType) { |
9437 | enum DoesntSupport { |
9438 | FuncTemplates = 0, |
9439 | VirtFuncs = 1, |
9440 | DeducedReturn = 2, |
9441 | Constructors = 3, |
9442 | Destructors = 4, |
9443 | DeletedFuncs = 5, |
9444 | DefaultedFuncs = 6, |
9445 | ConstexprFuncs = 7, |
9446 | }; |
9447 | enum Different { |
9448 | CallingConv = 0, |
9449 | ReturnType = 1, |
9450 | ConstexprSpec = 2, |
9451 | InlineSpec = 3, |
9452 | StorageClass = 4, |
9453 | Linkage = 5 |
9454 | }; |
9455 | |
9456 | bool IsCPUSpecificCPUDispatchMVType = |
9457 | MVType == MultiVersionKind::CPUDispatch || |
9458 | MVType == MultiVersionKind::CPUSpecific; |
9459 | |
9460 | if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { |
9461 | S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); |
9462 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); |
9463 | return true; |
9464 | } |
9465 | |
9466 | if (!NewFD->getType()->getAs<FunctionProtoType>()) |
9467 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); |
9468 | |
9469 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { |
9470 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); |
9471 | if (OldFD) |
9472 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); |
9473 | return true; |
9474 | } |
9475 | |
9476 | // For now, disallow all other attributes. These should be opt-in, but |
9477 | // an analysis of all of them is a future FIXME. |
9478 | if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { |
9479 | S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) |
9480 | << IsCPUSpecificCPUDispatchMVType; |
9481 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); |
9482 | return true; |
9483 | } |
9484 | |
9485 | if (HasNonMultiVersionAttributes(NewFD, MVType)) |
9486 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) |
9487 | << IsCPUSpecificCPUDispatchMVType; |
9488 | |
9489 | if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) |
9490 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) |
9491 | << IsCPUSpecificCPUDispatchMVType << FuncTemplates; |
9492 | |
9493 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { |
9494 | if (NewCXXFD->isVirtual()) |
9495 | return S.Diag(NewCXXFD->getLocation(), |
9496 | diag::err_multiversion_doesnt_support) |
9497 | << IsCPUSpecificCPUDispatchMVType << VirtFuncs; |
9498 | |
9499 | if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) |
9500 | return S.Diag(NewCXXCtor->getLocation(), |
9501 | diag::err_multiversion_doesnt_support) |
9502 | << IsCPUSpecificCPUDispatchMVType << Constructors; |
9503 | |
9504 | if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) |
9505 | return S.Diag(NewCXXDtor->getLocation(), |
9506 | diag::err_multiversion_doesnt_support) |
9507 | << IsCPUSpecificCPUDispatchMVType << Destructors; |
9508 | } |
9509 | |
9510 | if (NewFD->isDeleted()) |
9511 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) |
9512 | << IsCPUSpecificCPUDispatchMVType << DeletedFuncs; |
9513 | |
9514 | if (NewFD->isDefaulted()) |
9515 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) |
9516 | << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs; |
9517 | |
9518 | if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch || |
9519 | MVType == MultiVersionKind::CPUSpecific)) |
9520 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) |
9521 | << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs; |
9522 | |
9523 | QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); |
9524 | const auto *NewType = cast<FunctionType>(NewQType); |
9525 | QualType NewReturnType = NewType->getReturnType(); |
9526 | |
9527 | if (NewReturnType->isUndeducedType()) |
9528 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) |
9529 | << IsCPUSpecificCPUDispatchMVType << DeducedReturn; |
9530 | |
9531 | // Only allow transition to MultiVersion if it hasn't been used. |
9532 | if (OldFD && CausesMV && OldFD->isUsed(false)) |
9533 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); |
9534 | |
9535 | // Ensure the return type is identical. |
9536 | if (OldFD) { |
9537 | QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); |
9538 | const auto *OldType = cast<FunctionType>(OldQType); |
9539 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); |
9540 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); |
9541 | |
9542 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) |
9543 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) |
9544 | << CallingConv; |
9545 | |
9546 | QualType OldReturnType = OldType->getReturnType(); |
9547 | |
9548 | if (OldReturnType != NewReturnType) |
9549 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) |
9550 | << ReturnType; |
9551 | |
9552 | if (OldFD->isConstexpr() != NewFD->isConstexpr()) |
9553 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) |
9554 | << ConstexprSpec; |
9555 | |
9556 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) |
9557 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) |
9558 | << InlineSpec; |
9559 | |
9560 | if (OldFD->getStorageClass() != NewFD->getStorageClass()) |
9561 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) |
9562 | << StorageClass; |
9563 | |
9564 | if (OldFD->isExternC() != NewFD->isExternC()) |
9565 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) |
9566 | << Linkage; |
9567 | |
9568 | if (S.CheckEquivalentExceptionSpec( |
9569 | OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), |
9570 | NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) |
9571 | return true; |
9572 | } |
9573 | return false; |
9574 | } |
9575 | |
9576 | /// Check the validity of a multiversion function declaration that is the |
9577 | /// first of its kind. Also sets the multiversion'ness' of the function itself. |
9578 | /// |
9579 | /// This sets NewFD->isInvalidDecl() to true if there was an error. |
9580 | /// |
9581 | /// Returns true if there was an error, false otherwise. |
9582 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, |
9583 | MultiVersionKind MVType, |
9584 | const TargetAttr *TA, |
9585 | const CPUDispatchAttr *CPUDisp, |
9586 | const CPUSpecificAttr *CPUSpec) { |
9587 | assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 9588, __PRETTY_FUNCTION__)) |
9588 | "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 9588, __PRETTY_FUNCTION__)); |
9589 | |
9590 | // Target only causes MV if it is default, otherwise this is a normal |
9591 | // function. |
9592 | if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) |
9593 | return false; |
9594 | |
9595 | if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { |
9596 | FD->setInvalidDecl(); |
9597 | return true; |
9598 | } |
9599 | |
9600 | if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { |
9601 | FD->setInvalidDecl(); |
9602 | return true; |
9603 | } |
9604 | |
9605 | FD->setIsMultiVersion(); |
9606 | return false; |
9607 | } |
9608 | |
9609 | static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { |
9610 | for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { |
9611 | if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) |
9612 | return true; |
9613 | } |
9614 | |
9615 | return false; |
9616 | } |
9617 | |
9618 | static bool CheckTargetCausesMultiVersioning( |
9619 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, |
9620 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, |
9621 | LookupResult &Previous) { |
9622 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); |
9623 | TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); |
9624 | // Sort order doesn't matter, it just needs to be consistent. |
9625 | llvm::sort(NewParsed.Features); |
9626 | |
9627 | // If the old decl is NOT MultiVersioned yet, and we don't cause that |
9628 | // to change, this is a simple redeclaration. |
9629 | if (!NewTA->isDefaultVersion() && |
9630 | (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) |
9631 | return false; |
9632 | |
9633 | // Otherwise, this decl causes MultiVersioning. |
9634 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { |
9635 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); |
9636 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); |
9637 | NewFD->setInvalidDecl(); |
9638 | return true; |
9639 | } |
9640 | |
9641 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, |
9642 | MultiVersionKind::Target)) { |
9643 | NewFD->setInvalidDecl(); |
9644 | return true; |
9645 | } |
9646 | |
9647 | if (CheckMultiVersionValue(S, NewFD)) { |
9648 | NewFD->setInvalidDecl(); |
9649 | return true; |
9650 | } |
9651 | |
9652 | // If this is 'default', permit the forward declaration. |
9653 | if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { |
9654 | Redeclaration = true; |
9655 | OldDecl = OldFD; |
9656 | OldFD->setIsMultiVersion(); |
9657 | NewFD->setIsMultiVersion(); |
9658 | return false; |
9659 | } |
9660 | |
9661 | if (CheckMultiVersionValue(S, OldFD)) { |
9662 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); |
9663 | NewFD->setInvalidDecl(); |
9664 | return true; |
9665 | } |
9666 | |
9667 | TargetAttr::ParsedTargetAttr OldParsed = |
9668 | OldTA->parse(std::less<std::string>()); |
9669 | |
9670 | if (OldParsed == NewParsed) { |
9671 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); |
9672 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); |
9673 | NewFD->setInvalidDecl(); |
9674 | return true; |
9675 | } |
9676 | |
9677 | for (const auto *FD : OldFD->redecls()) { |
9678 | const auto *CurTA = FD->getAttr<TargetAttr>(); |
9679 | // We allow forward declarations before ANY multiversioning attributes, but |
9680 | // nothing after the fact. |
9681 | if (PreviousDeclsHaveMultiVersionAttribute(FD) && |
9682 | (!CurTA || CurTA->isInherited())) { |
9683 | S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) |
9684 | << 0; |
9685 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); |
9686 | NewFD->setInvalidDecl(); |
9687 | return true; |
9688 | } |
9689 | } |
9690 | |
9691 | OldFD->setIsMultiVersion(); |
9692 | NewFD->setIsMultiVersion(); |
9693 | Redeclaration = false; |
9694 | MergeTypeWithPrevious = false; |
9695 | OldDecl = nullptr; |
9696 | Previous.clear(); |
9697 | return false; |
9698 | } |
9699 | |
9700 | /// Check the validity of a new function declaration being added to an existing |
9701 | /// multiversioned declaration collection. |
9702 | static bool CheckMultiVersionAdditionalDecl( |
9703 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, |
9704 | MultiVersionKind NewMVType, const TargetAttr *NewTA, |
9705 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, |
9706 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, |
9707 | LookupResult &Previous) { |
9708 | |
9709 | MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); |
9710 | // Disallow mixing of multiversioning types. |
9711 | if ((OldMVType == MultiVersionKind::Target && |
9712 | NewMVType != MultiVersionKind::Target) || |
9713 | (NewMVType == MultiVersionKind::Target && |
9714 | OldMVType != MultiVersionKind::Target)) { |
9715 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); |
9716 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); |
9717 | NewFD->setInvalidDecl(); |
9718 | return true; |
9719 | } |
9720 | |
9721 | TargetAttr::ParsedTargetAttr NewParsed; |
9722 | if (NewTA) { |
9723 | NewParsed = NewTA->parse(); |
9724 | llvm::sort(NewParsed.Features); |
9725 | } |
9726 | |
9727 | bool UseMemberUsingDeclRules = |
9728 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); |
9729 | |
9730 | // Next, check ALL non-overloads to see if this is a redeclaration of a |
9731 | // previous member of the MultiVersion set. |
9732 | for (NamedDecl *ND : Previous) { |
9733 | FunctionDecl *CurFD = ND->getAsFunction(); |
9734 | if (!CurFD) |
9735 | continue; |
9736 | if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) |
9737 | continue; |
9738 | |
9739 | if (NewMVType == MultiVersionKind::Target) { |
9740 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); |
9741 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { |
9742 | NewFD->setIsMultiVersion(); |
9743 | Redeclaration = true; |
9744 | OldDecl = ND; |
9745 | return false; |
9746 | } |
9747 | |
9748 | TargetAttr::ParsedTargetAttr CurParsed = |
9749 | CurTA->parse(std::less<std::string>()); |
9750 | if (CurParsed == NewParsed) { |
9751 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); |
9752 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); |
9753 | NewFD->setInvalidDecl(); |
9754 | return true; |
9755 | } |
9756 | } else { |
9757 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); |
9758 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); |
9759 | // Handle CPUDispatch/CPUSpecific versions. |
9760 | // Only 1 CPUDispatch function is allowed, this will make it go through |
9761 | // the redeclaration errors. |
9762 | if (NewMVType == MultiVersionKind::CPUDispatch && |
9763 | CurFD->hasAttr<CPUDispatchAttr>()) { |
9764 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && |
9765 | std::equal( |
9766 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), |
9767 | NewCPUDisp->cpus_begin(), |
9768 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { |
9769 | return Cur->getName() == New->getName(); |
9770 | })) { |
9771 | NewFD->setIsMultiVersion(); |
9772 | Redeclaration = true; |
9773 | OldDecl = ND; |
9774 | return false; |
9775 | } |
9776 | |
9777 | // If the declarations don't match, this is an error condition. |
9778 | S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); |
9779 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); |
9780 | NewFD->setInvalidDecl(); |
9781 | return true; |
9782 | } |
9783 | if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { |
9784 | |
9785 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && |
9786 | std::equal( |
9787 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), |
9788 | NewCPUSpec->cpus_begin(), |
9789 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { |
9790 | return Cur->getName() == New->getName(); |
9791 | })) { |
9792 | NewFD->setIsMultiVersion(); |
9793 | Redeclaration = true; |
9794 | OldDecl = ND; |
9795 | return false; |
9796 | } |
9797 | |
9798 | // Only 1 version of CPUSpecific is allowed for each CPU. |
9799 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { |
9800 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { |
9801 | if (CurII == NewII) { |
9802 | S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) |
9803 | << NewII; |
9804 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); |
9805 | NewFD->setInvalidDecl(); |
9806 | return true; |
9807 | } |
9808 | } |
9809 | } |
9810 | } |
9811 | // If the two decls aren't the same MVType, there is no possible error |
9812 | // condition. |
9813 | } |
9814 | } |
9815 | |
9816 | // Else, this is simply a non-redecl case. Checking the 'value' is only |
9817 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are |
9818 | // handled in the attribute adding step. |
9819 | if (NewMVType == MultiVersionKind::Target && |
9820 | CheckMultiVersionValue(S, NewFD)) { |
9821 | NewFD->setInvalidDecl(); |
9822 | return true; |
9823 | } |
9824 | |
9825 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false, NewMVType)) { |
9826 | NewFD->setInvalidDecl(); |
9827 | return true; |
9828 | } |
9829 | |
9830 | // Permit forward declarations in the case where these two are compatible. |
9831 | if (!OldFD->isMultiVersion()) { |
9832 | OldFD->setIsMultiVersion(); |
9833 | NewFD->setIsMultiVersion(); |
9834 | Redeclaration = true; |
9835 | OldDecl = OldFD; |
9836 | return false; |
9837 | } |
9838 | |
9839 | NewFD->setIsMultiVersion(); |
9840 | Redeclaration = false; |
9841 | MergeTypeWithPrevious = false; |
9842 | OldDecl = nullptr; |
9843 | Previous.clear(); |
9844 | return false; |
9845 | } |
9846 | |
9847 | |
9848 | /// Check the validity of a mulitversion function declaration. |
9849 | /// Also sets the multiversion'ness' of the function itself. |
9850 | /// |
9851 | /// This sets NewFD->isInvalidDecl() to true if there was an error. |
9852 | /// |
9853 | /// Returns true if there was an error, false otherwise. |
9854 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, |
9855 | bool &Redeclaration, NamedDecl *&OldDecl, |
9856 | bool &MergeTypeWithPrevious, |
9857 | LookupResult &Previous) { |
9858 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); |
9859 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); |
9860 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); |
9861 | |
9862 | // Mixing Multiversioning types is prohibited. |
9863 | if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || |
9864 | (NewCPUDisp && NewCPUSpec)) { |
9865 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); |
9866 | NewFD->setInvalidDecl(); |
9867 | return true; |
9868 | } |
9869 | |
9870 | MultiVersionKind MVType = NewFD->getMultiVersionKind(); |
9871 | |
9872 | // Main isn't allowed to become a multiversion function, however it IS |
9873 | // permitted to have 'main' be marked with the 'target' optimization hint. |
9874 | if (NewFD->isMain()) { |
9875 | if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || |
9876 | MVType == MultiVersionKind::CPUDispatch || |
9877 | MVType == MultiVersionKind::CPUSpecific) { |
9878 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); |
9879 | NewFD->setInvalidDecl(); |
9880 | return true; |
9881 | } |
9882 | return false; |
9883 | } |
9884 | |
9885 | if (!OldDecl || !OldDecl->getAsFunction() || |
9886 | OldDecl->getDeclContext()->getRedeclContext() != |
9887 | NewFD->getDeclContext()->getRedeclContext()) { |
9888 | // If there's no previous declaration, AND this isn't attempting to cause |
9889 | // multiversioning, this isn't an error condition. |
9890 | if (MVType == MultiVersionKind::None) |
9891 | return false; |
9892 | return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp, |
9893 | NewCPUSpec); |
9894 | } |
9895 | |
9896 | FunctionDecl *OldFD = OldDecl->getAsFunction(); |
9897 | |
9898 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) |
9899 | return false; |
9900 | |
9901 | if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { |
9902 | S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) |
9903 | << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); |
9904 | NewFD->setInvalidDecl(); |
9905 | return true; |
9906 | } |
9907 | |
9908 | // Handle the target potentially causes multiversioning case. |
9909 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) |
9910 | return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, |
9911 | Redeclaration, OldDecl, |
9912 | MergeTypeWithPrevious, Previous); |
9913 | |
9914 | // At this point, we have a multiversion function decl (in OldFD) AND an |
9915 | // appropriate attribute in the current function decl. Resolve that these are |
9916 | // still compatible with previous declarations. |
9917 | return CheckMultiVersionAdditionalDecl( |
9918 | S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, |
9919 | OldDecl, MergeTypeWithPrevious, Previous); |
9920 | } |
9921 | |
9922 | /// Perform semantic checking of a new function declaration. |
9923 | /// |
9924 | /// Performs semantic analysis of the new function declaration |
9925 | /// NewFD. This routine performs all semantic checking that does not |
9926 | /// require the actual declarator involved in the declaration, and is |
9927 | /// used both for the declaration of functions as they are parsed |
9928 | /// (called via ActOnDeclarator) and for the declaration of functions |
9929 | /// that have been instantiated via C++ template instantiation (called |
9930 | /// via InstantiateDecl). |
9931 | /// |
9932 | /// \param IsMemberSpecialization whether this new function declaration is |
9933 | /// a member specialization (that replaces any definition provided by the |
9934 | /// previous declaration). |
9935 | /// |
9936 | /// This sets NewFD->isInvalidDecl() to true if there was an error. |
9937 | /// |
9938 | /// \returns true if the function declaration is a redeclaration. |
9939 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, |
9940 | LookupResult &Previous, |
9941 | bool IsMemberSpecialization) { |
9942 | assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 9943, __PRETTY_FUNCTION__)) |
9943 | "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 9943, __PRETTY_FUNCTION__)); |
9944 | |
9945 | // Determine whether the type of this function should be merged with |
9946 | // a previous visible declaration. This never happens for functions in C++, |
9947 | // and always happens in C if the previous declaration was visible. |
9948 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && |
9949 | !Previous.isShadowed(); |
9950 | |
9951 | bool Redeclaration = false; |
9952 | NamedDecl *OldDecl = nullptr; |
9953 | bool MayNeedOverloadableChecks = false; |
9954 | |
9955 | // Merge or overload the declaration with an existing declaration of |
9956 | // the same name, if appropriate. |
9957 | if (!Previous.empty()) { |
9958 | // Determine whether NewFD is an overload of PrevDecl or |
9959 | // a declaration that requires merging. If it's an overload, |
9960 | // there's no more work to do here; we'll just add the new |
9961 | // function to the scope. |
9962 | if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { |
9963 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); |
9964 | if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { |
9965 | Redeclaration = true; |
9966 | OldDecl = Candidate; |
9967 | } |
9968 | } else { |
9969 | MayNeedOverloadableChecks = true; |
9970 | switch (CheckOverload(S, NewFD, Previous, OldDecl, |
9971 | /*NewIsUsingDecl*/ false)) { |
9972 | case Ovl_Match: |
9973 | Redeclaration = true; |
9974 | break; |
9975 | |
9976 | case Ovl_NonFunction: |
9977 | Redeclaration = true; |
9978 | break; |
9979 | |
9980 | case Ovl_Overload: |
9981 | Redeclaration = false; |
9982 | break; |
9983 | } |
9984 | } |
9985 | } |
9986 | |
9987 | // Check for a previous extern "C" declaration with this name. |
9988 | if (!Redeclaration && |
9989 | checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { |
9990 | if (!Previous.empty()) { |
9991 | // This is an extern "C" declaration with the same name as a previous |
9992 | // declaration, and thus redeclares that entity... |
9993 | Redeclaration = true; |
9994 | OldDecl = Previous.getFoundDecl(); |
9995 | MergeTypeWithPrevious = false; |
9996 | |
9997 | // ... except in the presence of __attribute__((overloadable)). |
9998 | if (OldDecl->hasAttr<OverloadableAttr>() || |
9999 | NewFD->hasAttr<OverloadableAttr>()) { |
10000 | if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { |
10001 | MayNeedOverloadableChecks = true; |
10002 | Redeclaration = false; |
10003 | OldDecl = nullptr; |
10004 | } |
10005 | } |
10006 | } |
10007 | } |
10008 | |
10009 | if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, |
10010 | MergeTypeWithPrevious, Previous)) |
10011 | return Redeclaration; |
10012 | |
10013 | // C++11 [dcl.constexpr]p8: |
10014 | // A constexpr specifier for a non-static member function that is not |
10015 | // a constructor declares that member function to be const. |
10016 | // |
10017 | // This needs to be delayed until we know whether this is an out-of-line |
10018 | // definition of a static member function. |
10019 | // |
10020 | // This rule is not present in C++1y, so we produce a backwards |
10021 | // compatibility warning whenever it happens in C++11. |
10022 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); |
10023 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && |
10024 | !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && |
10025 | !MD->getTypeQualifiers().hasConst()) { |
10026 | CXXMethodDecl *OldMD = nullptr; |
10027 | if (OldDecl) |
10028 | OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); |
10029 | if (!OldMD || !OldMD->isStatic()) { |
10030 | const FunctionProtoType *FPT = |
10031 | MD->getType()->castAs<FunctionProtoType>(); |
10032 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); |
10033 | EPI.TypeQuals.addConst(); |
10034 | MD->setType(Context.getFunctionType(FPT->getReturnType(), |
10035 | FPT->getParamTypes(), EPI)); |
10036 | |
10037 | // Warn that we did this, if we're not performing template instantiation. |
10038 | // In that case, we'll have warned already when the template was defined. |
10039 | if (!inTemplateInstantiation()) { |
10040 | SourceLocation AddConstLoc; |
10041 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() |
10042 | .IgnoreParens().getAs<FunctionTypeLoc>()) |
10043 | AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); |
10044 | |
10045 | Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) |
10046 | << FixItHint::CreateInsertion(AddConstLoc, " const"); |
10047 | } |
10048 | } |
10049 | } |
10050 | |
10051 | if (Redeclaration) { |
10052 | // NewFD and OldDecl represent declarations that need to be |
10053 | // merged. |
10054 | if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { |
10055 | NewFD->setInvalidDecl(); |
10056 | return Redeclaration; |
10057 | } |
10058 | |
10059 | Previous.clear(); |
10060 | Previous.addDecl(OldDecl); |
10061 | |
10062 | if (FunctionTemplateDecl *OldTemplateDecl = |
10063 | dyn_cast<FunctionTemplateDecl>(OldDecl)) { |
10064 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); |
10065 | FunctionTemplateDecl *NewTemplateDecl |
10066 | = NewFD->getDescribedFunctionTemplate(); |
10067 | assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch" ) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10067, __PRETTY_FUNCTION__)); |
10068 | |
10069 | // The call to MergeFunctionDecl above may have created some state in |
10070 | // NewTemplateDecl that needs to be merged with OldTemplateDecl before we |
10071 | // can add it as a redeclaration. |
10072 | NewTemplateDecl->mergePrevDecl(OldTemplateDecl); |
10073 | |
10074 | NewFD->setPreviousDeclaration(OldFD); |
10075 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); |
10076 | if (NewFD->isCXXClassMember()) { |
10077 | NewFD->setAccess(OldTemplateDecl->getAccess()); |
10078 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); |
10079 | } |
10080 | |
10081 | // If this is an explicit specialization of a member that is a function |
10082 | // template, mark it as a member specialization. |
10083 | if (IsMemberSpecialization && |
10084 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { |
10085 | NewTemplateDecl->setMemberSpecialization(); |
10086 | assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast <void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10086, __PRETTY_FUNCTION__)); |
10087 | // Explicit specializations of a member template do not inherit deleted |
10088 | // status from the parent member template that they are specializing. |
10089 | if (OldFD->isDeleted()) { |
10090 | // FIXME: This assert will not hold in the presence of modules. |
10091 | assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void > (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10091, __PRETTY_FUNCTION__)); |
10092 | // FIXME: We need an update record for this AST mutation. |
10093 | OldFD->setDeletedAsWritten(false); |
10094 | } |
10095 | } |
10096 | |
10097 | } else { |
10098 | if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { |
10099 | auto *OldFD = cast<FunctionDecl>(OldDecl); |
10100 | // This needs to happen first so that 'inline' propagates. |
10101 | NewFD->setPreviousDeclaration(OldFD); |
10102 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); |
10103 | if (NewFD->isCXXClassMember()) |
10104 | NewFD->setAccess(OldFD->getAccess()); |
10105 | } |
10106 | } |
10107 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && |
10108 | !NewFD->getAttr<OverloadableAttr>()) { |
10109 | assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10114, __PRETTY_FUNCTION__)) |
10110 | llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10114, __PRETTY_FUNCTION__)) |
10111 | [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10114, __PRETTY_FUNCTION__)) |
10112 | return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10114, __PRETTY_FUNCTION__)) |
10113 | })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10114, __PRETTY_FUNCTION__)) |
10114 | "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10114, __PRETTY_FUNCTION__)); |
10115 | |
10116 | auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { |
10117 | const auto *FD = dyn_cast<FunctionDecl>(ND); |
10118 | return FD && !FD->hasAttr<OverloadableAttr>(); |
10119 | }); |
10120 | |
10121 | if (OtherUnmarkedIter != Previous.end()) { |
10122 | Diag(NewFD->getLocation(), |
10123 | diag::err_attribute_overloadable_multiple_unmarked_overloads); |
10124 | Diag((*OtherUnmarkedIter)->getLocation(), |
10125 | diag::note_attribute_overloadable_prev_overload) |
10126 | << false; |
10127 | |
10128 | NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); |
10129 | } |
10130 | } |
10131 | |
10132 | // Semantic checking for this function declaration (in isolation). |
10133 | |
10134 | if (getLangOpts().CPlusPlus) { |
10135 | // C++-specific checks. |
10136 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { |
10137 | CheckConstructor(Constructor); |
10138 | } else if (CXXDestructorDecl *Destructor = |
10139 | dyn_cast<CXXDestructorDecl>(NewFD)) { |
10140 | CXXRecordDecl *Record = Destructor->getParent(); |
10141 | QualType ClassType = Context.getTypeDeclType(Record); |
10142 | |
10143 | // FIXME: Shouldn't we be able to perform this check even when the class |
10144 | // type is dependent? Both gcc and edg can handle that. |
10145 | if (!ClassType->isDependentType()) { |
10146 | DeclarationName Name |
10147 | = Context.DeclarationNames.getCXXDestructorName( |
10148 | Context.getCanonicalType(ClassType)); |
10149 | if (NewFD->getDeclName() != Name) { |
10150 | Diag(NewFD->getLocation(), diag::err_destructor_name); |
10151 | NewFD->setInvalidDecl(); |
10152 | return Redeclaration; |
10153 | } |
10154 | } |
10155 | } else if (CXXConversionDecl *Conversion |
10156 | = dyn_cast<CXXConversionDecl>(NewFD)) { |
10157 | ActOnConversionDeclarator(Conversion); |
10158 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { |
10159 | if (auto *TD = Guide->getDescribedFunctionTemplate()) |
10160 | CheckDeductionGuideTemplate(TD); |
10161 | |
10162 | // A deduction guide is not on the list of entities that can be |
10163 | // explicitly specialized. |
10164 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) |
10165 | Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) |
10166 | << /*explicit specialization*/ 1; |
10167 | } |
10168 | |
10169 | // Find any virtual functions that this function overrides. |
10170 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { |
10171 | if (!Method->isFunctionTemplateSpecialization() && |
10172 | !Method->getDescribedFunctionTemplate() && |
10173 | Method->isCanonicalDecl()) { |
10174 | if (AddOverriddenMethods(Method->getParent(), Method)) { |
10175 | // If the function was marked as "static", we have a problem. |
10176 | if (NewFD->getStorageClass() == SC_Static) { |
10177 | ReportOverrides(*this, diag::err_static_overrides_virtual, Method); |
10178 | } |
10179 | } |
10180 | } |
10181 | |
10182 | if (Method->isStatic()) |
10183 | checkThisInStaticMemberFunctionType(Method); |
10184 | } |
10185 | |
10186 | // Extra checking for C++ overloaded operators (C++ [over.oper]). |
10187 | if (NewFD->isOverloadedOperator() && |
10188 | CheckOverloadedOperatorDeclaration(NewFD)) { |
10189 | NewFD->setInvalidDecl(); |
10190 | return Redeclaration; |
10191 | } |
10192 | |
10193 | // Extra checking for C++0x literal operators (C++0x [over.literal]). |
10194 | if (NewFD->getLiteralIdentifier() && |
10195 | CheckLiteralOperatorDeclaration(NewFD)) { |
10196 | NewFD->setInvalidDecl(); |
10197 | return Redeclaration; |
10198 | } |
10199 | |
10200 | // In C++, check default arguments now that we have merged decls. Unless |
10201 | // the lexical context is the class, because in this case this is done |
10202 | // during delayed parsing anyway. |
10203 | if (!CurContext->isRecord()) |
10204 | CheckCXXDefaultArguments(NewFD); |
10205 | |
10206 | // If this function declares a builtin function, check the type of this |
10207 | // declaration against the expected type for the builtin. |
10208 | if (unsigned BuiltinID = NewFD->getBuiltinID()) { |
10209 | ASTContext::GetBuiltinTypeError Error; |
10210 | LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); |
10211 | QualType T = Context.GetBuiltinType(BuiltinID, Error); |
10212 | // If the type of the builtin differs only in its exception |
10213 | // specification, that's OK. |
10214 | // FIXME: If the types do differ in this way, it would be better to |
10215 | // retain the 'noexcept' form of the type. |
10216 | if (!T.isNull() && |
10217 | !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, |
10218 | NewFD->getType())) |
10219 | // The type of this function differs from the type of the builtin, |
10220 | // so forget about the builtin entirely. |
10221 | Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); |
10222 | } |
10223 | |
10224 | // If this function is declared as being extern "C", then check to see if |
10225 | // the function returns a UDT (class, struct, or union type) that is not C |
10226 | // compatible, and if it does, warn the user. |
10227 | // But, issue any diagnostic on the first declaration only. |
10228 | if (Previous.empty() && NewFD->isExternC()) { |
10229 | QualType R = NewFD->getReturnType(); |
10230 | if (R->isIncompleteType() && !R->isVoidType()) |
10231 | Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) |
10232 | << NewFD << R; |
10233 | else if (!R.isPODType(Context) && !R->isVoidType() && |
10234 | !R->isObjCObjectPointerType()) |
10235 | Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; |
10236 | } |
10237 | |
10238 | // C++1z [dcl.fct]p6: |
10239 | // [...] whether the function has a non-throwing exception-specification |
10240 | // [is] part of the function type |
10241 | // |
10242 | // This results in an ABI break between C++14 and C++17 for functions whose |
10243 | // declared type includes an exception-specification in a parameter or |
10244 | // return type. (Exception specifications on the function itself are OK in |
10245 | // most cases, and exception specifications are not permitted in most other |
10246 | // contexts where they could make it into a mangling.) |
10247 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { |
10248 | auto HasNoexcept = [&](QualType T) -> bool { |
10249 | // Strip off declarator chunks that could be between us and a function |
10250 | // type. We don't need to look far, exception specifications are very |
10251 | // restricted prior to C++17. |
10252 | if (auto *RT = T->getAs<ReferenceType>()) |
10253 | T = RT->getPointeeType(); |
10254 | else if (T->isAnyPointerType()) |
10255 | T = T->getPointeeType(); |
10256 | else if (auto *MPT = T->getAs<MemberPointerType>()) |
10257 | T = MPT->getPointeeType(); |
10258 | if (auto *FPT = T->getAs<FunctionProtoType>()) |
10259 | if (FPT->isNothrow()) |
10260 | return true; |
10261 | return false; |
10262 | }; |
10263 | |
10264 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); |
10265 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); |
10266 | for (QualType T : FPT->param_types()) |
10267 | AnyNoexcept |= HasNoexcept(T); |
10268 | if (AnyNoexcept) |
10269 | Diag(NewFD->getLocation(), |
10270 | diag::warn_cxx17_compat_exception_spec_in_signature) |
10271 | << NewFD; |
10272 | } |
10273 | |
10274 | if (!Redeclaration && LangOpts.CUDA) |
10275 | checkCUDATargetOverload(NewFD, Previous); |
10276 | } |
10277 | return Redeclaration; |
10278 | } |
10279 | |
10280 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { |
10281 | // C++11 [basic.start.main]p3: |
10282 | // A program that [...] declares main to be inline, static or |
10283 | // constexpr is ill-formed. |
10284 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall |
10285 | // appear in a declaration of main. |
10286 | // static main is not an error under C99, but we should warn about it. |
10287 | // We accept _Noreturn main as an extension. |
10288 | if (FD->getStorageClass() == SC_Static) |
10289 | Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus |
10290 | ? diag::err_static_main : diag::warn_static_main) |
10291 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); |
10292 | if (FD->isInlineSpecified()) |
10293 | Diag(DS.getInlineSpecLoc(), diag::err_inline_main) |
10294 | << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); |
10295 | if (DS.isNoreturnSpecified()) { |
10296 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); |
10297 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); |
10298 | Diag(NoreturnLoc, diag::ext_noreturn_main); |
10299 | Diag(NoreturnLoc, diag::note_main_remove_noreturn) |
10300 | << FixItHint::CreateRemoval(NoreturnRange); |
10301 | } |
10302 | if (FD->isConstexpr()) { |
10303 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) |
10304 | << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); |
10305 | FD->setConstexpr(false); |
10306 | } |
10307 | |
10308 | if (getLangOpts().OpenCL) { |
10309 | Diag(FD->getLocation(), diag::err_opencl_no_main) |
10310 | << FD->hasAttr<OpenCLKernelAttr>(); |
10311 | FD->setInvalidDecl(); |
10312 | return; |
10313 | } |
10314 | |
10315 | QualType T = FD->getType(); |
10316 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10316, __PRETTY_FUNCTION__)); |
10317 | const FunctionType* FT = T->castAs<FunctionType>(); |
10318 | |
10319 | // Set default calling convention for main() |
10320 | if (FT->getCallConv() != CC_C) { |
10321 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); |
10322 | FD->setType(QualType(FT, 0)); |
10323 | T = Context.getCanonicalType(FD->getType()); |
10324 | } |
10325 | |
10326 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { |
10327 | // In C with GNU extensions we allow main() to have non-integer return |
10328 | // type, but we should warn about the extension, and we disable the |
10329 | // implicit-return-zero rule. |
10330 | |
10331 | // GCC in C mode accepts qualified 'int'. |
10332 | if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) |
10333 | FD->setHasImplicitReturnZero(true); |
10334 | else { |
10335 | Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); |
10336 | SourceRange RTRange = FD->getReturnTypeSourceRange(); |
10337 | if (RTRange.isValid()) |
10338 | Diag(RTRange.getBegin(), diag::note_main_change_return_type) |
10339 | << FixItHint::CreateReplacement(RTRange, "int"); |
10340 | } |
10341 | } else { |
10342 | // In C and C++, main magically returns 0 if you fall off the end; |
10343 | // set the flag which tells us that. |
10344 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. |
10345 | |
10346 | // All the standards say that main() should return 'int'. |
10347 | if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) |
10348 | FD->setHasImplicitReturnZero(true); |
10349 | else { |
10350 | // Otherwise, this is just a flat-out error. |
10351 | SourceRange RTRange = FD->getReturnTypeSourceRange(); |
10352 | Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) |
10353 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") |
10354 | : FixItHint()); |
10355 | FD->setInvalidDecl(true); |
10356 | } |
10357 | } |
10358 | |
10359 | // Treat protoless main() as nullary. |
10360 | if (isa<FunctionNoProtoType>(FT)) return; |
10361 | |
10362 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); |
10363 | unsigned nparams = FTP->getNumParams(); |
10364 | assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10364, __PRETTY_FUNCTION__)); |
10365 | |
10366 | bool HasExtraParameters = (nparams > 3); |
10367 | |
10368 | if (FTP->isVariadic()) { |
10369 | Diag(FD->getLocation(), diag::ext_variadic_main); |
10370 | // FIXME: if we had information about the location of the ellipsis, we |
10371 | // could add a FixIt hint to remove it as a parameter. |
10372 | } |
10373 | |
10374 | // Darwin passes an undocumented fourth argument of type char**. If |
10375 | // other platforms start sprouting these, the logic below will start |
10376 | // getting shifty. |
10377 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) |
10378 | HasExtraParameters = false; |
10379 | |
10380 | if (HasExtraParameters) { |
10381 | Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; |
10382 | FD->setInvalidDecl(true); |
10383 | nparams = 3; |
10384 | } |
10385 | |
10386 | // FIXME: a lot of the following diagnostics would be improved |
10387 | // if we had some location information about types. |
10388 | |
10389 | QualType CharPP = |
10390 | Context.getPointerType(Context.getPointerType(Context.CharTy)); |
10391 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; |
10392 | |
10393 | for (unsigned i = 0; i < nparams; ++i) { |
10394 | QualType AT = FTP->getParamType(i); |
10395 | |
10396 | bool mismatch = true; |
10397 | |
10398 | if (Context.hasSameUnqualifiedType(AT, Expected[i])) |
10399 | mismatch = false; |
10400 | else if (Expected[i] == CharPP) { |
10401 | // As an extension, the following forms are okay: |
10402 | // char const ** |
10403 | // char const * const * |
10404 | // char * const * |
10405 | |
10406 | QualifierCollector qs; |
10407 | const PointerType* PT; |
10408 | if ((PT = qs.strip(AT)->getAs<PointerType>()) && |
10409 | (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && |
10410 | Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), |
10411 | Context.CharTy)) { |
10412 | qs.removeConst(); |
10413 | mismatch = !qs.empty(); |
10414 | } |
10415 | } |
10416 | |
10417 | if (mismatch) { |
10418 | Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; |
10419 | // TODO: suggest replacing given type with expected type |
10420 | FD->setInvalidDecl(true); |
10421 | } |
10422 | } |
10423 | |
10424 | if (nparams == 1 && !FD->isInvalidDecl()) { |
10425 | Diag(FD->getLocation(), diag::warn_main_one_arg); |
10426 | } |
10427 | |
10428 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { |
10429 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; |
10430 | FD->setInvalidDecl(); |
10431 | } |
10432 | } |
10433 | |
10434 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { |
10435 | QualType T = FD->getType(); |
10436 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10436, __PRETTY_FUNCTION__)); |
10437 | const FunctionType *FT = T->castAs<FunctionType>(); |
10438 | |
10439 | // Set an implicit return of 'zero' if the function can return some integral, |
10440 | // enumeration, pointer or nullptr type. |
10441 | if (FT->getReturnType()->isIntegralOrEnumerationType() || |
10442 | FT->getReturnType()->isAnyPointerType() || |
10443 | FT->getReturnType()->isNullPtrType()) |
10444 | // DllMain is exempt because a return value of zero means it failed. |
10445 | if (FD->getName() != "DllMain") |
10446 | FD->setHasImplicitReturnZero(true); |
10447 | |
10448 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { |
10449 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; |
10450 | FD->setInvalidDecl(); |
10451 | } |
10452 | } |
10453 | |
10454 | bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { |
10455 | // FIXME: Need strict checking. In C89, we need to check for |
10456 | // any assignment, increment, decrement, function-calls, or |
10457 | // commas outside of a sizeof. In C99, it's the same list, |
10458 | // except that the aforementioned are allowed in unevaluated |
10459 | // expressions. Everything else falls under the |
10460 | // "may accept other forms of constant expressions" exception. |
10461 | // (We never end up here for C++, so the constant expression |
10462 | // rules there don't matter.) |
10463 | const Expr *Culprit; |
10464 | if (Init->isConstantInitializer(Context, false, &Culprit)) |
10465 | return false; |
10466 | Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) |
10467 | << Culprit->getSourceRange(); |
10468 | return true; |
10469 | } |
10470 | |
10471 | namespace { |
10472 | // Visits an initialization expression to see if OrigDecl is evaluated in |
10473 | // its own initialization and throws a warning if it does. |
10474 | class SelfReferenceChecker |
10475 | : public EvaluatedExprVisitor<SelfReferenceChecker> { |
10476 | Sema &S; |
10477 | Decl *OrigDecl; |
10478 | bool isRecordType; |
10479 | bool isPODType; |
10480 | bool isReferenceType; |
10481 | |
10482 | bool isInitList; |
10483 | llvm::SmallVector<unsigned, 4> InitFieldIndex; |
10484 | |
10485 | public: |
10486 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; |
10487 | |
10488 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), |
10489 | S(S), OrigDecl(OrigDecl) { |
10490 | isPODType = false; |
10491 | isRecordType = false; |
10492 | isReferenceType = false; |
10493 | isInitList = false; |
10494 | if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { |
10495 | isPODType = VD->getType().isPODType(S.Context); |
10496 | isRecordType = VD->getType()->isRecordType(); |
10497 | isReferenceType = VD->getType()->isReferenceType(); |
10498 | } |
10499 | } |
10500 | |
10501 | // For most expressions, just call the visitor. For initializer lists, |
10502 | // track the index of the field being initialized since fields are |
10503 | // initialized in order allowing use of previously initialized fields. |
10504 | void CheckExpr(Expr *E) { |
10505 | InitListExpr *InitList = dyn_cast<InitListExpr>(E); |
10506 | if (!InitList) { |
10507 | Visit(E); |
10508 | return; |
10509 | } |
10510 | |
10511 | // Track and increment the index here. |
10512 | isInitList = true; |
10513 | InitFieldIndex.push_back(0); |
10514 | for (auto Child : InitList->children()) { |
10515 | CheckExpr(cast<Expr>(Child)); |
10516 | ++InitFieldIndex.back(); |
10517 | } |
10518 | InitFieldIndex.pop_back(); |
10519 | } |
10520 | |
10521 | // Returns true if MemberExpr is checked and no further checking is needed. |
10522 | // Returns false if additional checking is required. |
10523 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { |
10524 | llvm::SmallVector<FieldDecl*, 4> Fields; |
10525 | Expr *Base = E; |
10526 | bool ReferenceField = false; |
10527 | |
10528 | // Get the field members used. |
10529 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { |
10530 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); |
10531 | if (!FD) |
10532 | return false; |
10533 | Fields.push_back(FD); |
10534 | if (FD->getType()->isReferenceType()) |
10535 | ReferenceField = true; |
10536 | Base = ME->getBase()->IgnoreParenImpCasts(); |
10537 | } |
10538 | |
10539 | // Keep checking only if the base Decl is the same. |
10540 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); |
10541 | if (!DRE || DRE->getDecl() != OrigDecl) |
10542 | return false; |
10543 | |
10544 | // A reference field can be bound to an unininitialized field. |
10545 | if (CheckReference && !ReferenceField) |
10546 | return true; |
10547 | |
10548 | // Convert FieldDecls to their index number. |
10549 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; |
10550 | for (const FieldDecl *I : llvm::reverse(Fields)) |
10551 | UsedFieldIndex.push_back(I->getFieldIndex()); |
10552 | |
10553 | // See if a warning is needed by checking the first difference in index |
10554 | // numbers. If field being used has index less than the field being |
10555 | // initialized, then the use is safe. |
10556 | for (auto UsedIter = UsedFieldIndex.begin(), |
10557 | UsedEnd = UsedFieldIndex.end(), |
10558 | OrigIter = InitFieldIndex.begin(), |
10559 | OrigEnd = InitFieldIndex.end(); |
10560 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { |
10561 | if (*UsedIter < *OrigIter) |
10562 | return true; |
10563 | if (*UsedIter > *OrigIter) |
10564 | break; |
10565 | } |
10566 | |
10567 | // TODO: Add a different warning which will print the field names. |
10568 | HandleDeclRefExpr(DRE); |
10569 | return true; |
10570 | } |
10571 | |
10572 | // For most expressions, the cast is directly above the DeclRefExpr. |
10573 | // For conditional operators, the cast can be outside the conditional |
10574 | // operator if both expressions are DeclRefExpr's. |
10575 | void HandleValue(Expr *E) { |
10576 | E = E->IgnoreParens(); |
10577 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { |
10578 | HandleDeclRefExpr(DRE); |
10579 | return; |
10580 | } |
10581 | |
10582 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { |
10583 | Visit(CO->getCond()); |
10584 | HandleValue(CO->getTrueExpr()); |
10585 | HandleValue(CO->getFalseExpr()); |
10586 | return; |
10587 | } |
10588 | |
10589 | if (BinaryConditionalOperator *BCO = |
10590 | dyn_cast<BinaryConditionalOperator>(E)) { |
10591 | Visit(BCO->getCond()); |
10592 | HandleValue(BCO->getFalseExpr()); |
10593 | return; |
10594 | } |
10595 | |
10596 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { |
10597 | HandleValue(OVE->getSourceExpr()); |
10598 | return; |
10599 | } |
10600 | |
10601 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { |
10602 | if (BO->getOpcode() == BO_Comma) { |
10603 | Visit(BO->getLHS()); |
10604 | HandleValue(BO->getRHS()); |
10605 | return; |
10606 | } |
10607 | } |
10608 | |
10609 | if (isa<MemberExpr>(E)) { |
10610 | if (isInitList) { |
10611 | if (CheckInitListMemberExpr(cast<MemberExpr>(E), |
10612 | false /*CheckReference*/)) |
10613 | return; |
10614 | } |
10615 | |
10616 | Expr *Base = E->IgnoreParenImpCasts(); |
10617 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { |
10618 | // Check for static member variables and don't warn on them. |
10619 | if (!isa<FieldDecl>(ME->getMemberDecl())) |
10620 | return; |
10621 | Base = ME->getBase()->IgnoreParenImpCasts(); |
10622 | } |
10623 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) |
10624 | HandleDeclRefExpr(DRE); |
10625 | return; |
10626 | } |
10627 | |
10628 | Visit(E); |
10629 | } |
10630 | |
10631 | // Reference types not handled in HandleValue are handled here since all |
10632 | // uses of references are bad, not just r-value uses. |
10633 | void VisitDeclRefExpr(DeclRefExpr *E) { |
10634 | if (isReferenceType) |
10635 | HandleDeclRefExpr(E); |
10636 | } |
10637 | |
10638 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { |
10639 | if (E->getCastKind() == CK_LValueToRValue) { |
10640 | HandleValue(E->getSubExpr()); |
10641 | return; |
10642 | } |
10643 | |
10644 | Inherited::VisitImplicitCastExpr(E); |
10645 | } |
10646 | |
10647 | void VisitMemberExpr(MemberExpr *E) { |
10648 | if (isInitList) { |
10649 | if (CheckInitListMemberExpr(E, true /*CheckReference*/)) |
10650 | return; |
10651 | } |
10652 | |
10653 | // Don't warn on arrays since they can be treated as pointers. |
10654 | if (E->getType()->canDecayToPointerType()) return; |
10655 | |
10656 | // Warn when a non-static method call is followed by non-static member |
10657 | // field accesses, which is followed by a DeclRefExpr. |
10658 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); |
10659 | bool Warn = (MD && !MD->isStatic()); |
10660 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); |
10661 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { |
10662 | if (!isa<FieldDecl>(ME->getMemberDecl())) |
10663 | Warn = false; |
10664 | Base = ME->getBase()->IgnoreParenImpCasts(); |
10665 | } |
10666 | |
10667 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { |
10668 | if (Warn) |
10669 | HandleDeclRefExpr(DRE); |
10670 | return; |
10671 | } |
10672 | |
10673 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. |
10674 | // Visit that expression. |
10675 | Visit(Base); |
10676 | } |
10677 | |
10678 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { |
10679 | Expr *Callee = E->getCallee(); |
10680 | |
10681 | if (isa<UnresolvedLookupExpr>(Callee)) |
10682 | return Inherited::VisitCXXOperatorCallExpr(E); |
10683 | |
10684 | Visit(Callee); |
10685 | for (auto Arg: E->arguments()) |
10686 | HandleValue(Arg->IgnoreParenImpCasts()); |
10687 | } |
10688 | |
10689 | void VisitUnaryOperator(UnaryOperator *E) { |
10690 | // For POD record types, addresses of its own members are well-defined. |
10691 | if (E->getOpcode() == UO_AddrOf && isRecordType && |
10692 | isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { |
10693 | if (!isPODType) |
10694 | HandleValue(E->getSubExpr()); |
10695 | return; |
10696 | } |
10697 | |
10698 | if (E->isIncrementDecrementOp()) { |
10699 | HandleValue(E->getSubExpr()); |
10700 | return; |
10701 | } |
10702 | |
10703 | Inherited::VisitUnaryOperator(E); |
10704 | } |
10705 | |
10706 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} |
10707 | |
10708 | void VisitCXXConstructExpr(CXXConstructExpr *E) { |
10709 | if (E->getConstructor()->isCopyConstructor()) { |
10710 | Expr *ArgExpr = E->getArg(0); |
10711 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) |
10712 | if (ILE->getNumInits() == 1) |
10713 | ArgExpr = ILE->getInit(0); |
10714 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) |
10715 | if (ICE->getCastKind() == CK_NoOp) |
10716 | ArgExpr = ICE->getSubExpr(); |
10717 | HandleValue(ArgExpr); |
10718 | return; |
10719 | } |
10720 | Inherited::VisitCXXConstructExpr(E); |
10721 | } |
10722 | |
10723 | void VisitCallExpr(CallExpr *E) { |
10724 | // Treat std::move as a use. |
10725 | if (E->isCallToStdMove()) { |
10726 | HandleValue(E->getArg(0)); |
10727 | return; |
10728 | } |
10729 | |
10730 | Inherited::VisitCallExpr(E); |
10731 | } |
10732 | |
10733 | void VisitBinaryOperator(BinaryOperator *E) { |
10734 | if (E->isCompoundAssignmentOp()) { |
10735 | HandleValue(E->getLHS()); |
10736 | Visit(E->getRHS()); |
10737 | return; |
10738 | } |
10739 | |
10740 | Inherited::VisitBinaryOperator(E); |
10741 | } |
10742 | |
10743 | // A custom visitor for BinaryConditionalOperator is needed because the |
10744 | // regular visitor would check the condition and true expression separately |
10745 | // but both point to the same place giving duplicate diagnostics. |
10746 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { |
10747 | Visit(E->getCond()); |
10748 | Visit(E->getFalseExpr()); |
10749 | } |
10750 | |
10751 | void HandleDeclRefExpr(DeclRefExpr *DRE) { |
10752 | Decl* ReferenceDecl = DRE->getDecl(); |
10753 | if (OrigDecl != ReferenceDecl) return; |
10754 | unsigned diag; |
10755 | if (isReferenceType) { |
10756 | diag = diag::warn_uninit_self_reference_in_reference_init; |
10757 | } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { |
10758 | diag = diag::warn_static_self_reference_in_init; |
10759 | } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || |
10760 | isa<NamespaceDecl>(OrigDecl->getDeclContext()) || |
10761 | DRE->getDecl()->getType()->isRecordType()) { |
10762 | diag = diag::warn_uninit_self_reference_in_init; |
10763 | } else { |
10764 | // Local variables will be handled by the CFG analysis. |
10765 | return; |
10766 | } |
10767 | |
10768 | S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, |
10769 | S.PDiag(diag) |
10770 | << DRE->getDecl() << OrigDecl->getLocation() |
10771 | << DRE->getSourceRange()); |
10772 | } |
10773 | }; |
10774 | |
10775 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. |
10776 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, |
10777 | bool DirectInit) { |
10778 | // Parameters arguments are occassionially constructed with itself, |
10779 | // for instance, in recursive functions. Skip them. |
10780 | if (isa<ParmVarDecl>(OrigDecl)) |
10781 | return; |
10782 | |
10783 | E = E->IgnoreParens(); |
10784 | |
10785 | // Skip checking T a = a where T is not a record or reference type. |
10786 | // Doing so is a way to silence uninitialized warnings. |
10787 | if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) |
10788 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) |
10789 | if (ICE->getCastKind() == CK_LValueToRValue) |
10790 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) |
10791 | if (DRE->getDecl() == OrigDecl) |
10792 | return; |
10793 | |
10794 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); |
10795 | } |
10796 | } // end anonymous namespace |
10797 | |
10798 | namespace { |
10799 | // Simple wrapper to add the name of a variable or (if no variable is |
10800 | // available) a DeclarationName into a diagnostic. |
10801 | struct VarDeclOrName { |
10802 | VarDecl *VDecl; |
10803 | DeclarationName Name; |
10804 | |
10805 | friend const Sema::SemaDiagnosticBuilder & |
10806 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { |
10807 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; |
10808 | } |
10809 | }; |
10810 | } // end anonymous namespace |
10811 | |
10812 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, |
10813 | DeclarationName Name, QualType Type, |
10814 | TypeSourceInfo *TSI, |
10815 | SourceRange Range, bool DirectInit, |
10816 | Expr *Init) { |
10817 | bool IsInitCapture = !VDecl; |
10818 | assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10819, __PRETTY_FUNCTION__)) |
10819 | "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10819, __PRETTY_FUNCTION__)); |
10820 | |
10821 | VarDeclOrName VN{VDecl, Name}; |
10822 | |
10823 | DeducedType *Deduced = Type->getContainedDeducedType(); |
10824 | assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type" ) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10824, __PRETTY_FUNCTION__)); |
10825 | |
10826 | // C++11 [dcl.spec.auto]p3 |
10827 | if (!Init) { |
10828 | assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast <void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10828, __PRETTY_FUNCTION__)); |
10829 | |
10830 | // Except for class argument deduction, and then for an initializing |
10831 | // declaration only, i.e. no static at class scope or extern. |
10832 | if (!isa<DeducedTemplateSpecializationType>(Deduced) || |
10833 | VDecl->hasExternalStorage() || |
10834 | VDecl->isStaticDataMember()) { |
10835 | Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) |
10836 | << VDecl->getDeclName() << Type; |
10837 | return QualType(); |
10838 | } |
10839 | } |
10840 | |
10841 | ArrayRef<Expr*> DeduceInits; |
10842 | if (Init) |
10843 | DeduceInits = Init; |
10844 | |
10845 | if (DirectInit) { |
10846 | if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) |
10847 | DeduceInits = PL->exprs(); |
10848 | } |
10849 | |
10850 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { |
10851 | assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?" ) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10851, __PRETTY_FUNCTION__)); |
10852 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); |
10853 | InitializationKind Kind = InitializationKind::CreateForInit( |
10854 | VDecl->getLocation(), DirectInit, Init); |
10855 | // FIXME: Initialization should not be taking a mutable list of inits. |
10856 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); |
10857 | return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, |
10858 | InitsCopy); |
10859 | } |
10860 | |
10861 | if (DirectInit) { |
10862 | if (auto *IL = dyn_cast<InitListExpr>(Init)) |
10863 | DeduceInits = IL->inits(); |
10864 | } |
10865 | |
10866 | // Deduction only works if we have exactly one source expression. |
10867 | if (DeduceInits.empty()) { |
10868 | // It isn't possible to write this directly, but it is possible to |
10869 | // end up in this situation with "auto x(some_pack...);" |
10870 | Diag(Init->getBeginLoc(), IsInitCapture |
10871 | ? diag::err_init_capture_no_expression |
10872 | : diag::err_auto_var_init_no_expression) |
10873 | << VN << Type << Range; |
10874 | return QualType(); |
10875 | } |
10876 | |
10877 | if (DeduceInits.size() > 1) { |
10878 | Diag(DeduceInits[1]->getBeginLoc(), |
10879 | IsInitCapture ? diag::err_init_capture_multiple_expressions |
10880 | : diag::err_auto_var_init_multiple_expressions) |
10881 | << VN << Type << Range; |
10882 | return QualType(); |
10883 | } |
10884 | |
10885 | Expr *DeduceInit = DeduceInits[0]; |
10886 | if (DirectInit && isa<InitListExpr>(DeduceInit)) { |
10887 | Diag(Init->getBeginLoc(), IsInitCapture |
10888 | ? diag::err_init_capture_paren_braces |
10889 | : diag::err_auto_var_init_paren_braces) |
10890 | << isa<InitListExpr>(Init) << VN << Type << Range; |
10891 | return QualType(); |
10892 | } |
10893 | |
10894 | // Expressions default to 'id' when we're in a debugger. |
10895 | bool DefaultedAnyToId = false; |
10896 | if (getLangOpts().DebuggerCastResultToId && |
10897 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { |
10898 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); |
10899 | if (Result.isInvalid()) { |
10900 | return QualType(); |
10901 | } |
10902 | Init = Result.get(); |
10903 | DefaultedAnyToId = true; |
10904 | } |
10905 | |
10906 | // C++ [dcl.decomp]p1: |
10907 | // If the assignment-expression [...] has array type A and no ref-qualifier |
10908 | // is present, e has type cv A |
10909 | if (VDecl && isa<DecompositionDecl>(VDecl) && |
10910 | Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && |
10911 | DeduceInit->getType()->isConstantArrayType()) |
10912 | return Context.getQualifiedType(DeduceInit->getType(), |
10913 | Type.getQualifiers()); |
10914 | |
10915 | QualType DeducedType; |
10916 | if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { |
10917 | if (!IsInitCapture) |
10918 | DiagnoseAutoDeductionFailure(VDecl, DeduceInit); |
10919 | else if (isa<InitListExpr>(Init)) |
10920 | Diag(Range.getBegin(), |
10921 | diag::err_init_capture_deduction_failure_from_init_list) |
10922 | << VN |
10923 | << (DeduceInit->getType().isNull() ? TSI->getType() |
10924 | : DeduceInit->getType()) |
10925 | << DeduceInit->getSourceRange(); |
10926 | else |
10927 | Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) |
10928 | << VN << TSI->getType() |
10929 | << (DeduceInit->getType().isNull() ? TSI->getType() |
10930 | : DeduceInit->getType()) |
10931 | << DeduceInit->getSourceRange(); |
10932 | } |
10933 | |
10934 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using |
10935 | // 'id' instead of a specific object type prevents most of our usual |
10936 | // checks. |
10937 | // We only want to warn outside of template instantiations, though: |
10938 | // inside a template, the 'id' could have come from a parameter. |
10939 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && |
10940 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { |
10941 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); |
10942 | Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; |
10943 | } |
10944 | |
10945 | return DeducedType; |
10946 | } |
10947 | |
10948 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, |
10949 | Expr *Init) { |
10950 | QualType DeducedType = deduceVarTypeFromInitializer( |
10951 | VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), |
10952 | VDecl->getSourceRange(), DirectInit, Init); |
10953 | if (DeducedType.isNull()) { |
10954 | VDecl->setInvalidDecl(); |
10955 | return true; |
10956 | } |
10957 | |
10958 | VDecl->setType(DeducedType); |
10959 | assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10959, __PRETTY_FUNCTION__)); |
10960 | |
10961 | // In ARC, infer lifetime. |
10962 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) |
10963 | VDecl->setInvalidDecl(); |
10964 | |
10965 | // If this is a redeclaration, check that the type we just deduced matches |
10966 | // the previously declared type. |
10967 | if (VarDecl *Old = VDecl->getPreviousDecl()) { |
10968 | // We never need to merge the type, because we cannot form an incomplete |
10969 | // array of auto, nor deduce such a type. |
10970 | MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); |
10971 | } |
10972 | |
10973 | // Check the deduced type is valid for a variable declaration. |
10974 | CheckVariableDeclarationType(VDecl); |
10975 | return VDecl->isInvalidDecl(); |
10976 | } |
10977 | |
10978 | /// AddInitializerToDecl - Adds the initializer Init to the |
10979 | /// declaration dcl. If DirectInit is true, this is C++ direct |
10980 | /// initialization rather than copy initialization. |
10981 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { |
10982 | // If there is no declaration, there was an error parsing it. Just ignore |
10983 | // the initializer. |
10984 | if (!RealDecl || RealDecl->isInvalidDecl()) { |
10985 | CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); |
10986 | return; |
10987 | } |
10988 | |
10989 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { |
10990 | // Pure-specifiers are handled in ActOnPureSpecifier. |
10991 | Diag(Method->getLocation(), diag::err_member_function_initialization) |
10992 | << Method->getDeclName() << Init->getSourceRange(); |
10993 | Method->setInvalidDecl(); |
10994 | return; |
10995 | } |
10996 | |
10997 | VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); |
10998 | if (!VDecl) { |
10999 | assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here" ) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 10999, __PRETTY_FUNCTION__)); |
11000 | Diag(RealDecl->getLocation(), diag::err_illegal_initializer); |
11001 | RealDecl->setInvalidDecl(); |
11002 | return; |
11003 | } |
11004 | |
11005 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. |
11006 | if (VDecl->getType()->isUndeducedType()) { |
11007 | // Attempt typo correction early so that the type of the init expression can |
11008 | // be deduced based on the chosen correction if the original init contains a |
11009 | // TypoExpr. |
11010 | ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); |
11011 | if (!Res.isUsable()) { |
11012 | RealDecl->setInvalidDecl(); |
11013 | return; |
11014 | } |
11015 | Init = Res.get(); |
11016 | |
11017 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) |
11018 | return; |
11019 | } |
11020 | |
11021 | // dllimport cannot be used on variable definitions. |
11022 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { |
11023 | Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); |
11024 | VDecl->setInvalidDecl(); |
11025 | return; |
11026 | } |
11027 | |
11028 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { |
11029 | // C99 6.7.8p5. C++ has no such restriction, but that is a defect. |
11030 | Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); |
11031 | VDecl->setInvalidDecl(); |
11032 | return; |
11033 | } |
11034 | |
11035 | if (!VDecl->getType()->isDependentType()) { |
11036 | // A definition must end up with a complete type, which means it must be |
11037 | // complete with the restriction that an array type might be completed by |
11038 | // the initializer; note that later code assumes this restriction. |
11039 | QualType BaseDeclType = VDecl->getType(); |
11040 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) |
11041 | BaseDeclType = Array->getElementType(); |
11042 | if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, |
11043 | diag::err_typecheck_decl_incomplete_type)) { |
11044 | RealDecl->setInvalidDecl(); |
11045 | return; |
11046 | } |
11047 | |
11048 | // The variable can not have an abstract class type. |
11049 | if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), |
11050 | diag::err_abstract_type_in_decl, |
11051 | AbstractVariableType)) |
11052 | VDecl->setInvalidDecl(); |
11053 | } |
11054 | |
11055 | // If adding the initializer will turn this declaration into a definition, |
11056 | // and we already have a definition for this variable, diagnose or otherwise |
11057 | // handle the situation. |
11058 | VarDecl *Def; |
11059 | if ((Def = VDecl->getDefinition()) && Def != VDecl && |
11060 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && |
11061 | !VDecl->isThisDeclarationADemotedDefinition() && |
11062 | checkVarDeclRedefinition(Def, VDecl)) |
11063 | return; |
11064 | |
11065 | if (getLangOpts().CPlusPlus) { |
11066 | // C++ [class.static.data]p4 |
11067 | // If a static data member is of const integral or const |
11068 | // enumeration type, its declaration in the class definition can |
11069 | // specify a constant-initializer which shall be an integral |
11070 | // constant expression (5.19). In that case, the member can appear |
11071 | // in integral constant expressions. The member shall still be |
11072 | // defined in a namespace scope if it is used in the program and the |
11073 | // namespace scope definition shall not contain an initializer. |
11074 | // |
11075 | // We already performed a redefinition check above, but for static |
11076 | // data members we also need to check whether there was an in-class |
11077 | // declaration with an initializer. |
11078 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { |
11079 | Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) |
11080 | << VDecl->getDeclName(); |
11081 | Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), |
11082 | diag::note_previous_initializer) |
11083 | << 0; |
11084 | return; |
11085 | } |
11086 | |
11087 | if (VDecl->hasLocalStorage()) |
11088 | setFunctionHasBranchProtectedScope(); |
11089 | |
11090 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { |
11091 | VDecl->setInvalidDecl(); |
11092 | return; |
11093 | } |
11094 | } |
11095 | |
11096 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside |
11097 | // a kernel function cannot be initialized." |
11098 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { |
11099 | Diag(VDecl->getLocation(), diag::err_local_cant_init); |
11100 | VDecl->setInvalidDecl(); |
11101 | return; |
11102 | } |
11103 | |
11104 | // Get the decls type and save a reference for later, since |
11105 | // CheckInitializerTypes may change it. |
11106 | QualType DclT = VDecl->getType(), SavT = DclT; |
11107 | |
11108 | // Expressions default to 'id' when we're in a debugger |
11109 | // and we are assigning it to a variable of Objective-C pointer type. |
11110 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && |
11111 | Init->getType() == Context.UnknownAnyTy) { |
11112 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); |
11113 | if (Result.isInvalid()) { |
11114 | VDecl->setInvalidDecl(); |
11115 | return; |
11116 | } |
11117 | Init = Result.get(); |
11118 | } |
11119 | |
11120 | // Perform the initialization. |
11121 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); |
11122 | if (!VDecl->isInvalidDecl()) { |
11123 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); |
11124 | InitializationKind Kind = InitializationKind::CreateForInit( |
11125 | VDecl->getLocation(), DirectInit, Init); |
11126 | |
11127 | MultiExprArg Args = Init; |
11128 | if (CXXDirectInit) |
11129 | Args = MultiExprArg(CXXDirectInit->getExprs(), |
11130 | CXXDirectInit->getNumExprs()); |
11131 | |
11132 | // Try to correct any TypoExprs in the initialization arguments. |
11133 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { |
11134 | ExprResult Res = CorrectDelayedTyposInExpr( |
11135 | Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { |
11136 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); |
11137 | return Init.Failed() ? ExprError() : E; |
11138 | }); |
11139 | if (Res.isInvalid()) { |
11140 | VDecl->setInvalidDecl(); |
11141 | } else if (Res.get() != Args[Idx]) { |
11142 | Args[Idx] = Res.get(); |
11143 | } |
11144 | } |
11145 | if (VDecl->isInvalidDecl()) |
11146 | return; |
11147 | |
11148 | InitializationSequence InitSeq(*this, Entity, Kind, Args, |
11149 | /*TopLevelOfInitList=*/false, |
11150 | /*TreatUnavailableAsInvalid=*/false); |
11151 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); |
11152 | if (Result.isInvalid()) { |
11153 | VDecl->setInvalidDecl(); |
11154 | return; |
11155 | } |
11156 | |
11157 | Init = Result.getAs<Expr>(); |
11158 | } |
11159 | |
11160 | // Check for self-references within variable initializers. |
11161 | // Variables declared within a function/method body (except for references) |
11162 | // are handled by a dataflow analysis. |
11163 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || |
11164 | VDecl->getType()->isReferenceType()) { |
11165 | CheckSelfReference(*this, RealDecl, Init, DirectInit); |
11166 | } |
11167 | |
11168 | // If the type changed, it means we had an incomplete type that was |
11169 | // completed by the initializer. For example: |
11170 | // int ary[] = { 1, 3, 5 }; |
11171 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. |
11172 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) |
11173 | VDecl->setType(DclT); |
11174 | |
11175 | if (!VDecl->isInvalidDecl()) { |
11176 | checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); |
11177 | |
11178 | if (VDecl->hasAttr<BlocksAttr>()) |
11179 | checkRetainCycles(VDecl, Init); |
11180 | |
11181 | // It is safe to assign a weak reference into a strong variable. |
11182 | // Although this code can still have problems: |
11183 | // id x = self.weakProp; |
11184 | // id y = self.weakProp; |
11185 | // we do not warn to warn spuriously when 'x' and 'y' are on separate |
11186 | // paths through the function. This should be revisited if |
11187 | // -Wrepeated-use-of-weak is made flow-sensitive. |
11188 | if (FunctionScopeInfo *FSI = getCurFunction()) |
11189 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || |
11190 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && |
11191 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, |
11192 | Init->getBeginLoc())) |
11193 | FSI->markSafeWeakUse(Init); |
11194 | } |
11195 | |
11196 | // The initialization is usually a full-expression. |
11197 | // |
11198 | // FIXME: If this is a braced initialization of an aggregate, it is not |
11199 | // an expression, and each individual field initializer is a separate |
11200 | // full-expression. For instance, in: |
11201 | // |
11202 | // struct Temp { ~Temp(); }; |
11203 | // struct S { S(Temp); }; |
11204 | // struct T { S a, b; } t = { Temp(), Temp() } |
11205 | // |
11206 | // we should destroy the first Temp before constructing the second. |
11207 | ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), |
11208 | false, |
11209 | VDecl->isConstexpr()); |
11210 | if (Result.isInvalid()) { |
11211 | VDecl->setInvalidDecl(); |
11212 | return; |
11213 | } |
11214 | Init = Result.get(); |
11215 | |
11216 | // Attach the initializer to the decl. |
11217 | VDecl->setInit(Init); |
11218 | |
11219 | if (VDecl->isLocalVarDecl()) { |
11220 | // Don't check the initializer if the declaration is malformed. |
11221 | if (VDecl->isInvalidDecl()) { |
11222 | // do nothing |
11223 | |
11224 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. |
11225 | // This is true even in OpenCL C++. |
11226 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { |
11227 | CheckForConstantInitializer(Init, DclT); |
11228 | |
11229 | // Otherwise, C++ does not restrict the initializer. |
11230 | } else if (getLangOpts().CPlusPlus) { |
11231 | // do nothing |
11232 | |
11233 | // C99 6.7.8p4: All the expressions in an initializer for an object that has |
11234 | // static storage duration shall be constant expressions or string literals. |
11235 | } else if (VDecl->getStorageClass() == SC_Static) { |
11236 | CheckForConstantInitializer(Init, DclT); |
11237 | |
11238 | // C89 is stricter than C99 for aggregate initializers. |
11239 | // C89 6.5.7p3: All the expressions [...] in an initializer list |
11240 | // for an object that has aggregate or union type shall be |
11241 | // constant expressions. |
11242 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && |
11243 | isa<InitListExpr>(Init)) { |
11244 | const Expr *Culprit; |
11245 | if (!Init->isConstantInitializer(Context, false, &Culprit)) { |
11246 | Diag(Culprit->getExprLoc(), |
11247 | diag::ext_aggregate_init_not_constant) |
11248 | << Culprit->getSourceRange(); |
11249 | } |
11250 | } |
11251 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && |
11252 | VDecl->getLexicalDeclContext()->isRecord()) { |
11253 | // This is an in-class initialization for a static data member, e.g., |
11254 | // |
11255 | // struct S { |
11256 | // static const int value = 17; |
11257 | // }; |
11258 | |
11259 | // C++ [class.mem]p4: |
11260 | // A member-declarator can contain a constant-initializer only |
11261 | // if it declares a static member (9.4) of const integral or |
11262 | // const enumeration type, see 9.4.2. |
11263 | // |
11264 | // C++11 [class.static.data]p3: |
11265 | // If a non-volatile non-inline const static data member is of integral |
11266 | // or enumeration type, its declaration in the class definition can |
11267 | // specify a brace-or-equal-initializer in which every initializer-clause |
11268 | // that is an assignment-expression is a constant expression. A static |
11269 | // data member of literal type can be declared in the class definition |
11270 | // with the constexpr specifier; if so, its declaration shall specify a |
11271 | // brace-or-equal-initializer in which every initializer-clause that is |
11272 | // an assignment-expression is a constant expression. |
11273 | |
11274 | // Do nothing on dependent types. |
11275 | if (DclT->isDependentType()) { |
11276 | |
11277 | // Allow any 'static constexpr' members, whether or not they are of literal |
11278 | // type. We separately check that every constexpr variable is of literal |
11279 | // type. |
11280 | } else if (VDecl->isConstexpr()) { |
11281 | |
11282 | // Require constness. |
11283 | } else if (!DclT.isConstQualified()) { |
11284 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) |
11285 | << Init->getSourceRange(); |
11286 | VDecl->setInvalidDecl(); |
11287 | |
11288 | // We allow integer constant expressions in all cases. |
11289 | } else if (DclT->isIntegralOrEnumerationType()) { |
11290 | // Check whether the expression is a constant expression. |
11291 | SourceLocation Loc; |
11292 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) |
11293 | // In C++11, a non-constexpr const static data member with an |
11294 | // in-class initializer cannot be volatile. |
11295 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); |
11296 | else if (Init->isValueDependent()) |
11297 | ; // Nothing to check. |
11298 | else if (Init->isIntegerConstantExpr(Context, &Loc)) |
11299 | ; // Ok, it's an ICE! |
11300 | else if (Init->getType()->isScopedEnumeralType() && |
11301 | Init->isCXX11ConstantExpr(Context)) |
11302 | ; // Ok, it is a scoped-enum constant expression. |
11303 | else if (Init->isEvaluatable(Context)) { |
11304 | // If we can constant fold the initializer through heroics, accept it, |
11305 | // but report this as a use of an extension for -pedantic. |
11306 | Diag(Loc, diag::ext_in_class_initializer_non_constant) |
11307 | << Init->getSourceRange(); |
11308 | } else { |
11309 | // Otherwise, this is some crazy unknown case. Report the issue at the |
11310 | // location provided by the isIntegerConstantExpr failed check. |
11311 | Diag(Loc, diag::err_in_class_initializer_non_constant) |
11312 | << Init->getSourceRange(); |
11313 | VDecl->setInvalidDecl(); |
11314 | } |
11315 | |
11316 | // We allow foldable floating-point constants as an extension. |
11317 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok |
11318 | // In C++98, this is a GNU extension. In C++11, it is not, but we support |
11319 | // it anyway and provide a fixit to add the 'constexpr'. |
11320 | if (getLangOpts().CPlusPlus11) { |
11321 | Diag(VDecl->getLocation(), |
11322 | diag::ext_in_class_initializer_float_type_cxx11) |
11323 | << DclT << Init->getSourceRange(); |
11324 | Diag(VDecl->getBeginLoc(), |
11325 | diag::note_in_class_initializer_float_type_cxx11) |
11326 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); |
11327 | } else { |
11328 | Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) |
11329 | << DclT << Init->getSourceRange(); |
11330 | |
11331 | if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { |
11332 | Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) |
11333 | << Init->getSourceRange(); |
11334 | VDecl->setInvalidDecl(); |
11335 | } |
11336 | } |
11337 | |
11338 | // Suggest adding 'constexpr' in C++11 for literal types. |
11339 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { |
11340 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) |
11341 | << DclT << Init->getSourceRange() |
11342 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); |
11343 | VDecl->setConstexpr(true); |
11344 | |
11345 | } else { |
11346 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) |
11347 | << DclT << Init->getSourceRange(); |
11348 | VDecl->setInvalidDecl(); |
11349 | } |
11350 | } else if (VDecl->isFileVarDecl()) { |
11351 | // In C, extern is typically used to avoid tentative definitions when |
11352 | // declaring variables in headers, but adding an intializer makes it a |
11353 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. |
11354 | // In C++, extern is often used to give implictly static const variables |
11355 | // external linkage, so don't warn in that case. If selectany is present, |
11356 | // this might be header code intended for C and C++ inclusion, so apply the |
11357 | // C++ rules. |
11358 | if (VDecl->getStorageClass() == SC_Extern && |
11359 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || |
11360 | !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && |
11361 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && |
11362 | !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) |
11363 | Diag(VDecl->getLocation(), diag::warn_extern_init); |
11364 | |
11365 | // C99 6.7.8p4. All file scoped initializers need to be constant. |
11366 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) |
11367 | CheckForConstantInitializer(Init, DclT); |
11368 | } |
11369 | |
11370 | // We will represent direct-initialization similarly to copy-initialization: |
11371 | // int x(1); -as-> int x = 1; |
11372 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); |
11373 | // |
11374 | // Clients that want to distinguish between the two forms, can check for |
11375 | // direct initializer using VarDecl::getInitStyle(). |
11376 | // A major benefit is that clients that don't particularly care about which |
11377 | // exactly form was it (like the CodeGen) can handle both cases without |
11378 | // special case code. |
11379 | |
11380 | // C++ 8.5p11: |
11381 | // The form of initialization (using parentheses or '=') is generally |
11382 | // insignificant, but does matter when the entity being initialized has a |
11383 | // class type. |
11384 | if (CXXDirectInit) { |
11385 | assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init." ) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 11385, __PRETTY_FUNCTION__)); |
11386 | VDecl->setInitStyle(VarDecl::CallInit); |
11387 | } else if (DirectInit) { |
11388 | // This must be list-initialization. No other way is direct-initialization. |
11389 | VDecl->setInitStyle(VarDecl::ListInit); |
11390 | } |
11391 | |
11392 | CheckCompleteVariableDeclaration(VDecl); |
11393 | } |
11394 | |
11395 | /// ActOnInitializerError - Given that there was an error parsing an |
11396 | /// initializer for the given declaration, try to return to some form |
11397 | /// of sanity. |
11398 | void Sema::ActOnInitializerError(Decl *D) { |
11399 | // Our main concern here is re-establishing invariants like "a |
11400 | // variable's type is either dependent or complete". |
11401 | if (!D || D->isInvalidDecl()) return; |
11402 | |
11403 | VarDecl *VD = dyn_cast<VarDecl>(D); |
11404 | if (!VD) return; |
11405 | |
11406 | // Bindings are not usable if we can't make sense of the initializer. |
11407 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) |
11408 | for (auto *BD : DD->bindings()) |
11409 | BD->setInvalidDecl(); |
11410 | |
11411 | // Auto types are meaningless if we can't make sense of the initializer. |
11412 | if (ParsingInitForAutoVars.count(D)) { |
11413 | D->setInvalidDecl(); |
11414 | return; |
11415 | } |
11416 | |
11417 | QualType Ty = VD->getType(); |
11418 | if (Ty->isDependentType()) return; |
11419 | |
11420 | // Require a complete type. |
11421 | if (RequireCompleteType(VD->getLocation(), |
11422 | Context.getBaseElementType(Ty), |
11423 | diag::err_typecheck_decl_incomplete_type)) { |
11424 | VD->setInvalidDecl(); |
11425 | return; |
11426 | } |
11427 | |
11428 | // Require a non-abstract type. |
11429 | if (RequireNonAbstractType(VD->getLocation(), Ty, |
11430 | diag::err_abstract_type_in_decl, |
11431 | AbstractVariableType)) { |
11432 | VD->setInvalidDecl(); |
11433 | return; |
11434 | } |
11435 | |
11436 | // Don't bother complaining about constructors or destructors, |
11437 | // though. |
11438 | } |
11439 | |
11440 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { |
11441 | // If there is no declaration, there was an error parsing it. Just ignore it. |
11442 | if (!RealDecl) |
11443 | return; |
11444 | |
11445 | if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { |
11446 | QualType Type = Var->getType(); |
11447 | |
11448 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. |
11449 | if (isa<DecompositionDecl>(RealDecl)) { |
11450 | Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; |
11451 | Var->setInvalidDecl(); |
11452 | return; |
11453 | } |
11454 | |
11455 | if (Type->isUndeducedType() && |
11456 | DeduceVariableDeclarationType(Var, false, nullptr)) |
11457 | return; |
11458 | |
11459 | // C++11 [class.static.data]p3: A static data member can be declared with |
11460 | // the constexpr specifier; if so, its declaration shall specify |
11461 | // a brace-or-equal-initializer. |
11462 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to |
11463 | // the definition of a variable [...] or the declaration of a static data |
11464 | // member. |
11465 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && |
11466 | !Var->isThisDeclarationADemotedDefinition()) { |
11467 | if (Var->isStaticDataMember()) { |
11468 | // C++1z removes the relevant rule; the in-class declaration is always |
11469 | // a definition there. |
11470 | if (!getLangOpts().CPlusPlus17) { |
11471 | Diag(Var->getLocation(), |
11472 | diag::err_constexpr_static_mem_var_requires_init) |
11473 | << Var->getDeclName(); |
11474 | Var->setInvalidDecl(); |
11475 | return; |
11476 | } |
11477 | } else { |
11478 | Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); |
11479 | Var->setInvalidDecl(); |
11480 | return; |
11481 | } |
11482 | } |
11483 | |
11484 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must |
11485 | // be initialized. |
11486 | if (!Var->isInvalidDecl() && |
11487 | Var->getType().getAddressSpace() == LangAS::opencl_constant && |
11488 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { |
11489 | Diag(Var->getLocation(), diag::err_opencl_constant_no_init); |
11490 | Var->setInvalidDecl(); |
11491 | return; |
11492 | } |
11493 | |
11494 | switch (Var->isThisDeclarationADefinition()) { |
11495 | case VarDecl::Definition: |
11496 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) |
11497 | break; |
11498 | |
11499 | // We have an out-of-line definition of a static data member |
11500 | // that has an in-class initializer, so we type-check this like |
11501 | // a declaration. |
11502 | // |
11503 | LLVM_FALLTHROUGH[[clang::fallthrough]]; |
11504 | |
11505 | case VarDecl::DeclarationOnly: |
11506 | // It's only a declaration. |
11507 | |
11508 | // Block scope. C99 6.7p7: If an identifier for an object is |
11509 | // declared with no linkage (C99 6.2.2p6), the type for the |
11510 | // object shall be complete. |
11511 | if (!Type->isDependentType() && Var->isLocalVarDecl() && |
11512 | !Var->hasLinkage() && !Var->isInvalidDecl() && |
11513 | RequireCompleteType(Var->getLocation(), Type, |
11514 | diag::err_typecheck_decl_incomplete_type)) |
11515 | Var->setInvalidDecl(); |
11516 | |
11517 | // Make sure that the type is not abstract. |
11518 | if (!Type->isDependentType() && !Var->isInvalidDecl() && |
11519 | RequireNonAbstractType(Var->getLocation(), Type, |
11520 | diag::err_abstract_type_in_decl, |
11521 | AbstractVariableType)) |
11522 | Var->setInvalidDecl(); |
11523 | if (!Type->isDependentType() && !Var->isInvalidDecl() && |
11524 | Var->getStorageClass() == SC_PrivateExtern) { |
11525 | Diag(Var->getLocation(), diag::warn_private_extern); |
11526 | Diag(Var->getLocation(), diag::note_private_extern); |
11527 | } |
11528 | |
11529 | return; |
11530 | |
11531 | case VarDecl::TentativeDefinition: |
11532 | // File scope. C99 6.9.2p2: A declaration of an identifier for an |
11533 | // object that has file scope without an initializer, and without a |
11534 | // storage-class specifier or with the storage-class specifier "static", |
11535 | // constitutes a tentative definition. Note: A tentative definition with |
11536 | // external linkage is valid (C99 6.2.2p5). |
11537 | if (!Var->isInvalidDecl()) { |
11538 | if (const IncompleteArrayType *ArrayT |
11539 | = Context.getAsIncompleteArrayType(Type)) { |
11540 | if (RequireCompleteType(Var->getLocation(), |
11541 | ArrayT->getElementType(), |
11542 | diag::err_illegal_decl_array_incomplete_type)) |
11543 | Var->setInvalidDecl(); |
11544 | } else if (Var->getStorageClass() == SC_Static) { |
11545 | // C99 6.9.2p3: If the declaration of an identifier for an object is |
11546 | // a tentative definition and has internal linkage (C99 6.2.2p3), the |
11547 | // declared type shall not be an incomplete type. |
11548 | // NOTE: code such as the following |
11549 | // static struct s; |
11550 | // struct s { int a; }; |
11551 | // is accepted by gcc. Hence here we issue a warning instead of |
11552 | // an error and we do not invalidate the static declaration. |
11553 | // NOTE: to avoid multiple warnings, only check the first declaration. |
11554 | if (Var->isFirstDecl()) |
11555 | RequireCompleteType(Var->getLocation(), Type, |
11556 | diag::ext_typecheck_decl_incomplete_type); |
11557 | } |
11558 | } |
11559 | |
11560 | // Record the tentative definition; we're done. |
11561 | if (!Var->isInvalidDecl()) |
11562 | TentativeDefinitions.push_back(Var); |
11563 | return; |
11564 | } |
11565 | |
11566 | // Provide a specific diagnostic for uninitialized variable |
11567 | // definitions with incomplete array type. |
11568 | if (Type->isIncompleteArrayType()) { |
11569 | Diag(Var->getLocation(), |
11570 | diag::err_typecheck_incomplete_array_needs_initializer); |
11571 | Var->setInvalidDecl(); |
11572 | return; |
11573 | } |
11574 | |
11575 | // Provide a specific diagnostic for uninitialized variable |
11576 | // definitions with reference type. |
11577 | if (Type->isReferenceType()) { |
11578 | Diag(Var->getLocation(), diag::err_reference_var_requires_init) |
11579 | << Var->getDeclName() |
11580 | << SourceRange(Var->getLocation(), Var->getLocation()); |
11581 | Var->setInvalidDecl(); |
11582 | return; |
11583 | } |
11584 | |
11585 | // Do not attempt to type-check the default initializer for a |
11586 | // variable with dependent type. |
11587 | if (Type->isDependentType()) |
11588 | return; |
11589 | |
11590 | if (Var->isInvalidDecl()) |
11591 | return; |
11592 | |
11593 | if (!Var->hasAttr<AliasAttr>()) { |
11594 | if (RequireCompleteType(Var->getLocation(), |
11595 | Context.getBaseElementType(Type), |
11596 | diag::err_typecheck_decl_incomplete_type)) { |
11597 | Var->setInvalidDecl(); |
11598 | return; |
11599 | } |
11600 | } else { |
11601 | return; |
11602 | } |
11603 | |
11604 | // The variable can not have an abstract class type. |
11605 | if (RequireNonAbstractType(Var->getLocation(), Type, |
11606 | diag::err_abstract_type_in_decl, |
11607 | AbstractVariableType)) { |
11608 | Var->setInvalidDecl(); |
11609 | return; |
11610 | } |
11611 | |
11612 | // Check for jumps past the implicit initializer. C++0x |
11613 | // clarifies that this applies to a "variable with automatic |
11614 | // storage duration", not a "local variable". |
11615 | // C++11 [stmt.dcl]p3 |
11616 | // A program that jumps from a point where a variable with automatic |
11617 | // storage duration is not in scope to a point where it is in scope is |
11618 | // ill-formed unless the variable has scalar type, class type with a |
11619 | // trivial default constructor and a trivial destructor, a cv-qualified |
11620 | // version of one of these types, or an array of one of the preceding |
11621 | // types and is declared without an initializer. |
11622 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { |
11623 | if (const RecordType *Record |
11624 | = Context.getBaseElementType(Type)->getAs<RecordType>()) { |
11625 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); |
11626 | // Mark the function (if we're in one) for further checking even if the |
11627 | // looser rules of C++11 do not require such checks, so that we can |
11628 | // diagnose incompatibilities with C++98. |
11629 | if (!CXXRecord->isPOD()) |
11630 | setFunctionHasBranchProtectedScope(); |
11631 | } |
11632 | } |
11633 | |
11634 | // C++03 [dcl.init]p9: |
11635 | // If no initializer is specified for an object, and the |
11636 | // object is of (possibly cv-qualified) non-POD class type (or |
11637 | // array thereof), the object shall be default-initialized; if |
11638 | // the object is of const-qualified type, the underlying class |
11639 | // type shall have a user-declared default |
11640 | // constructor. Otherwise, if no initializer is specified for |
11641 | // a non- static object, the object and its subobjects, if |
11642 | // any, have an indeterminate initial value); if the object |
11643 | // or any of its subobjects are of const-qualified type, the |
11644 | // program is ill-formed. |
11645 | // C++0x [dcl.init]p11: |
11646 | // If no initializer is specified for an object, the object is |
11647 | // default-initialized; [...]. |
11648 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); |
11649 | InitializationKind Kind |
11650 | = InitializationKind::CreateDefault(Var->getLocation()); |
11651 | |
11652 | InitializationSequence InitSeq(*this, Entity, Kind, None); |
11653 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); |
11654 | if (Init.isInvalid()) |
11655 | Var->setInvalidDecl(); |
11656 | else if (Init.get()) { |
11657 | Var->setInit(MaybeCreateExprWithCleanups(Init.get())); |
11658 | // This is important for template substitution. |
11659 | Var->setInitStyle(VarDecl::CallInit); |
11660 | } |
11661 | |
11662 | CheckCompleteVariableDeclaration(Var); |
11663 | } |
11664 | } |
11665 | |
11666 | void Sema::ActOnCXXForRangeDecl(Decl *D) { |
11667 | // If there is no declaration, there was an error parsing it. Ignore it. |
11668 | if (!D) |
11669 | return; |
11670 | |
11671 | VarDecl *VD = dyn_cast<VarDecl>(D); |
11672 | if (!VD) { |
11673 | Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); |
11674 | D->setInvalidDecl(); |
11675 | return; |
11676 | } |
11677 | |
11678 | VD->setCXXForRangeDecl(true); |
11679 | |
11680 | // for-range-declaration cannot be given a storage class specifier. |
11681 | int Error = -1; |
11682 | switch (VD->getStorageClass()) { |
11683 | case SC_None: |
11684 | break; |
11685 | case SC_Extern: |
11686 | Error = 0; |
11687 | break; |
11688 | case SC_Static: |
11689 | Error = 1; |
11690 | break; |
11691 | case SC_PrivateExtern: |
11692 | Error = 2; |
11693 | break; |
11694 | case SC_Auto: |
11695 | Error = 3; |
11696 | break; |
11697 | case SC_Register: |
11698 | Error = 4; |
11699 | break; |
11700 | } |
11701 | if (Error != -1) { |
11702 | Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) |
11703 | << VD->getDeclName() << Error; |
11704 | D->setInvalidDecl(); |
11705 | } |
11706 | } |
11707 | |
11708 | StmtResult |
11709 | Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, |
11710 | IdentifierInfo *Ident, |
11711 | ParsedAttributes &Attrs, |
11712 | SourceLocation AttrEnd) { |
11713 | // C++1y [stmt.iter]p1: |
11714 | // A range-based for statement of the form |
11715 | // for ( for-range-identifier : for-range-initializer ) statement |
11716 | // is equivalent to |
11717 | // for ( auto&& for-range-identifier : for-range-initializer ) statement |
11718 | DeclSpec DS(Attrs.getPool().getFactory()); |
11719 | |
11720 | const char *PrevSpec; |
11721 | unsigned DiagID; |
11722 | DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, |
11723 | getPrintingPolicy()); |
11724 | |
11725 | Declarator D(DS, DeclaratorContext::ForContext); |
11726 | D.SetIdentifier(Ident, IdentLoc); |
11727 | D.takeAttributes(Attrs, AttrEnd); |
11728 | |
11729 | ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); |
11730 | D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), |
11731 | IdentLoc); |
11732 | Decl *Var = ActOnDeclarator(S, D); |
11733 | cast<VarDecl>(Var)->setCXXForRangeDecl(true); |
11734 | FinalizeDeclaration(Var); |
11735 | return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, |
11736 | AttrEnd.isValid() ? AttrEnd : IdentLoc); |
11737 | } |
11738 | |
11739 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { |
11740 | if (var->isInvalidDecl()) return; |
11741 | |
11742 | if (getLangOpts().OpenCL) { |
11743 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an |
11744 | // initialiser |
11745 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && |
11746 | !var->hasInit()) { |
11747 | Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) |
11748 | << 1 /*Init*/; |
11749 | var->setInvalidDecl(); |
11750 | return; |
11751 | } |
11752 | } |
11753 | |
11754 | // In Objective-C, don't allow jumps past the implicit initialization of a |
11755 | // local retaining variable. |
11756 | if (getLangOpts().ObjC && |
11757 | var->hasLocalStorage()) { |
11758 | switch (var->getType().getObjCLifetime()) { |
11759 | case Qualifiers::OCL_None: |
11760 | case Qualifiers::OCL_ExplicitNone: |
11761 | case Qualifiers::OCL_Autoreleasing: |
11762 | break; |
11763 | |
11764 | case Qualifiers::OCL_Weak: |
11765 | case Qualifiers::OCL_Strong: |
11766 | setFunctionHasBranchProtectedScope(); |
11767 | break; |
11768 | } |
11769 | } |
11770 | |
11771 | if (var->hasLocalStorage() && |
11772 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) |
11773 | setFunctionHasBranchProtectedScope(); |
11774 | |
11775 | // Warn about externally-visible variables being defined without a |
11776 | // prior declaration. We only want to do this for global |
11777 | // declarations, but we also specifically need to avoid doing it for |
11778 | // class members because the linkage of an anonymous class can |
11779 | // change if it's later given a typedef name. |
11780 | if (var->isThisDeclarationADefinition() && |
11781 | var->getDeclContext()->getRedeclContext()->isFileContext() && |
11782 | var->isExternallyVisible() && var->hasLinkage() && |
11783 | !var->isInline() && !var->getDescribedVarTemplate() && |
11784 | !isTemplateInstantiation(var->getTemplateSpecializationKind()) && |
11785 | !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, |
11786 | var->getLocation())) { |
11787 | // Find a previous declaration that's not a definition. |
11788 | VarDecl *prev = var->getPreviousDecl(); |
11789 | while (prev && prev->isThisDeclarationADefinition()) |
11790 | prev = prev->getPreviousDecl(); |
11791 | |
11792 | if (!prev) |
11793 | Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; |
11794 | } |
11795 | |
11796 | // Cache the result of checking for constant initialization. |
11797 | Optional<bool> CacheHasConstInit; |
11798 | const Expr *CacheCulprit; |
11799 | auto checkConstInit = [&]() mutable { |
11800 | if (!CacheHasConstInit) |
11801 | CacheHasConstInit = var->getInit()->isConstantInitializer( |
11802 | Context, var->getType()->isReferenceType(), &CacheCulprit); |
11803 | return *CacheHasConstInit; |
11804 | }; |
11805 | |
11806 | if (var->getTLSKind() == VarDecl::TLS_Static) { |
11807 | if (var->getType().isDestructedType()) { |
11808 | // GNU C++98 edits for __thread, [basic.start.term]p3: |
11809 | // The type of an object with thread storage duration shall not |
11810 | // have a non-trivial destructor. |
11811 | Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); |
11812 | if (getLangOpts().CPlusPlus11) |
11813 | Diag(var->getLocation(), diag::note_use_thread_local); |
11814 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { |
11815 | if (!checkConstInit()) { |
11816 | // GNU C++98 edits for __thread, [basic.start.init]p4: |
11817 | // An object of thread storage duration shall not require dynamic |
11818 | // initialization. |
11819 | // FIXME: Need strict checking here. |
11820 | Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) |
11821 | << CacheCulprit->getSourceRange(); |
11822 | if (getLangOpts().CPlusPlus11) |
11823 | Diag(var->getLocation(), diag::note_use_thread_local); |
11824 | } |
11825 | } |
11826 | } |
11827 | |
11828 | // Apply section attributes and pragmas to global variables. |
11829 | bool GlobalStorage = var->hasGlobalStorage(); |
11830 | if (GlobalStorage && var->isThisDeclarationADefinition() && |
11831 | !inTemplateInstantiation()) { |
11832 | PragmaStack<StringLiteral *> *Stack = nullptr; |
11833 | int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; |
11834 | if (var->getType().isConstQualified()) |
11835 | Stack = &ConstSegStack; |
11836 | else if (!var->getInit()) { |
11837 | Stack = &BSSSegStack; |
11838 | SectionFlags |= ASTContext::PSF_Write; |
11839 | } else { |
11840 | Stack = &DataSegStack; |
11841 | SectionFlags |= ASTContext::PSF_Write; |
11842 | } |
11843 | if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { |
11844 | var->addAttr(SectionAttr::CreateImplicit( |
11845 | Context, SectionAttr::Declspec_allocate, |
11846 | Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); |
11847 | } |
11848 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) |
11849 | if (UnifySection(SA->getName(), SectionFlags, var)) |
11850 | var->dropAttr<SectionAttr>(); |
11851 | |
11852 | // Apply the init_seg attribute if this has an initializer. If the |
11853 | // initializer turns out to not be dynamic, we'll end up ignoring this |
11854 | // attribute. |
11855 | if (CurInitSeg && var->getInit()) |
11856 | var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), |
11857 | CurInitSegLoc)); |
11858 | } |
11859 | |
11860 | // All the following checks are C++ only. |
11861 | if (!getLangOpts().CPlusPlus) { |
11862 | // If this variable must be emitted, add it as an initializer for the |
11863 | // current module. |
11864 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) |
11865 | Context.addModuleInitializer(ModuleScopes.back().Module, var); |
11866 | return; |
11867 | } |
11868 | |
11869 | if (auto *DD = dyn_cast<DecompositionDecl>(var)) |
11870 | CheckCompleteDecompositionDeclaration(DD); |
11871 | |
11872 | QualType type = var->getType(); |
11873 | if (type->isDependentType()) return; |
11874 | |
11875 | if (var->hasAttr<BlocksAttr>()) |
11876 | getCurFunction()->addByrefBlockVar(var); |
11877 | |
11878 | Expr *Init = var->getInit(); |
11879 | bool IsGlobal = GlobalStorage && !var->isStaticLocal(); |
11880 | QualType baseType = Context.getBaseElementType(type); |
11881 | |
11882 | if (Init && !Init->isValueDependent()) { |
11883 | if (var->isConstexpr()) { |
11884 | SmallVector<PartialDiagnosticAt, 8> Notes; |
11885 | if (!var->evaluateValue(Notes) || !var->isInitICE()) { |
11886 | SourceLocation DiagLoc = var->getLocation(); |
11887 | // If the note doesn't add any useful information other than a source |
11888 | // location, fold it into the primary diagnostic. |
11889 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == |
11890 | diag::note_invalid_subexpr_in_const_expr) { |
11891 | DiagLoc = Notes[0].first; |
11892 | Notes.clear(); |
11893 | } |
11894 | Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) |
11895 | << var << Init->getSourceRange(); |
11896 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) |
11897 | Diag(Notes[I].first, Notes[I].second); |
11898 | } |
11899 | } else if (var->isUsableInConstantExpressions(Context)) { |
11900 | // Check whether the initializer of a const variable of integral or |
11901 | // enumeration type is an ICE now, since we can't tell whether it was |
11902 | // initialized by a constant expression if we check later. |
11903 | var->checkInitIsICE(); |
11904 | } |
11905 | |
11906 | // Don't emit further diagnostics about constexpr globals since they |
11907 | // were just diagnosed. |
11908 | if (!var->isConstexpr() && GlobalStorage && |
11909 | var->hasAttr<RequireConstantInitAttr>()) { |
11910 | // FIXME: Need strict checking in C++03 here. |
11911 | bool DiagErr = getLangOpts().CPlusPlus11 |
11912 | ? !var->checkInitIsICE() : !checkConstInit(); |
11913 | if (DiagErr) { |
11914 | auto attr = var->getAttr<RequireConstantInitAttr>(); |
11915 | Diag(var->getLocation(), diag::err_require_constant_init_failed) |
11916 | << Init->getSourceRange(); |
11917 | Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) |
11918 | << attr->getRange(); |
11919 | if (getLangOpts().CPlusPlus11) { |
11920 | APValue Value; |
11921 | SmallVector<PartialDiagnosticAt, 8> Notes; |
11922 | Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); |
11923 | for (auto &it : Notes) |
11924 | Diag(it.first, it.second); |
11925 | } else { |
11926 | Diag(CacheCulprit->getExprLoc(), |
11927 | diag::note_invalid_subexpr_in_const_expr) |
11928 | << CacheCulprit->getSourceRange(); |
11929 | } |
11930 | } |
11931 | } |
11932 | else if (!var->isConstexpr() && IsGlobal && |
11933 | !getDiagnostics().isIgnored(diag::warn_global_constructor, |
11934 | var->getLocation())) { |
11935 | // Warn about globals which don't have a constant initializer. Don't |
11936 | // warn about globals with a non-trivial destructor because we already |
11937 | // warned about them. |
11938 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); |
11939 | if (!(RD && !RD->hasTrivialDestructor())) { |
11940 | if (!checkConstInit()) |
11941 | Diag(var->getLocation(), diag::warn_global_constructor) |
11942 | << Init->getSourceRange(); |
11943 | } |
11944 | } |
11945 | } |
11946 | |
11947 | // Require the destructor. |
11948 | if (const RecordType *recordType = baseType->getAs<RecordType>()) |
11949 | FinalizeVarWithDestructor(var, recordType); |
11950 | |
11951 | // If this variable must be emitted, add it as an initializer for the current |
11952 | // module. |
11953 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) |
11954 | Context.addModuleInitializer(ModuleScopes.back().Module, var); |
11955 | } |
11956 | |
11957 | /// Determines if a variable's alignment is dependent. |
11958 | static bool hasDependentAlignment(VarDecl *VD) { |
11959 | if (VD->getType()->isDependentType()) |
11960 | return true; |
11961 | for (auto *I : VD->specific_attrs<AlignedAttr>()) |
11962 | if (I->isAlignmentDependent()) |
11963 | return true; |
11964 | return false; |
11965 | } |
11966 | |
11967 | /// Check if VD needs to be dllexport/dllimport due to being in a |
11968 | /// dllexport/import function. |
11969 | void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { |
11970 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 11970, __PRETTY_FUNCTION__)); |
11971 | |
11972 | auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); |
11973 | |
11974 | // Find outermost function when VD is in lambda function. |
11975 | while (FD && !getDLLAttr(FD) && |
11976 | !FD->hasAttr<DLLExportStaticLocalAttr>() && |
11977 | !FD->hasAttr<DLLImportStaticLocalAttr>()) { |
11978 | FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); |
11979 | } |
11980 | |
11981 | if (!FD) |
11982 | return; |
11983 | |
11984 | // Static locals inherit dll attributes from their function. |
11985 | if (Attr *A = getDLLAttr(FD)) { |
11986 | auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); |
11987 | NewAttr->setInherited(true); |
11988 | VD->addAttr(NewAttr); |
11989 | } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { |
11990 | auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(), |
11991 | getASTContext(), |
11992 | A->getSpellingListIndex()); |
11993 | NewAttr->setInherited(true); |
11994 | VD->addAttr(NewAttr); |
11995 | |
11996 | // Export this function to enforce exporting this static variable even |
11997 | // if it is not used in this compilation unit. |
11998 | if (!FD->hasAttr<DLLExportAttr>()) |
11999 | FD->addAttr(NewAttr); |
12000 | |
12001 | } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { |
12002 | auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(), |
12003 | getASTContext(), |
12004 | A->getSpellingListIndex()); |
12005 | NewAttr->setInherited(true); |
12006 | VD->addAttr(NewAttr); |
12007 | } |
12008 | } |
12009 | |
12010 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform |
12011 | /// any semantic actions necessary after any initializer has been attached. |
12012 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { |
12013 | // Note that we are no longer parsing the initializer for this declaration. |
12014 | ParsingInitForAutoVars.erase(ThisDecl); |
12015 | |
12016 | VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); |
12017 | if (!VD) |
12018 | return; |
12019 | |
12020 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active |
12021 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && |
12022 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { |
12023 | if (PragmaClangBSSSection.Valid) |
12024 | VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, |
12025 | PragmaClangBSSSection.SectionName, |
12026 | PragmaClangBSSSection.PragmaLocation)); |
12027 | if (PragmaClangDataSection.Valid) |
12028 | VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, |
12029 | PragmaClangDataSection.SectionName, |
12030 | PragmaClangDataSection.PragmaLocation)); |
12031 | if (PragmaClangRodataSection.Valid) |
12032 | VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, |
12033 | PragmaClangRodataSection.SectionName, |
12034 | PragmaClangRodataSection.PragmaLocation)); |
12035 | } |
12036 | |
12037 | if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { |
12038 | for (auto *BD : DD->bindings()) { |
12039 | FinalizeDeclaration(BD); |
12040 | } |
12041 | } |
12042 | |
12043 | checkAttributesAfterMerging(*this, *VD); |
12044 | |
12045 | // Perform TLS alignment check here after attributes attached to the variable |
12046 | // which may affect the alignment have been processed. Only perform the check |
12047 | // if the target has a maximum TLS alignment (zero means no constraints). |
12048 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { |
12049 | // Protect the check so that it's not performed on dependent types and |
12050 | // dependent alignments (we can't determine the alignment in that case). |
12051 | if (VD->getTLSKind() && !hasDependentAlignment(VD) && |
12052 | !VD->isInvalidDecl()) { |
12053 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); |
12054 | if (Context.getDeclAlign(VD) > MaxAlignChars) { |
12055 | Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) |
12056 | << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD |
12057 | << (unsigned)MaxAlignChars.getQuantity(); |
12058 | } |
12059 | } |
12060 | } |
12061 | |
12062 | if (VD->isStaticLocal()) { |
12063 | CheckStaticLocalForDllExport(VD); |
12064 | |
12065 | if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { |
12066 | // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ |
12067 | // function, only __shared__ variables or variables without any device |
12068 | // memory qualifiers may be declared with static storage class. |
12069 | // Note: It is unclear how a function-scope non-const static variable |
12070 | // without device memory qualifier is implemented, therefore only static |
12071 | // const variable without device memory qualifier is allowed. |
12072 | [&]() { |
12073 | if (!getLangOpts().CUDA) |
12074 | return; |
12075 | if (VD->hasAttr<CUDASharedAttr>()) |
12076 | return; |
12077 | if (VD->getType().isConstQualified() && |
12078 | !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) |
12079 | return; |
12080 | if (CUDADiagIfDeviceCode(VD->getLocation(), |
12081 | diag::err_device_static_local_var) |
12082 | << CurrentCUDATarget()) |
12083 | VD->setInvalidDecl(); |
12084 | }(); |
12085 | } |
12086 | } |
12087 | |
12088 | // Perform check for initializers of device-side global variables. |
12089 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA |
12090 | // 7.5). We must also apply the same checks to all __shared__ |
12091 | // variables whether they are local or not. CUDA also allows |
12092 | // constant initializers for __constant__ and __device__ variables. |
12093 | if (getLangOpts().CUDA) |
12094 | checkAllowedCUDAInitializer(VD); |
12095 | |
12096 | // Grab the dllimport or dllexport attribute off of the VarDecl. |
12097 | const InheritableAttr *DLLAttr = getDLLAttr(VD); |
12098 | |
12099 | // Imported static data members cannot be defined out-of-line. |
12100 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { |
12101 | if (VD->isStaticDataMember() && VD->isOutOfLine() && |
12102 | VD->isThisDeclarationADefinition()) { |
12103 | // We allow definitions of dllimport class template static data members |
12104 | // with a warning. |
12105 | CXXRecordDecl *Context = |
12106 | cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); |
12107 | bool IsClassTemplateMember = |
12108 | isa<ClassTemplatePartialSpecializationDecl>(Context) || |
12109 | Context->getDescribedClassTemplate(); |
12110 | |
12111 | Diag(VD->getLocation(), |
12112 | IsClassTemplateMember |
12113 | ? diag::warn_attribute_dllimport_static_field_definition |
12114 | : diag::err_attribute_dllimport_static_field_definition); |
12115 | Diag(IA->getLocation(), diag::note_attribute); |
12116 | if (!IsClassTemplateMember) |
12117 | VD->setInvalidDecl(); |
12118 | } |
12119 | } |
12120 | |
12121 | // dllimport/dllexport variables cannot be thread local, their TLS index |
12122 | // isn't exported with the variable. |
12123 | if (DLLAttr && VD->getTLSKind()) { |
12124 | auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); |
12125 | if (F && getDLLAttr(F)) { |
12126 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12126, __PRETTY_FUNCTION__)); |
12127 | // But if this is a static local in a dlimport/dllexport function, the |
12128 | // function will never be inlined, which means the var would never be |
12129 | // imported, so having it marked import/export is safe. |
12130 | } else { |
12131 | Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD |
12132 | << DLLAttr; |
12133 | VD->setInvalidDecl(); |
12134 | } |
12135 | } |
12136 | |
12137 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { |
12138 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { |
12139 | Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; |
12140 | VD->dropAttr<UsedAttr>(); |
12141 | } |
12142 | } |
12143 | |
12144 | const DeclContext *DC = VD->getDeclContext(); |
12145 | // If there's a #pragma GCC visibility in scope, and this isn't a class |
12146 | // member, set the visibility of this variable. |
12147 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) |
12148 | AddPushedVisibilityAttribute(VD); |
12149 | |
12150 | // FIXME: Warn on unused var template partial specializations. |
12151 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) |
12152 | MarkUnusedFileScopedDecl(VD); |
12153 | |
12154 | // Now we have parsed the initializer and can update the table of magic |
12155 | // tag values. |
12156 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || |
12157 | !VD->getType()->isIntegralOrEnumerationType()) |
12158 | return; |
12159 | |
12160 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { |
12161 | const Expr *MagicValueExpr = VD->getInit(); |
12162 | if (!MagicValueExpr) { |
12163 | continue; |
12164 | } |
12165 | llvm::APSInt MagicValueInt; |
12166 | if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { |
12167 | Diag(I->getRange().getBegin(), |
12168 | diag::err_type_tag_for_datatype_not_ice) |
12169 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); |
12170 | continue; |
12171 | } |
12172 | if (MagicValueInt.getActiveBits() > 64) { |
12173 | Diag(I->getRange().getBegin(), |
12174 | diag::err_type_tag_for_datatype_too_large) |
12175 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); |
12176 | continue; |
12177 | } |
12178 | uint64_t MagicValue = MagicValueInt.getZExtValue(); |
12179 | RegisterTypeTagForDatatype(I->getArgumentKind(), |
12180 | MagicValue, |
12181 | I->getMatchingCType(), |
12182 | I->getLayoutCompatible(), |
12183 | I->getMustBeNull()); |
12184 | } |
12185 | } |
12186 | |
12187 | static bool hasDeducedAuto(DeclaratorDecl *DD) { |
12188 | auto *VD = dyn_cast<VarDecl>(DD); |
12189 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); |
12190 | } |
12191 | |
12192 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, |
12193 | ArrayRef<Decl *> Group) { |
12194 | SmallVector<Decl*, 8> Decls; |
12195 | |
12196 | if (DS.isTypeSpecOwned()) |
12197 | Decls.push_back(DS.getRepAsDecl()); |
12198 | |
12199 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; |
12200 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; |
12201 | bool DiagnosedMultipleDecomps = false; |
12202 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; |
12203 | bool DiagnosedNonDeducedAuto = false; |
12204 | |
12205 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { |
12206 | if (Decl *D = Group[i]) { |
12207 | // For declarators, there are some additional syntactic-ish checks we need |
12208 | // to perform. |
12209 | if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { |
12210 | if (!FirstDeclaratorInGroup) |
12211 | FirstDeclaratorInGroup = DD; |
12212 | if (!FirstDecompDeclaratorInGroup) |
12213 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); |
12214 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && |
12215 | !hasDeducedAuto(DD)) |
12216 | FirstNonDeducedAutoInGroup = DD; |
12217 | |
12218 | if (FirstDeclaratorInGroup != DD) { |
12219 | // A decomposition declaration cannot be combined with any other |
12220 | // declaration in the same group. |
12221 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { |
12222 | Diag(FirstDecompDeclaratorInGroup->getLocation(), |
12223 | diag::err_decomp_decl_not_alone) |
12224 | << FirstDeclaratorInGroup->getSourceRange() |
12225 | << DD->getSourceRange(); |
12226 | DiagnosedMultipleDecomps = true; |
12227 | } |
12228 | |
12229 | // A declarator that uses 'auto' in any way other than to declare a |
12230 | // variable with a deduced type cannot be combined with any other |
12231 | // declarator in the same group. |
12232 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { |
12233 | Diag(FirstNonDeducedAutoInGroup->getLocation(), |
12234 | diag::err_auto_non_deduced_not_alone) |
12235 | << FirstNonDeducedAutoInGroup->getType() |
12236 | ->hasAutoForTrailingReturnType() |
12237 | << FirstDeclaratorInGroup->getSourceRange() |
12238 | << DD->getSourceRange(); |
12239 | DiagnosedNonDeducedAuto = true; |
12240 | } |
12241 | } |
12242 | } |
12243 | |
12244 | Decls.push_back(D); |
12245 | } |
12246 | } |
12247 | |
12248 | if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { |
12249 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { |
12250 | handleTagNumbering(Tag, S); |
12251 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && |
12252 | getLangOpts().CPlusPlus) |
12253 | Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); |
12254 | } |
12255 | } |
12256 | |
12257 | return BuildDeclaratorGroup(Decls); |
12258 | } |
12259 | |
12260 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration |
12261 | /// group, performing any necessary semantic checking. |
12262 | Sema::DeclGroupPtrTy |
12263 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { |
12264 | // C++14 [dcl.spec.auto]p7: (DR1347) |
12265 | // If the type that replaces the placeholder type is not the same in each |
12266 | // deduction, the program is ill-formed. |
12267 | if (Group.size() > 1) { |
12268 | QualType Deduced; |
12269 | VarDecl *DeducedDecl = nullptr; |
12270 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { |
12271 | VarDecl *D = dyn_cast<VarDecl>(Group[i]); |
12272 | if (!D || D->isInvalidDecl()) |
12273 | break; |
12274 | DeducedType *DT = D->getType()->getContainedDeducedType(); |
12275 | if (!DT || DT->getDeducedType().isNull()) |
12276 | continue; |
12277 | if (Deduced.isNull()) { |
12278 | Deduced = DT->getDeducedType(); |
12279 | DeducedDecl = D; |
12280 | } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { |
12281 | auto *AT = dyn_cast<AutoType>(DT); |
12282 | Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), |
12283 | diag::err_auto_different_deductions) |
12284 | << (AT ? (unsigned)AT->getKeyword() : 3) |
12285 | << Deduced << DeducedDecl->getDeclName() |
12286 | << DT->getDeducedType() << D->getDeclName() |
12287 | << DeducedDecl->getInit()->getSourceRange() |
12288 | << D->getInit()->getSourceRange(); |
12289 | D->setInvalidDecl(); |
12290 | break; |
12291 | } |
12292 | } |
12293 | } |
12294 | |
12295 | ActOnDocumentableDecls(Group); |
12296 | |
12297 | return DeclGroupPtrTy::make( |
12298 | DeclGroupRef::Create(Context, Group.data(), Group.size())); |
12299 | } |
12300 | |
12301 | void Sema::ActOnDocumentableDecl(Decl *D) { |
12302 | ActOnDocumentableDecls(D); |
12303 | } |
12304 | |
12305 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { |
12306 | // Don't parse the comment if Doxygen diagnostics are ignored. |
12307 | if (Group.empty() || !Group[0]) |
12308 | return; |
12309 | |
12310 | if (Diags.isIgnored(diag::warn_doc_param_not_found, |
12311 | Group[0]->getLocation()) && |
12312 | Diags.isIgnored(diag::warn_unknown_comment_command_name, |
12313 | Group[0]->getLocation())) |
12314 | return; |
12315 | |
12316 | if (Group.size() >= 2) { |
12317 | // This is a decl group. Normally it will contain only declarations |
12318 | // produced from declarator list. But in case we have any definitions or |
12319 | // additional declaration references: |
12320 | // 'typedef struct S {} S;' |
12321 | // 'typedef struct S *S;' |
12322 | // 'struct S *pS;' |
12323 | // FinalizeDeclaratorGroup adds these as separate declarations. |
12324 | Decl *MaybeTagDecl = Group[0]; |
12325 | if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { |
12326 | Group = Group.slice(1); |
12327 | } |
12328 | } |
12329 | |
12330 | // See if there are any new comments that are not attached to a decl. |
12331 | ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); |
12332 | if (!Comments.empty() && |
12333 | !Comments.back()->isAttached()) { |
12334 | // There is at least one comment that not attached to a decl. |
12335 | // Maybe it should be attached to one of these decls? |
12336 | // |
12337 | // Note that this way we pick up not only comments that precede the |
12338 | // declaration, but also comments that *follow* the declaration -- thanks to |
12339 | // the lookahead in the lexer: we've consumed the semicolon and looked |
12340 | // ahead through comments. |
12341 | for (unsigned i = 0, e = Group.size(); i != e; ++i) |
12342 | Context.getCommentForDecl(Group[i], &PP); |
12343 | } |
12344 | } |
12345 | |
12346 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() |
12347 | /// to introduce parameters into function prototype scope. |
12348 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { |
12349 | const DeclSpec &DS = D.getDeclSpec(); |
12350 | |
12351 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. |
12352 | |
12353 | // C++03 [dcl.stc]p2 also permits 'auto'. |
12354 | StorageClass SC = SC_None; |
12355 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { |
12356 | SC = SC_Register; |
12357 | // In C++11, the 'register' storage class specifier is deprecated. |
12358 | // In C++17, it is not allowed, but we tolerate it as an extension. |
12359 | if (getLangOpts().CPlusPlus11) { |
12360 | Diag(DS.getStorageClassSpecLoc(), |
12361 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class |
12362 | : diag::warn_deprecated_register) |
12363 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); |
12364 | } |
12365 | } else if (getLangOpts().CPlusPlus && |
12366 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { |
12367 | SC = SC_Auto; |
12368 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { |
12369 | Diag(DS.getStorageClassSpecLoc(), |
12370 | diag::err_invalid_storage_class_in_func_decl); |
12371 | D.getMutableDeclSpec().ClearStorageClassSpecs(); |
12372 | } |
12373 | |
12374 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) |
12375 | Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) |
12376 | << DeclSpec::getSpecifierName(TSCS); |
12377 | if (DS.isInlineSpecified()) |
12378 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) |
12379 | << getLangOpts().CPlusPlus17; |
12380 | if (DS.isConstexprSpecified()) |
12381 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) |
12382 | << 0; |
12383 | |
12384 | DiagnoseFunctionSpecifiers(DS); |
12385 | |
12386 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
12387 | QualType parmDeclType = TInfo->getType(); |
12388 | |
12389 | if (getLangOpts().CPlusPlus) { |
12390 | // Check that there are no default arguments inside the type of this |
12391 | // parameter. |
12392 | CheckExtraCXXDefaultArguments(D); |
12393 | |
12394 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). |
12395 | if (D.getCXXScopeSpec().isSet()) { |
12396 | Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) |
12397 | << D.getCXXScopeSpec().getRange(); |
12398 | D.getCXXScopeSpec().clear(); |
12399 | } |
12400 | } |
12401 | |
12402 | // Ensure we have a valid name |
12403 | IdentifierInfo *II = nullptr; |
12404 | if (D.hasName()) { |
12405 | II = D.getIdentifier(); |
12406 | if (!II) { |
12407 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) |
12408 | << GetNameForDeclarator(D).getName(); |
12409 | D.setInvalidType(true); |
12410 | } |
12411 | } |
12412 | |
12413 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); |
12414 | if (II) { |
12415 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, |
12416 | ForVisibleRedeclaration); |
12417 | LookupName(R, S); |
12418 | if (R.isSingleResult()) { |
12419 | NamedDecl *PrevDecl = R.getFoundDecl(); |
12420 | if (PrevDecl->isTemplateParameter()) { |
12421 | // Maybe we will complain about the shadowed template parameter. |
12422 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); |
12423 | // Just pretend that we didn't see the previous declaration. |
12424 | PrevDecl = nullptr; |
12425 | } else if (S->isDeclScope(PrevDecl)) { |
12426 | Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; |
12427 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); |
12428 | |
12429 | // Recover by removing the name |
12430 | II = nullptr; |
12431 | D.SetIdentifier(nullptr, D.getIdentifierLoc()); |
12432 | D.setInvalidType(true); |
12433 | } |
12434 | } |
12435 | } |
12436 | |
12437 | // Temporarily put parameter variables in the translation unit, not |
12438 | // the enclosing context. This prevents them from accidentally |
12439 | // looking like class members in C++. |
12440 | ParmVarDecl *New = |
12441 | CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), |
12442 | D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); |
12443 | |
12444 | if (D.isInvalidType()) |
12445 | New->setInvalidDecl(); |
12446 | |
12447 | assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void> (0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12447, __PRETTY_FUNCTION__)); |
12448 | assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast< void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12448, __PRETTY_FUNCTION__)); |
12449 | New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, |
12450 | S->getNextFunctionPrototypeIndex()); |
12451 | |
12452 | // Add the parameter declaration into this scope. |
12453 | S->AddDecl(New); |
12454 | if (II) |
12455 | IdResolver.AddDecl(New); |
12456 | |
12457 | ProcessDeclAttributes(S, New, D); |
12458 | |
12459 | if (D.getDeclSpec().isModulePrivateSpecified()) |
12460 | Diag(New->getLocation(), diag::err_module_private_local) |
12461 | << 1 << New->getDeclName() |
12462 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) |
12463 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); |
12464 | |
12465 | if (New->hasAttr<BlocksAttr>()) { |
12466 | Diag(New->getLocation(), diag::err_block_on_nonlocal); |
12467 | } |
12468 | return New; |
12469 | } |
12470 | |
12471 | /// Synthesizes a variable for a parameter arising from a |
12472 | /// typedef. |
12473 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, |
12474 | SourceLocation Loc, |
12475 | QualType T) { |
12476 | /* FIXME: setting StartLoc == Loc. |
12477 | Would it be worth to modify callers so as to provide proper source |
12478 | location for the unnamed parameters, embedding the parameter's type? */ |
12479 | ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, |
12480 | T, Context.getTrivialTypeSourceInfo(T, Loc), |
12481 | SC_None, nullptr); |
12482 | Param->setImplicit(); |
12483 | return Param; |
12484 | } |
12485 | |
12486 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { |
12487 | // Don't diagnose unused-parameter errors in template instantiations; we |
12488 | // will already have done so in the template itself. |
12489 | if (inTemplateInstantiation()) |
12490 | return; |
12491 | |
12492 | for (const ParmVarDecl *Parameter : Parameters) { |
12493 | if (!Parameter->isReferenced() && Parameter->getDeclName() && |
12494 | !Parameter->hasAttr<UnusedAttr>()) { |
12495 | Diag(Parameter->getLocation(), diag::warn_unused_parameter) |
12496 | << Parameter->getDeclName(); |
12497 | } |
12498 | } |
12499 | } |
12500 | |
12501 | void Sema::DiagnoseSizeOfParametersAndReturnValue( |
12502 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { |
12503 | if (LangOpts.NumLargeByValueCopy == 0) // No check. |
12504 | return; |
12505 | |
12506 | // Warn if the return value is pass-by-value and larger than the specified |
12507 | // threshold. |
12508 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { |
12509 | unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); |
12510 | if (Size > LangOpts.NumLargeByValueCopy) |
12511 | Diag(D->getLocation(), diag::warn_return_value_size) |
12512 | << D->getDeclName() << Size; |
12513 | } |
12514 | |
12515 | // Warn if any parameter is pass-by-value and larger than the specified |
12516 | // threshold. |
12517 | for (const ParmVarDecl *Parameter : Parameters) { |
12518 | QualType T = Parameter->getType(); |
12519 | if (T->isDependentType() || !T.isPODType(Context)) |
12520 | continue; |
12521 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); |
12522 | if (Size > LangOpts.NumLargeByValueCopy) |
12523 | Diag(Parameter->getLocation(), diag::warn_parameter_size) |
12524 | << Parameter->getDeclName() << Size; |
12525 | } |
12526 | } |
12527 | |
12528 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, |
12529 | SourceLocation NameLoc, IdentifierInfo *Name, |
12530 | QualType T, TypeSourceInfo *TSInfo, |
12531 | StorageClass SC) { |
12532 | // In ARC, infer a lifetime qualifier for appropriate parameter types. |
12533 | if (getLangOpts().ObjCAutoRefCount && |
12534 | T.getObjCLifetime() == Qualifiers::OCL_None && |
12535 | T->isObjCLifetimeType()) { |
12536 | |
12537 | Qualifiers::ObjCLifetime lifetime; |
12538 | |
12539 | // Special cases for arrays: |
12540 | // - if it's const, use __unsafe_unretained |
12541 | // - otherwise, it's an error |
12542 | if (T->isArrayType()) { |
12543 | if (!T.isConstQualified()) { |
12544 | DelayedDiagnostics.add( |
12545 | sema::DelayedDiagnostic::makeForbiddenType( |
12546 | NameLoc, diag::err_arc_array_param_no_ownership, T, false)); |
12547 | } |
12548 | lifetime = Qualifiers::OCL_ExplicitNone; |
12549 | } else { |
12550 | lifetime = T->getObjCARCImplicitLifetime(); |
12551 | } |
12552 | T = Context.getLifetimeQualifiedType(T, lifetime); |
12553 | } |
12554 | |
12555 | ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, |
12556 | Context.getAdjustedParameterType(T), |
12557 | TSInfo, SC, nullptr); |
12558 | |
12559 | // Parameters can not be abstract class types. |
12560 | // For record types, this is done by the AbstractClassUsageDiagnoser once |
12561 | // the class has been completely parsed. |
12562 | if (!CurContext->isRecord() && |
12563 | RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, |
12564 | AbstractParamType)) |
12565 | New->setInvalidDecl(); |
12566 | |
12567 | // Parameter declarators cannot be interface types. All ObjC objects are |
12568 | // passed by reference. |
12569 | if (T->isObjCObjectType()) { |
12570 | SourceLocation TypeEndLoc = |
12571 | getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); |
12572 | Diag(NameLoc, |
12573 | diag::err_object_cannot_be_passed_returned_by_value) << 1 << T |
12574 | << FixItHint::CreateInsertion(TypeEndLoc, "*"); |
12575 | T = Context.getObjCObjectPointerType(T); |
12576 | New->setType(T); |
12577 | } |
12578 | |
12579 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage |
12580 | // duration shall not be qualified by an address-space qualifier." |
12581 | // Since all parameters have automatic store duration, they can not have |
12582 | // an address space. |
12583 | if (T.getAddressSpace() != LangAS::Default && |
12584 | // OpenCL allows function arguments declared to be an array of a type |
12585 | // to be qualified with an address space. |
12586 | !(getLangOpts().OpenCL && |
12587 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { |
12588 | Diag(NameLoc, diag::err_arg_with_address_space); |
12589 | New->setInvalidDecl(); |
12590 | } |
12591 | |
12592 | return New; |
12593 | } |
12594 | |
12595 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, |
12596 | SourceLocation LocAfterDecls) { |
12597 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); |
12598 | |
12599 | // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' |
12600 | // for a K&R function. |
12601 | if (!FTI.hasPrototype) { |
12602 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { |
12603 | --i; |
12604 | if (FTI.Params[i].Param == nullptr) { |
12605 | SmallString<256> Code; |
12606 | llvm::raw_svector_ostream(Code) |
12607 | << " int " << FTI.Params[i].Ident->getName() << ";\n"; |
12608 | Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) |
12609 | << FTI.Params[i].Ident |
12610 | << FixItHint::CreateInsertion(LocAfterDecls, Code); |
12611 | |
12612 | // Implicitly declare the argument as type 'int' for lack of a better |
12613 | // type. |
12614 | AttributeFactory attrs; |
12615 | DeclSpec DS(attrs); |
12616 | const char* PrevSpec; // unused |
12617 | unsigned DiagID; // unused |
12618 | DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, |
12619 | DiagID, Context.getPrintingPolicy()); |
12620 | // Use the identifier location for the type source range. |
12621 | DS.SetRangeStart(FTI.Params[i].IdentLoc); |
12622 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); |
12623 | Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); |
12624 | ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); |
12625 | FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); |
12626 | } |
12627 | } |
12628 | } |
12629 | } |
12630 | |
12631 | Decl * |
12632 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, |
12633 | MultiTemplateParamsArg TemplateParameterLists, |
12634 | SkipBodyInfo *SkipBody) { |
12635 | assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused" ) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12635, __PRETTY_FUNCTION__)); |
12636 | assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!" ) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12636, __PRETTY_FUNCTION__)); |
12637 | Scope *ParentScope = FnBodyScope->getParent(); |
12638 | |
12639 | D.setFunctionDefinitionKind(FDK_Definition); |
12640 | Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); |
12641 | return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); |
12642 | } |
12643 | |
12644 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { |
12645 | Consumer.HandleInlineFunctionDefinition(D); |
12646 | } |
12647 | |
12648 | static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, |
12649 | const FunctionDecl*& PossibleZeroParamPrototype) { |
12650 | // Don't warn about invalid declarations. |
12651 | if (FD->isInvalidDecl()) |
12652 | return false; |
12653 | |
12654 | // Or declarations that aren't global. |
12655 | if (!FD->isGlobal()) |
12656 | return false; |
12657 | |
12658 | // Don't warn about C++ member functions. |
12659 | if (isa<CXXMethodDecl>(FD)) |
12660 | return false; |
12661 | |
12662 | // Don't warn about 'main'. |
12663 | if (FD->isMain()) |
12664 | return false; |
12665 | |
12666 | // Don't warn about inline functions. |
12667 | if (FD->isInlined()) |
12668 | return false; |
12669 | |
12670 | // Don't warn about function templates. |
12671 | if (FD->getDescribedFunctionTemplate()) |
12672 | return false; |
12673 | |
12674 | // Don't warn about function template specializations. |
12675 | if (FD->isFunctionTemplateSpecialization()) |
12676 | return false; |
12677 | |
12678 | // Don't warn for OpenCL kernels. |
12679 | if (FD->hasAttr<OpenCLKernelAttr>()) |
12680 | return false; |
12681 | |
12682 | // Don't warn on explicitly deleted functions. |
12683 | if (FD->isDeleted()) |
12684 | return false; |
12685 | |
12686 | bool MissingPrototype = true; |
12687 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); |
12688 | Prev; Prev = Prev->getPreviousDecl()) { |
12689 | // Ignore any declarations that occur in function or method |
12690 | // scope, because they aren't visible from the header. |
12691 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) |
12692 | continue; |
12693 | |
12694 | MissingPrototype = !Prev->getType()->isFunctionProtoType(); |
12695 | if (FD->getNumParams() == 0) |
12696 | PossibleZeroParamPrototype = Prev; |
12697 | break; |
12698 | } |
12699 | |
12700 | return MissingPrototype; |
12701 | } |
12702 | |
12703 | void |
12704 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, |
12705 | const FunctionDecl *EffectiveDefinition, |
12706 | SkipBodyInfo *SkipBody) { |
12707 | const FunctionDecl *Definition = EffectiveDefinition; |
12708 | if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { |
12709 | // If this is a friend function defined in a class template, it does not |
12710 | // have a body until it is used, nevertheless it is a definition, see |
12711 | // [temp.inst]p2: |
12712 | // |
12713 | // ... for the purpose of determining whether an instantiated redeclaration |
12714 | // is valid according to [basic.def.odr] and [class.mem], a declaration that |
12715 | // corresponds to a definition in the template is considered to be a |
12716 | // definition. |
12717 | // |
12718 | // The following code must produce redefinition error: |
12719 | // |
12720 | // template<typename T> struct C20 { friend void func_20() {} }; |
12721 | // C20<int> c20i; |
12722 | // void func_20() {} |
12723 | // |
12724 | for (auto I : FD->redecls()) { |
12725 | if (I != FD && !I->isInvalidDecl() && |
12726 | I->getFriendObjectKind() != Decl::FOK_None) { |
12727 | if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { |
12728 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { |
12729 | // A merged copy of the same function, instantiated as a member of |
12730 | // the same class, is OK. |
12731 | if (declaresSameEntity(OrigFD, Original) && |
12732 | declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), |
12733 | cast<Decl>(FD->getLexicalDeclContext()))) |
12734 | continue; |
12735 | } |
12736 | |
12737 | if (Original->isThisDeclarationADefinition()) { |
12738 | Definition = I; |
12739 | break; |
12740 | } |
12741 | } |
12742 | } |
12743 | } |
12744 | } |
12745 | |
12746 | if (!Definition) |
12747 | // Similar to friend functions a friend function template may be a |
12748 | // definition and do not have a body if it is instantiated in a class |
12749 | // template. |
12750 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { |
12751 | for (auto I : FTD->redecls()) { |
12752 | auto D = cast<FunctionTemplateDecl>(I); |
12753 | if (D != FTD) { |
12754 | assert(!D->isThisDeclarationADefinition() &&((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12755, __PRETTY_FUNCTION__)) |
12755 | "More than one definition in redeclaration chain")((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12755, __PRETTY_FUNCTION__)); |
12756 | if (D->getFriendObjectKind() != Decl::FOK_None) |
12757 | if (FunctionTemplateDecl *FT = |
12758 | D->getInstantiatedFromMemberTemplate()) { |
12759 | if (FT->isThisDeclarationADefinition()) { |
12760 | Definition = D->getTemplatedDecl(); |
12761 | break; |
12762 | } |
12763 | } |
12764 | } |
12765 | } |
12766 | } |
12767 | |
12768 | if (!Definition) |
12769 | return; |
12770 | |
12771 | if (canRedefineFunction(Definition, getLangOpts())) |
12772 | return; |
12773 | |
12774 | // Don't emit an error when this is redefinition of a typo-corrected |
12775 | // definition. |
12776 | if (TypoCorrectedFunctionDefinitions.count(Definition)) |
12777 | return; |
12778 | |
12779 | // If we don't have a visible definition of the function, and it's inline or |
12780 | // a template, skip the new definition. |
12781 | if (SkipBody && !hasVisibleDefinition(Definition) && |
12782 | (Definition->getFormalLinkage() == InternalLinkage || |
12783 | Definition->isInlined() || |
12784 | Definition->getDescribedFunctionTemplate() || |
12785 | Definition->getNumTemplateParameterLists())) { |
12786 | SkipBody->ShouldSkip = true; |
12787 | SkipBody->Previous = const_cast<FunctionDecl*>(Definition); |
12788 | if (auto *TD = Definition->getDescribedFunctionTemplate()) |
12789 | makeMergedDefinitionVisible(TD); |
12790 | makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); |
12791 | return; |
12792 | } |
12793 | |
12794 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && |
12795 | Definition->getStorageClass() == SC_Extern) |
12796 | Diag(FD->getLocation(), diag::err_redefinition_extern_inline) |
12797 | << FD->getDeclName() << getLangOpts().CPlusPlus; |
12798 | else |
12799 | Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); |
12800 | |
12801 | Diag(Definition->getLocation(), diag::note_previous_definition); |
12802 | FD->setInvalidDecl(); |
12803 | } |
12804 | |
12805 | static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, |
12806 | Sema &S) { |
12807 | CXXRecordDecl *const LambdaClass = CallOperator->getParent(); |
12808 | |
12809 | LambdaScopeInfo *LSI = S.PushLambdaScope(); |
12810 | LSI->CallOperator = CallOperator; |
12811 | LSI->Lambda = LambdaClass; |
12812 | LSI->ReturnType = CallOperator->getReturnType(); |
12813 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); |
12814 | |
12815 | if (LCD == LCD_None) |
12816 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; |
12817 | else if (LCD == LCD_ByCopy) |
12818 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; |
12819 | else if (LCD == LCD_ByRef) |
12820 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; |
12821 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); |
12822 | |
12823 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); |
12824 | LSI->Mutable = !CallOperator->isConst(); |
12825 | |
12826 | // Add the captures to the LSI so they can be noted as already |
12827 | // captured within tryCaptureVar. |
12828 | auto I = LambdaClass->field_begin(); |
12829 | for (const auto &C : LambdaClass->captures()) { |
12830 | if (C.capturesVariable()) { |
12831 | VarDecl *VD = C.getCapturedVar(); |
12832 | if (VD->isInitCapture()) |
12833 | S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); |
12834 | QualType CaptureType = VD->getType(); |
12835 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; |
12836 | LSI->addCapture(VD, /*IsBlock*/false, ByRef, |
12837 | /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), |
12838 | /*EllipsisLoc*/C.isPackExpansion() |
12839 | ? C.getEllipsisLoc() : SourceLocation(), |
12840 | CaptureType, /*Expr*/ nullptr); |
12841 | |
12842 | } else if (C.capturesThis()) { |
12843 | LSI->addThisCapture(/*Nested*/ false, C.getLocation(), |
12844 | /*Expr*/ nullptr, |
12845 | C.getCaptureKind() == LCK_StarThis); |
12846 | } else { |
12847 | LSI->addVLATypeCapture(C.getLocation(), I->getType()); |
12848 | } |
12849 | ++I; |
12850 | } |
12851 | } |
12852 | |
12853 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, |
12854 | SkipBodyInfo *SkipBody) { |
12855 | if (!D) { |
12856 | // Parsing the function declaration failed in some way. Push on a fake scope |
12857 | // anyway so we can try to parse the function body. |
12858 | PushFunctionScope(); |
12859 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); |
12860 | return D; |
12861 | } |
12862 | |
12863 | FunctionDecl *FD = nullptr; |
12864 | |
12865 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) |
12866 | FD = FunTmpl->getTemplatedDecl(); |
12867 | else |
12868 | FD = cast<FunctionDecl>(D); |
12869 | |
12870 | // Do not push if it is a lambda because one is already pushed when building |
12871 | // the lambda in ActOnStartOfLambdaDefinition(). |
12872 | if (!isLambdaCallOperator(FD)) |
12873 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); |
12874 | |
12875 | // Check for defining attributes before the check for redefinition. |
12876 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { |
12877 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; |
12878 | FD->dropAttr<AliasAttr>(); |
12879 | FD->setInvalidDecl(); |
12880 | } |
12881 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { |
12882 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; |
12883 | FD->dropAttr<IFuncAttr>(); |
12884 | FD->setInvalidDecl(); |
12885 | } |
12886 | |
12887 | // See if this is a redefinition. If 'will have body' is already set, then |
12888 | // these checks were already performed when it was set. |
12889 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { |
12890 | CheckForFunctionRedefinition(FD, nullptr, SkipBody); |
12891 | |
12892 | // If we're skipping the body, we're done. Don't enter the scope. |
12893 | if (SkipBody && SkipBody->ShouldSkip) |
12894 | return D; |
12895 | } |
12896 | |
12897 | // Mark this function as "will have a body eventually". This lets users to |
12898 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing |
12899 | // this function. |
12900 | FD->setWillHaveBody(); |
12901 | |
12902 | // If we are instantiating a generic lambda call operator, push |
12903 | // a LambdaScopeInfo onto the function stack. But use the information |
12904 | // that's already been calculated (ActOnLambdaExpr) to prime the current |
12905 | // LambdaScopeInfo. |
12906 | // When the template operator is being specialized, the LambdaScopeInfo, |
12907 | // has to be properly restored so that tryCaptureVariable doesn't try |
12908 | // and capture any new variables. In addition when calculating potential |
12909 | // captures during transformation of nested lambdas, it is necessary to |
12910 | // have the LSI properly restored. |
12911 | if (isGenericLambdaCallOperatorSpecialization(FD)) { |
12912 | assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12914, __PRETTY_FUNCTION__)) |
12913 | "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12914, __PRETTY_FUNCTION__)) |
12914 | "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12914, __PRETTY_FUNCTION__)); |
12915 | RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); |
12916 | } else { |
12917 | // Enter a new function scope |
12918 | PushFunctionScope(); |
12919 | } |
12920 | |
12921 | // Builtin functions cannot be defined. |
12922 | if (unsigned BuiltinID = FD->getBuiltinID()) { |
12923 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && |
12924 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { |
12925 | Diag(FD->getLocation(), diag::err_builtin_definition) << FD; |
12926 | FD->setInvalidDecl(); |
12927 | } |
12928 | } |
12929 | |
12930 | // The return type of a function definition must be complete |
12931 | // (C99 6.9.1p3, C++ [dcl.fct]p6). |
12932 | QualType ResultType = FD->getReturnType(); |
12933 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && |
12934 | !FD->isInvalidDecl() && |
12935 | RequireCompleteType(FD->getLocation(), ResultType, |
12936 | diag::err_func_def_incomplete_result)) |
12937 | FD->setInvalidDecl(); |
12938 | |
12939 | if (FnBodyScope) |
12940 | PushDeclContext(FnBodyScope, FD); |
12941 | |
12942 | // Check the validity of our function parameters |
12943 | CheckParmsForFunctionDef(FD->parameters(), |
12944 | /*CheckParameterNames=*/true); |
12945 | |
12946 | // Add non-parameter declarations already in the function to the current |
12947 | // scope. |
12948 | if (FnBodyScope) { |
12949 | for (Decl *NPD : FD->decls()) { |
12950 | auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); |
12951 | if (!NonParmDecl) |
12952 | continue; |
12953 | assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12954, __PRETTY_FUNCTION__)) |
12954 | "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12954, __PRETTY_FUNCTION__)); |
12955 | |
12956 | // If the decl has a name, make it accessible in the current scope. |
12957 | if (NonParmDecl->getDeclName()) |
12958 | PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); |
12959 | |
12960 | // Similarly, dive into enums and fish their constants out, making them |
12961 | // accessible in this scope. |
12962 | if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { |
12963 | for (auto *EI : ED->enumerators()) |
12964 | PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); |
12965 | } |
12966 | } |
12967 | } |
12968 | |
12969 | // Introduce our parameters into the function scope |
12970 | for (auto Param : FD->parameters()) { |
12971 | Param->setOwningFunction(FD); |
12972 | |
12973 | // If this has an identifier, add it to the scope stack. |
12974 | if (Param->getIdentifier() && FnBodyScope) { |
12975 | CheckShadow(FnBodyScope, Param); |
12976 | |
12977 | PushOnScopeChains(Param, FnBodyScope); |
12978 | } |
12979 | } |
12980 | |
12981 | // Ensure that the function's exception specification is instantiated. |
12982 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) |
12983 | ResolveExceptionSpec(D->getLocation(), FPT); |
12984 | |
12985 | // dllimport cannot be applied to non-inline function definitions. |
12986 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && |
12987 | !FD->isTemplateInstantiation()) { |
12988 | assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void > (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 12988, __PRETTY_FUNCTION__)); |
12989 | Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); |
12990 | FD->setInvalidDecl(); |
12991 | return D; |
12992 | } |
12993 | // We want to attach documentation to original Decl (which might be |
12994 | // a function template). |
12995 | ActOnDocumentableDecl(D); |
12996 | if (getCurLexicalContext()->isObjCContainer() && |
12997 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && |
12998 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) |
12999 | Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); |
13000 | |
13001 | return D; |
13002 | } |
13003 | |
13004 | /// Given the set of return statements within a function body, |
13005 | /// compute the variables that are subject to the named return value |
13006 | /// optimization. |
13007 | /// |
13008 | /// Each of the variables that is subject to the named return value |
13009 | /// optimization will be marked as NRVO variables in the AST, and any |
13010 | /// return statement that has a marked NRVO variable as its NRVO candidate can |
13011 | /// use the named return value optimization. |
13012 | /// |
13013 | /// This function applies a very simplistic algorithm for NRVO: if every return |
13014 | /// statement in the scope of a variable has the same NRVO candidate, that |
13015 | /// candidate is an NRVO variable. |
13016 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { |
13017 | ReturnStmt **Returns = Scope->Returns.data(); |
13018 | |
13019 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { |
13020 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { |
13021 | if (!NRVOCandidate->isNRVOVariable()) |
13022 | Returns[I]->setNRVOCandidate(nullptr); |
13023 | } |
13024 | } |
13025 | } |
13026 | |
13027 | bool Sema::canDelayFunctionBody(const Declarator &D) { |
13028 | // We can't delay parsing the body of a constexpr function template (yet). |
13029 | if (D.getDeclSpec().isConstexprSpecified()) |
13030 | return false; |
13031 | |
13032 | // We can't delay parsing the body of a function template with a deduced |
13033 | // return type (yet). |
13034 | if (D.getDeclSpec().hasAutoTypeSpec()) { |
13035 | // If the placeholder introduces a non-deduced trailing return type, |
13036 | // we can still delay parsing it. |
13037 | if (D.getNumTypeObjects()) { |
13038 | const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); |
13039 | if (Outer.Kind == DeclaratorChunk::Function && |
13040 | Outer.Fun.hasTrailingReturnType()) { |
13041 | QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); |
13042 | return Ty.isNull() || !Ty->isUndeducedType(); |
13043 | } |
13044 | } |
13045 | return false; |
13046 | } |
13047 | |
13048 | return true; |
13049 | } |
13050 | |
13051 | bool Sema::canSkipFunctionBody(Decl *D) { |
13052 | // We cannot skip the body of a function (or function template) which is |
13053 | // constexpr, since we may need to evaluate its body in order to parse the |
13054 | // rest of the file. |
13055 | // We cannot skip the body of a function with an undeduced return type, |
13056 | // because any callers of that function need to know the type. |
13057 | if (const FunctionDecl *FD = D->getAsFunction()) { |
13058 | if (FD->isConstexpr()) |
13059 | return false; |
13060 | // We can't simply call Type::isUndeducedType here, because inside template |
13061 | // auto can be deduced to a dependent type, which is not considered |
13062 | // "undeduced". |
13063 | if (FD->getReturnType()->getContainedDeducedType()) |
13064 | return false; |
13065 | } |
13066 | return Consumer.shouldSkipFunctionBody(D); |
13067 | } |
13068 | |
13069 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { |
13070 | if (!Decl) |
13071 | return nullptr; |
13072 | if (FunctionDecl *FD = Decl->getAsFunction()) |
13073 | FD->setHasSkippedBody(); |
13074 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) |
13075 | MD->setHasSkippedBody(); |
13076 | return Decl; |
13077 | } |
13078 | |
13079 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { |
13080 | return ActOnFinishFunctionBody(D, BodyArg, false); |
13081 | } |
13082 | |
13083 | /// RAII object that pops an ExpressionEvaluationContext when exiting a function |
13084 | /// body. |
13085 | class ExitFunctionBodyRAII { |
13086 | public: |
13087 | ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} |
13088 | ~ExitFunctionBodyRAII() { |
13089 | if (!IsLambda) |
13090 | S.PopExpressionEvaluationContext(); |
13091 | } |
13092 | |
13093 | private: |
13094 | Sema &S; |
13095 | bool IsLambda = false; |
13096 | }; |
13097 | |
13098 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, |
13099 | bool IsInstantiation) { |
13100 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; |
13101 | |
13102 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); |
13103 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; |
13104 | |
13105 | if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) |
13106 | CheckCompletedCoroutineBody(FD, Body); |
13107 | |
13108 | // Do not call PopExpressionEvaluationContext() if it is a lambda because one |
13109 | // is already popped when finishing the lambda in BuildLambdaExpr(). This is |
13110 | // meant to pop the context added in ActOnStartOfFunctionDef(). |
13111 | ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); |
13112 | |
13113 | if (FD) { |
13114 | FD->setBody(Body); |
13115 | FD->setWillHaveBody(false); |
13116 | |
13117 | if (getLangOpts().CPlusPlus14) { |
13118 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && |
13119 | FD->getReturnType()->isUndeducedType()) { |
13120 | // If the function has a deduced result type but contains no 'return' |
13121 | // statements, the result type as written must be exactly 'auto', and |
13122 | // the deduced result type is 'void'. |
13123 | if (!FD->getReturnType()->getAs<AutoType>()) { |
13124 | Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) |
13125 | << FD->getReturnType(); |
13126 | FD->setInvalidDecl(); |
13127 | } else { |
13128 | // Substitute 'void' for the 'auto' in the type. |
13129 | TypeLoc ResultType = getReturnTypeLoc(FD); |
13130 | Context.adjustDeducedFunctionResultType( |
13131 | FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); |
13132 | } |
13133 | } |
13134 | } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { |
13135 | // In C++11, we don't use 'auto' deduction rules for lambda call |
13136 | // operators because we don't support return type deduction. |
13137 | auto *LSI = getCurLambda(); |
13138 | if (LSI->HasImplicitReturnType) { |
13139 | deduceClosureReturnType(*LSI); |
13140 | |
13141 | // C++11 [expr.prim.lambda]p4: |
13142 | // [...] if there are no return statements in the compound-statement |
13143 | // [the deduced type is] the type void |
13144 | QualType RetType = |
13145 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; |
13146 | |
13147 | // Update the return type to the deduced type. |
13148 | const FunctionProtoType *Proto = |
13149 | FD->getType()->getAs<FunctionProtoType>(); |
13150 | FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), |
13151 | Proto->getExtProtoInfo())); |
13152 | } |
13153 | } |
13154 | |
13155 | // If the function implicitly returns zero (like 'main') or is naked, |
13156 | // don't complain about missing return statements. |
13157 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) |
13158 | WP.disableCheckFallThrough(); |
13159 | |
13160 | // MSVC permits the use of pure specifier (=0) on function definition, |
13161 | // defined at class scope, warn about this non-standard construct. |
13162 | if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) |
13163 | Diag(FD->getLocation(), diag::ext_pure_function_definition); |
13164 | |
13165 | if (!FD->isInvalidDecl()) { |
13166 | // Don't diagnose unused parameters of defaulted or deleted functions. |
13167 | if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) |
13168 | DiagnoseUnusedParameters(FD->parameters()); |
13169 | DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), |
13170 | FD->getReturnType(), FD); |
13171 | |
13172 | // If this is a structor, we need a vtable. |
13173 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) |
13174 | MarkVTableUsed(FD->getLocation(), Constructor->getParent()); |
13175 | else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) |
13176 | MarkVTableUsed(FD->getLocation(), Destructor->getParent()); |
13177 | |
13178 | // Try to apply the named return value optimization. We have to check |
13179 | // if we can do this here because lambdas keep return statements around |
13180 | // to deduce an implicit return type. |
13181 | if (FD->getReturnType()->isRecordType() && |
13182 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) |
13183 | computeNRVO(Body, getCurFunction()); |
13184 | } |
13185 | |
13186 | // GNU warning -Wmissing-prototypes: |
13187 | // Warn if a global function is defined without a previous |
13188 | // prototype declaration. This warning is issued even if the |
13189 | // definition itself provides a prototype. The aim is to detect |
13190 | // global functions that fail to be declared in header files. |
13191 | const FunctionDecl *PossibleZeroParamPrototype = nullptr; |
13192 | if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { |
13193 | Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; |
13194 | |
13195 | if (PossibleZeroParamPrototype) { |
13196 | // We found a declaration that is not a prototype, |
13197 | // but that could be a zero-parameter prototype |
13198 | if (TypeSourceInfo *TI = |
13199 | PossibleZeroParamPrototype->getTypeSourceInfo()) { |
13200 | TypeLoc TL = TI->getTypeLoc(); |
13201 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) |
13202 | Diag(PossibleZeroParamPrototype->getLocation(), |
13203 | diag::note_declaration_not_a_prototype) |
13204 | << PossibleZeroParamPrototype |
13205 | << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); |
13206 | } |
13207 | } |
13208 | |
13209 | // GNU warning -Wstrict-prototypes |
13210 | // Warn if K&R function is defined without a previous declaration. |
13211 | // This warning is issued only if the definition itself does not provide |
13212 | // a prototype. Only K&R definitions do not provide a prototype. |
13213 | // An empty list in a function declarator that is part of a definition |
13214 | // of that function specifies that the function has no parameters |
13215 | // (C99 6.7.5.3p14) |
13216 | if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && |
13217 | !LangOpts.CPlusPlus) { |
13218 | TypeSourceInfo *TI = FD->getTypeSourceInfo(); |
13219 | TypeLoc TL = TI->getTypeLoc(); |
13220 | FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); |
13221 | Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; |
13222 | } |
13223 | } |
13224 | |
13225 | // Warn on CPUDispatch with an actual body. |
13226 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) |
13227 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) |
13228 | if (!CmpndBody->body_empty()) |
13229 | Diag(CmpndBody->body_front()->getBeginLoc(), |
13230 | diag::warn_dispatch_body_ignored); |
13231 | |
13232 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { |
13233 | const CXXMethodDecl *KeyFunction; |
13234 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && |
13235 | MD->isVirtual() && |
13236 | (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && |
13237 | MD == KeyFunction->getCanonicalDecl()) { |
13238 | // Update the key-function state if necessary for this ABI. |
13239 | if (FD->isInlined() && |
13240 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { |
13241 | Context.setNonKeyFunction(MD); |
13242 | |
13243 | // If the newly-chosen key function is already defined, then we |
13244 | // need to mark the vtable as used retroactively. |
13245 | KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); |
13246 | const FunctionDecl *Definition; |
13247 | if (KeyFunction && KeyFunction->isDefined(Definition)) |
13248 | MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); |
13249 | } else { |
13250 | // We just defined they key function; mark the vtable as used. |
13251 | MarkVTableUsed(FD->getLocation(), MD->getParent(), true); |
13252 | } |
13253 | } |
13254 | } |
13255 | |
13256 | assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13257, __PRETTY_FUNCTION__)) |
13257 | "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13257, __PRETTY_FUNCTION__)); |
13258 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { |
13259 | assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused" ) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13259, __PRETTY_FUNCTION__)); |
13260 | MD->setBody(Body); |
13261 | if (!MD->isInvalidDecl()) { |
13262 | if (!MD->hasSkippedBody()) |
13263 | DiagnoseUnusedParameters(MD->parameters()); |
13264 | DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), |
13265 | MD->getReturnType(), MD); |
13266 | |
13267 | if (Body) |
13268 | computeNRVO(Body, getCurFunction()); |
13269 | } |
13270 | if (getCurFunction()->ObjCShouldCallSuper) { |
13271 | Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) |
13272 | << MD->getSelector().getAsString(); |
13273 | getCurFunction()->ObjCShouldCallSuper = false; |
13274 | } |
13275 | if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { |
13276 | const ObjCMethodDecl *InitMethod = nullptr; |
13277 | bool isDesignated = |
13278 | MD->isDesignatedInitializerForTheInterface(&InitMethod); |
13279 | assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void> (0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13279, __PRETTY_FUNCTION__)); |
13280 | (void)isDesignated; |
13281 | |
13282 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { |
13283 | auto IFace = MD->getClassInterface(); |
13284 | if (!IFace) |
13285 | return false; |
13286 | auto SuperD = IFace->getSuperClass(); |
13287 | if (!SuperD) |
13288 | return false; |
13289 | return SuperD->getIdentifier() == |
13290 | NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); |
13291 | }; |
13292 | // Don't issue this warning for unavailable inits or direct subclasses |
13293 | // of NSObject. |
13294 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { |
13295 | Diag(MD->getLocation(), |
13296 | diag::warn_objc_designated_init_missing_super_call); |
13297 | Diag(InitMethod->getLocation(), |
13298 | diag::note_objc_designated_init_marked_here); |
13299 | } |
13300 | getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; |
13301 | } |
13302 | if (getCurFunction()->ObjCWarnForNoInitDelegation) { |
13303 | // Don't issue this warning for unavaialable inits. |
13304 | if (!MD->isUnavailable()) |
13305 | Diag(MD->getLocation(), |
13306 | diag::warn_objc_secondary_init_missing_init_call); |
13307 | getCurFunction()->ObjCWarnForNoInitDelegation = false; |
13308 | } |
13309 | } else { |
13310 | // Parsing the function declaration failed in some way. Pop the fake scope |
13311 | // we pushed on. |
13312 | PopFunctionScopeInfo(ActivePolicy, dcl); |
13313 | return nullptr; |
13314 | } |
13315 | |
13316 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) |
13317 | DiagnoseUnguardedAvailabilityViolations(dcl); |
13318 | |
13319 | assert(!getCurFunction()->ObjCShouldCallSuper &&((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13321, __PRETTY_FUNCTION__)) |
13320 | "This should only be set for ObjC methods, which should have been "((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13321, __PRETTY_FUNCTION__)) |
13321 | "handled in the block above.")((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13321, __PRETTY_FUNCTION__)); |
13322 | |
13323 | // Verify and clean out per-function state. |
13324 | if (Body && (!FD || !FD->isDefaulted())) { |
13325 | // C++ constructors that have function-try-blocks can't have return |
13326 | // statements in the handlers of that block. (C++ [except.handle]p14) |
13327 | // Verify this. |
13328 | if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) |
13329 | DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); |
13330 | |
13331 | // Verify that gotos and switch cases don't jump into scopes illegally. |
13332 | if (getCurFunction()->NeedsScopeChecking() && |
13333 | !PP.isCodeCompletionEnabled()) |
13334 | DiagnoseInvalidJumps(Body); |
13335 | |
13336 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { |
13337 | if (!Destructor->getParent()->isDependentType()) |
13338 | CheckDestructor(Destructor); |
13339 | |
13340 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), |
13341 | Destructor->getParent()); |
13342 | } |
13343 | |
13344 | // If any errors have occurred, clear out any temporaries that may have |
13345 | // been leftover. This ensures that these temporaries won't be picked up for |
13346 | // deletion in some later function. |
13347 | if (getDiagnostics().hasErrorOccurred() || |
13348 | getDiagnostics().getSuppressAllDiagnostics()) { |
13349 | DiscardCleanupsInEvaluationContext(); |
13350 | } |
13351 | if (!getDiagnostics().hasUncompilableErrorOccurred() && |
13352 | !isa<FunctionTemplateDecl>(dcl)) { |
13353 | // Since the body is valid, issue any analysis-based warnings that are |
13354 | // enabled. |
13355 | ActivePolicy = &WP; |
13356 | } |
13357 | |
13358 | if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && |
13359 | (!CheckConstexprFunctionDecl(FD) || |
13360 | !CheckConstexprFunctionBody(FD, Body))) |
13361 | FD->setInvalidDecl(); |
13362 | |
13363 | if (FD && FD->hasAttr<NakedAttr>()) { |
13364 | for (const Stmt *S : Body->children()) { |
13365 | // Allow local register variables without initializer as they don't |
13366 | // require prologue. |
13367 | bool RegisterVariables = false; |
13368 | if (auto *DS = dyn_cast<DeclStmt>(S)) { |
13369 | for (const auto *Decl : DS->decls()) { |
13370 | if (const auto *Var = dyn_cast<VarDecl>(Decl)) { |
13371 | RegisterVariables = |
13372 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); |
13373 | if (!RegisterVariables) |
13374 | break; |
13375 | } |
13376 | } |
13377 | } |
13378 | if (RegisterVariables) |
13379 | continue; |
13380 | if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { |
13381 | Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); |
13382 | Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); |
13383 | FD->setInvalidDecl(); |
13384 | break; |
13385 | } |
13386 | } |
13387 | } |
13388 | |
13389 | assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13391, __PRETTY_FUNCTION__)) |
13390 | ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13391, __PRETTY_FUNCTION__)) |
13391 | "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13391, __PRETTY_FUNCTION__)); |
13392 | assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13392, __PRETTY_FUNCTION__)); |
13393 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13394, __PRETTY_FUNCTION__)) |
13394 | "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13394, __PRETTY_FUNCTION__)); |
13395 | } |
13396 | |
13397 | if (!IsInstantiation) |
13398 | PopDeclContext(); |
13399 | |
13400 | PopFunctionScopeInfo(ActivePolicy, dcl); |
13401 | // If any errors have occurred, clear out any temporaries that may have |
13402 | // been leftover. This ensures that these temporaries won't be picked up for |
13403 | // deletion in some later function. |
13404 | if (getDiagnostics().hasErrorOccurred()) { |
13405 | DiscardCleanupsInEvaluationContext(); |
13406 | } |
13407 | |
13408 | return dcl; |
13409 | } |
13410 | |
13411 | /// When we finish delayed parsing of an attribute, we must attach it to the |
13412 | /// relevant Decl. |
13413 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, |
13414 | ParsedAttributes &Attrs) { |
13415 | // Always attach attributes to the underlying decl. |
13416 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) |
13417 | D = TD->getTemplatedDecl(); |
13418 | ProcessDeclAttributeList(S, D, Attrs); |
13419 | |
13420 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) |
13421 | if (Method->isStatic()) |
13422 | checkThisInStaticMemberFunctionAttributes(Method); |
13423 | } |
13424 | |
13425 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function |
13426 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). |
13427 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, |
13428 | IdentifierInfo &II, Scope *S) { |
13429 | // Find the scope in which the identifier is injected and the corresponding |
13430 | // DeclContext. |
13431 | // FIXME: C89 does not say what happens if there is no enclosing block scope. |
13432 | // In that case, we inject the declaration into the translation unit scope |
13433 | // instead. |
13434 | Scope *BlockScope = S; |
13435 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) |
13436 | BlockScope = BlockScope->getParent(); |
13437 | |
13438 | Scope *ContextScope = BlockScope; |
13439 | while (!ContextScope->getEntity()) |
13440 | ContextScope = ContextScope->getParent(); |
13441 | ContextRAII SavedContext(*this, ContextScope->getEntity()); |
13442 | |
13443 | // Before we produce a declaration for an implicitly defined |
13444 | // function, see whether there was a locally-scoped declaration of |
13445 | // this name as a function or variable. If so, use that |
13446 | // (non-visible) declaration, and complain about it. |
13447 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); |
13448 | if (ExternCPrev) { |
13449 | // We still need to inject the function into the enclosing block scope so |
13450 | // that later (non-call) uses can see it. |
13451 | PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); |
13452 | |
13453 | // C89 footnote 38: |
13454 | // If in fact it is not defined as having type "function returning int", |
13455 | // the behavior is undefined. |
13456 | if (!isa<FunctionDecl>(ExternCPrev) || |
13457 | !Context.typesAreCompatible( |
13458 | cast<FunctionDecl>(ExternCPrev)->getType(), |
13459 | Context.getFunctionNoProtoType(Context.IntTy))) { |
13460 | Diag(Loc, diag::ext_use_out_of_scope_declaration) |
13461 | << ExternCPrev << !getLangOpts().C99; |
13462 | Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); |
13463 | return ExternCPrev; |
13464 | } |
13465 | } |
13466 | |
13467 | // Extension in C99. Legal in C90, but warn about it. |
13468 | unsigned diag_id; |
13469 | if (II.getName().startswith("__builtin_")) |
13470 | diag_id = diag::warn_builtin_unknown; |
13471 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. |
13472 | else if (getLangOpts().OpenCL) |
13473 | diag_id = diag::err_opencl_implicit_function_decl; |
13474 | else if (getLangOpts().C99) |
13475 | diag_id = diag::ext_implicit_function_decl; |
13476 | else |
13477 | diag_id = diag::warn_implicit_function_decl; |
13478 | Diag(Loc, diag_id) << &II; |
13479 | |
13480 | // If we found a prior declaration of this function, don't bother building |
13481 | // another one. We've already pushed that one into scope, so there's nothing |
13482 | // more to do. |
13483 | if (ExternCPrev) |
13484 | return ExternCPrev; |
13485 | |
13486 | // Because typo correction is expensive, only do it if the implicit |
13487 | // function declaration is going to be treated as an error. |
13488 | if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { |
13489 | TypoCorrection Corrected; |
13490 | if (S && |
13491 | (Corrected = CorrectTypo( |
13492 | DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, |
13493 | llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) |
13494 | diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), |
13495 | /*ErrorRecovery*/false); |
13496 | } |
13497 | |
13498 | // Set a Declarator for the implicit definition: int foo(); |
13499 | const char *Dummy; |
13500 | AttributeFactory attrFactory; |
13501 | DeclSpec DS(attrFactory); |
13502 | unsigned DiagID; |
13503 | bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, |
13504 | Context.getPrintingPolicy()); |
13505 | (void)Error; // Silence warning. |
13506 | assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast <void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13506, __PRETTY_FUNCTION__)); |
13507 | SourceLocation NoLoc; |
13508 | Declarator D(DS, DeclaratorContext::BlockContext); |
13509 | D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, |
13510 | /*IsAmbiguous=*/false, |
13511 | /*LParenLoc=*/NoLoc, |
13512 | /*Params=*/nullptr, |
13513 | /*NumParams=*/0, |
13514 | /*EllipsisLoc=*/NoLoc, |
13515 | /*RParenLoc=*/NoLoc, |
13516 | /*TypeQuals=*/0, |
13517 | /*RefQualifierIsLvalueRef=*/true, |
13518 | /*RefQualifierLoc=*/NoLoc, |
13519 | /*ConstQualifierLoc=*/NoLoc, |
13520 | /*VolatileQualifierLoc=*/NoLoc, |
13521 | /*RestrictQualifierLoc=*/NoLoc, |
13522 | /*MutableLoc=*/NoLoc, EST_None, |
13523 | /*ESpecRange=*/SourceRange(), |
13524 | /*Exceptions=*/nullptr, |
13525 | /*ExceptionRanges=*/nullptr, |
13526 | /*NumExceptions=*/0, |
13527 | /*NoexceptExpr=*/nullptr, |
13528 | /*ExceptionSpecTokens=*/nullptr, |
13529 | /*DeclsInPrototype=*/None, Loc, |
13530 | Loc, D), |
13531 | std::move(DS.getAttributes()), SourceLocation()); |
13532 | D.SetIdentifier(&II, Loc); |
13533 | |
13534 | // Insert this function into the enclosing block scope. |
13535 | FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); |
13536 | FD->setImplicit(); |
13537 | |
13538 | AddKnownFunctionAttributes(FD); |
13539 | |
13540 | return FD; |
13541 | } |
13542 | |
13543 | /// Adds any function attributes that we know a priori based on |
13544 | /// the declaration of this function. |
13545 | /// |
13546 | /// These attributes can apply both to implicitly-declared builtins |
13547 | /// (like __builtin___printf_chk) or to library-declared functions |
13548 | /// like NSLog or printf. |
13549 | /// |
13550 | /// We need to check for duplicate attributes both here and where user-written |
13551 | /// attributes are applied to declarations. |
13552 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { |
13553 | if (FD->isInvalidDecl()) |
13554 | return; |
13555 | |
13556 | // If this is a built-in function, map its builtin attributes to |
13557 | // actual attributes. |
13558 | if (unsigned BuiltinID = FD->getBuiltinID()) { |
13559 | // Handle printf-formatting attributes. |
13560 | unsigned FormatIdx; |
13561 | bool HasVAListArg; |
13562 | if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { |
13563 | if (!FD->hasAttr<FormatAttr>()) { |
13564 | const char *fmt = "printf"; |
13565 | unsigned int NumParams = FD->getNumParams(); |
13566 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) |
13567 | FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) |
13568 | fmt = "NSString"; |
13569 | FD->addAttr(FormatAttr::CreateImplicit(Context, |
13570 | &Context.Idents.get(fmt), |
13571 | FormatIdx+1, |
13572 | HasVAListArg ? 0 : FormatIdx+2, |
13573 | FD->getLocation())); |
13574 | } |
13575 | } |
13576 | if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, |
13577 | HasVAListArg)) { |
13578 | if (!FD->hasAttr<FormatAttr>()) |
13579 | FD->addAttr(FormatAttr::CreateImplicit(Context, |
13580 | &Context.Idents.get("scanf"), |
13581 | FormatIdx+1, |
13582 | HasVAListArg ? 0 : FormatIdx+2, |
13583 | FD->getLocation())); |
13584 | } |
13585 | |
13586 | // Mark const if we don't care about errno and that is the only thing |
13587 | // preventing the function from being const. This allows IRgen to use LLVM |
13588 | // intrinsics for such functions. |
13589 | if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && |
13590 | Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) |
13591 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); |
13592 | |
13593 | // We make "fma" on some platforms const because we know it does not set |
13594 | // errno in those environments even though it could set errno based on the |
13595 | // C standard. |
13596 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); |
13597 | if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && |
13598 | !FD->hasAttr<ConstAttr>()) { |
13599 | switch (BuiltinID) { |
13600 | case Builtin::BI__builtin_fma: |
13601 | case Builtin::BI__builtin_fmaf: |
13602 | case Builtin::BI__builtin_fmal: |
13603 | case Builtin::BIfma: |
13604 | case Builtin::BIfmaf: |
13605 | case Builtin::BIfmal: |
13606 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); |
13607 | break; |
13608 | default: |
13609 | break; |
13610 | } |
13611 | } |
13612 | |
13613 | if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && |
13614 | !FD->hasAttr<ReturnsTwiceAttr>()) |
13615 | FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, |
13616 | FD->getLocation())); |
13617 | if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) |
13618 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); |
13619 | if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) |
13620 | FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); |
13621 | if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) |
13622 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); |
13623 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && |
13624 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { |
13625 | // Add the appropriate attribute, depending on the CUDA compilation mode |
13626 | // and which target the builtin belongs to. For example, during host |
13627 | // compilation, aux builtins are __device__, while the rest are __host__. |
13628 | if (getLangOpts().CUDAIsDevice != |
13629 | Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) |
13630 | FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); |
13631 | else |
13632 | FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); |
13633 | } |
13634 | } |
13635 | |
13636 | // If C++ exceptions are enabled but we are told extern "C" functions cannot |
13637 | // throw, add an implicit nothrow attribute to any extern "C" function we come |
13638 | // across. |
13639 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && |
13640 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { |
13641 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); |
13642 | if (!FPT || FPT->getExceptionSpecType() == EST_None) |
13643 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); |
13644 | } |
13645 | |
13646 | IdentifierInfo *Name = FD->getIdentifier(); |
13647 | if (!Name) |
13648 | return; |
13649 | if ((!getLangOpts().CPlusPlus && |
13650 | FD->getDeclContext()->isTranslationUnit()) || |
13651 | (isa<LinkageSpecDecl>(FD->getDeclContext()) && |
13652 | cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == |
13653 | LinkageSpecDecl::lang_c)) { |
13654 | // Okay: this could be a libc/libm/Objective-C function we know |
13655 | // about. |
13656 | } else |
13657 | return; |
13658 | |
13659 | if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { |
13660 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be |
13661 | // target-specific builtins, perhaps? |
13662 | if (!FD->hasAttr<FormatAttr>()) |
13663 | FD->addAttr(FormatAttr::CreateImplicit(Context, |
13664 | &Context.Idents.get("printf"), 2, |
13665 | Name->isStr("vasprintf") ? 0 : 3, |
13666 | FD->getLocation())); |
13667 | } |
13668 | |
13669 | if (Name->isStr("__CFStringMakeConstantString")) { |
13670 | // We already have a __builtin___CFStringMakeConstantString, |
13671 | // but builds that use -fno-constant-cfstrings don't go through that. |
13672 | if (!FD->hasAttr<FormatArgAttr>()) |
13673 | FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), |
13674 | FD->getLocation())); |
13675 | } |
13676 | } |
13677 | |
13678 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, |
13679 | TypeSourceInfo *TInfo) { |
13680 | assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13680, __PRETTY_FUNCTION__)); |
13681 | assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13681, __PRETTY_FUNCTION__)); |
13682 | |
13683 | if (!TInfo) { |
13684 | assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type" ) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13684, __PRETTY_FUNCTION__)); |
13685 | TInfo = Context.getTrivialTypeSourceInfo(T); |
13686 | } |
13687 | |
13688 | // Scope manipulation handled by caller. |
13689 | TypedefDecl *NewTD = |
13690 | TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), |
13691 | D.getIdentifierLoc(), D.getIdentifier(), TInfo); |
13692 | |
13693 | // Bail out immediately if we have an invalid declaration. |
13694 | if (D.isInvalidType()) { |
13695 | NewTD->setInvalidDecl(); |
13696 | return NewTD; |
13697 | } |
13698 | |
13699 | if (D.getDeclSpec().isModulePrivateSpecified()) { |
13700 | if (CurContext->isFunctionOrMethod()) |
13701 | Diag(NewTD->getLocation(), diag::err_module_private_local) |
13702 | << 2 << NewTD->getDeclName() |
13703 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) |
13704 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); |
13705 | else |
13706 | NewTD->setModulePrivate(); |
13707 | } |
13708 | |
13709 | // C++ [dcl.typedef]p8: |
13710 | // If the typedef declaration defines an unnamed class (or |
13711 | // enum), the first typedef-name declared by the declaration |
13712 | // to be that class type (or enum type) is used to denote the |
13713 | // class type (or enum type) for linkage purposes only. |
13714 | // We need to check whether the type was declared in the declaration. |
13715 | switch (D.getDeclSpec().getTypeSpecType()) { |
13716 | case TST_enum: |
13717 | case TST_struct: |
13718 | case TST_interface: |
13719 | case TST_union: |
13720 | case TST_class: { |
13721 | TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); |
13722 | setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); |
13723 | break; |
13724 | } |
13725 | |
13726 | default: |
13727 | break; |
13728 | } |
13729 | |
13730 | return NewTD; |
13731 | } |
13732 | |
13733 | /// Check that this is a valid underlying type for an enum declaration. |
13734 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { |
13735 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); |
13736 | QualType T = TI->getType(); |
13737 | |
13738 | if (T->isDependentType()) |
13739 | return false; |
13740 | |
13741 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) |
13742 | if (BT->isInteger()) |
13743 | return false; |
13744 | |
13745 | Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; |
13746 | return true; |
13747 | } |
13748 | |
13749 | /// Check whether this is a valid redeclaration of a previous enumeration. |
13750 | /// \return true if the redeclaration was invalid. |
13751 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, |
13752 | QualType EnumUnderlyingTy, bool IsFixed, |
13753 | const EnumDecl *Prev) { |
13754 | if (IsScoped != Prev->isScoped()) { |
13755 | Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) |
13756 | << Prev->isScoped(); |
13757 | Diag(Prev->getLocation(), diag::note_previous_declaration); |
13758 | return true; |
13759 | } |
13760 | |
13761 | if (IsFixed && Prev->isFixed()) { |
13762 | if (!EnumUnderlyingTy->isDependentType() && |
13763 | !Prev->getIntegerType()->isDependentType() && |
13764 | !Context.hasSameUnqualifiedType(EnumUnderlyingTy, |
13765 | Prev->getIntegerType())) { |
13766 | // TODO: Highlight the underlying type of the redeclaration. |
13767 | Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) |
13768 | << EnumUnderlyingTy << Prev->getIntegerType(); |
13769 | Diag(Prev->getLocation(), diag::note_previous_declaration) |
13770 | << Prev->getIntegerTypeRange(); |
13771 | return true; |
13772 | } |
13773 | } else if (IsFixed != Prev->isFixed()) { |
13774 | Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) |
13775 | << Prev->isFixed(); |
13776 | Diag(Prev->getLocation(), diag::note_previous_declaration); |
13777 | return true; |
13778 | } |
13779 | |
13780 | return false; |
13781 | } |
13782 | |
13783 | /// Get diagnostic %select index for tag kind for |
13784 | /// redeclaration diagnostic message. |
13785 | /// WARNING: Indexes apply to particular diagnostics only! |
13786 | /// |
13787 | /// \returns diagnostic %select index. |
13788 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { |
13789 | switch (Tag) { |
13790 | case TTK_Struct: return 0; |
13791 | case TTK_Interface: return 1; |
13792 | case TTK_Class: return 2; |
13793 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13793); |
13794 | } |
13795 | } |
13796 | |
13797 | /// Determine if tag kind is a class-key compatible with |
13798 | /// class for redeclaration (class, struct, or __interface). |
13799 | /// |
13800 | /// \returns true iff the tag kind is compatible. |
13801 | static bool isClassCompatTagKind(TagTypeKind Tag) |
13802 | { |
13803 | return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; |
13804 | } |
13805 | |
13806 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, |
13807 | TagTypeKind TTK) { |
13808 | if (isa<TypedefDecl>(PrevDecl)) |
13809 | return NTK_Typedef; |
13810 | else if (isa<TypeAliasDecl>(PrevDecl)) |
13811 | return NTK_TypeAlias; |
13812 | else if (isa<ClassTemplateDecl>(PrevDecl)) |
13813 | return NTK_Template; |
13814 | else if (isa<TypeAliasTemplateDecl>(PrevDecl)) |
13815 | return NTK_TypeAliasTemplate; |
13816 | else if (isa<TemplateTemplateParmDecl>(PrevDecl)) |
13817 | return NTK_TemplateTemplateArgument; |
13818 | switch (TTK) { |
13819 | case TTK_Struct: |
13820 | case TTK_Interface: |
13821 | case TTK_Class: |
13822 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; |
13823 | case TTK_Union: |
13824 | return NTK_NonUnion; |
13825 | case TTK_Enum: |
13826 | return NTK_NonEnum; |
13827 | } |
13828 | llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 13828); |
13829 | } |
13830 | |
13831 | /// Determine whether a tag with a given kind is acceptable |
13832 | /// as a redeclaration of the given tag declaration. |
13833 | /// |
13834 | /// \returns true if the new tag kind is acceptable, false otherwise. |
13835 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, |
13836 | TagTypeKind NewTag, bool isDefinition, |
13837 | SourceLocation NewTagLoc, |
13838 | const IdentifierInfo *Name) { |
13839 | // C++ [dcl.type.elab]p3: |
13840 | // The class-key or enum keyword present in the |
13841 | // elaborated-type-specifier shall agree in kind with the |
13842 | // declaration to which the name in the elaborated-type-specifier |
13843 | // refers. This rule also applies to the form of |
13844 | // elaborated-type-specifier that declares a class-name or |
13845 | // friend class since it can be construed as referring to the |
13846 | // definition of the class. Thus, in any |
13847 | // elaborated-type-specifier, the enum keyword shall be used to |
13848 | // refer to an enumeration (7.2), the union class-key shall be |
13849 | // used to refer to a union (clause 9), and either the class or |
13850 | // struct class-key shall be used to refer to a class (clause 9) |
13851 | // declared using the class or struct class-key. |
13852 | TagTypeKind OldTag = Previous->getTagKind(); |
13853 | if (OldTag != NewTag && |
13854 | !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) |
13855 | return false; |
13856 | |
13857 | // Tags are compatible, but we might still want to warn on mismatched tags. |
13858 | // Non-class tags can't be mismatched at this point. |
13859 | if (!isClassCompatTagKind(NewTag)) |
13860 | return true; |
13861 | |
13862 | // Declarations for which -Wmismatched-tags is disabled are entirely ignored |
13863 | // by our warning analysis. We don't want to warn about mismatches with (eg) |
13864 | // declarations in system headers that are designed to be specialized, but if |
13865 | // a user asks us to warn, we should warn if their code contains mismatched |
13866 | // declarations. |
13867 | auto IsIgnoredLoc = [&](SourceLocation Loc) { |
13868 | return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, |
13869 | Loc); |
13870 | }; |
13871 | if (IsIgnoredLoc(NewTagLoc)) |
13872 | return true; |
13873 | |
13874 | auto IsIgnored = [&](const TagDecl *Tag) { |
13875 | return IsIgnoredLoc(Tag->getLocation()); |
13876 | }; |
13877 | while (IsIgnored(Previous)) { |
13878 | Previous = Previous->getPreviousDecl(); |
13879 | if (!Previous) |
13880 | return true; |
13881 | OldTag = Previous->getTagKind(); |
13882 | } |
13883 | |
13884 | bool isTemplate = false; |
13885 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) |
13886 | isTemplate = Record->getDescribedClassTemplate(); |
13887 | |
13888 | if (inTemplateInstantiation()) { |
13889 | if (OldTag != NewTag) { |
13890 | // In a template instantiation, do not offer fix-its for tag mismatches |
13891 | // since they usually mess up the template instead of fixing the problem. |
13892 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) |
13893 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name |
13894 | << getRedeclDiagFromTagKind(OldTag); |
13895 | // FIXME: Note previous location? |
13896 | } |
13897 | return true; |
13898 | } |
13899 | |
13900 | if (isDefinition) { |
13901 | // On definitions, check all previous tags and issue a fix-it for each |
13902 | // one that doesn't match the current tag. |
13903 | if (Previous->getDefinition()) { |
13904 | // Don't suggest fix-its for redefinitions. |
13905 | return true; |
13906 | } |
13907 | |
13908 | bool previousMismatch = false; |
13909 | for (const TagDecl *I : Previous->redecls()) { |
13910 | if (I->getTagKind() != NewTag) { |
13911 | // Ignore previous declarations for which the warning was disabled. |
13912 | if (IsIgnored(I)) |
13913 | continue; |
13914 | |
13915 | if (!previousMismatch) { |
13916 | previousMismatch = true; |
13917 | Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) |
13918 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name |
13919 | << getRedeclDiagFromTagKind(I->getTagKind()); |
13920 | } |
13921 | Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) |
13922 | << getRedeclDiagFromTagKind(NewTag) |
13923 | << FixItHint::CreateReplacement(I->getInnerLocStart(), |
13924 | TypeWithKeyword::getTagTypeKindName(NewTag)); |
13925 | } |
13926 | } |
13927 | return true; |
13928 | } |
13929 | |
13930 | // Identify the prevailing tag kind: this is the kind of the definition (if |
13931 | // there is a non-ignored definition), or otherwise the kind of the prior |
13932 | // (non-ignored) declaration. |
13933 | const TagDecl *PrevDef = Previous->getDefinition(); |
13934 | if (PrevDef && IsIgnored(PrevDef)) |
13935 | PrevDef = nullptr; |
13936 | const TagDecl *Redecl = PrevDef ? PrevDef : Previous; |
13937 | if (Redecl->getTagKind() != NewTag) { |
13938 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) |
13939 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name |
13940 | << getRedeclDiagFromTagKind(OldTag); |
13941 | Diag(Redecl->getLocation(), diag::note_previous_use); |
13942 | |
13943 | // If there is a previous definition, suggest a fix-it. |
13944 | if (PrevDef) { |
13945 | Diag(NewTagLoc, diag::note_struct_class_suggestion) |
13946 | << getRedeclDiagFromTagKind(Redecl->getTagKind()) |
13947 | << FixItHint::CreateReplacement(SourceRange(NewTagLoc), |
13948 | TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); |
13949 | } |
13950 | } |
13951 | |
13952 | return true; |
13953 | } |
13954 | |
13955 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name |
13956 | /// from an outer enclosing namespace or file scope inside a friend declaration. |
13957 | /// This should provide the commented out code in the following snippet: |
13958 | /// namespace N { |
13959 | /// struct X; |
13960 | /// namespace M { |
13961 | /// struct Y { friend struct /*N::*/ X; }; |
13962 | /// } |
13963 | /// } |
13964 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, |
13965 | SourceLocation NameLoc) { |
13966 | // While the decl is in a namespace, do repeated lookup of that name and see |
13967 | // if we get the same namespace back. If we do not, continue until |
13968 | // translation unit scope, at which point we have a fully qualified NNS. |
13969 | SmallVector<IdentifierInfo *, 4> Namespaces; |
13970 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); |
13971 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { |
13972 | // This tag should be declared in a namespace, which can only be enclosed by |
13973 | // other namespaces. Bail if there's an anonymous namespace in the chain. |
13974 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); |
13975 | if (!Namespace || Namespace->isAnonymousNamespace()) |
13976 | return FixItHint(); |
13977 | IdentifierInfo *II = Namespace->getIdentifier(); |
13978 | Namespaces.push_back(II); |
13979 | NamedDecl *Lookup = SemaRef.LookupSingleName( |
13980 | S, II, NameLoc, Sema::LookupNestedNameSpecifierName); |
13981 | if (Lookup == Namespace) |
13982 | break; |
13983 | } |
13984 | |
13985 | // Once we have all the namespaces, reverse them to go outermost first, and |
13986 | // build an NNS. |
13987 | SmallString<64> Insertion; |
13988 | llvm::raw_svector_ostream OS(Insertion); |
13989 | if (DC->isTranslationUnit()) |
13990 | OS << "::"; |
13991 | std::reverse(Namespaces.begin(), Namespaces.end()); |
13992 | for (auto *II : Namespaces) |
13993 | OS << II->getName() << "::"; |
13994 | return FixItHint::CreateInsertion(NameLoc, Insertion); |
13995 | } |
13996 | |
13997 | /// Determine whether a tag originally declared in context \p OldDC can |
13998 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup |
13999 | /// found a declaration in \p OldDC as a previous decl, perhaps through a |
14000 | /// using-declaration). |
14001 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, |
14002 | DeclContext *NewDC) { |
14003 | OldDC = OldDC->getRedeclContext(); |
14004 | NewDC = NewDC->getRedeclContext(); |
14005 | |
14006 | if (OldDC->Equals(NewDC)) |
14007 | return true; |
14008 | |
14009 | // In MSVC mode, we allow a redeclaration if the contexts are related (either |
14010 | // encloses the other). |
14011 | if (S.getLangOpts().MSVCCompat && |
14012 | (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) |
14013 | return true; |
14014 | |
14015 | return false; |
14016 | } |
14017 | |
14018 | /// This is invoked when we see 'struct foo' or 'struct {'. In the |
14019 | /// former case, Name will be non-null. In the later case, Name will be null. |
14020 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a |
14021 | /// reference/declaration/definition of a tag. |
14022 | /// |
14023 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or |
14024 | /// trailing-type-specifier) other than one in an alias-declaration. |
14025 | /// |
14026 | /// \param SkipBody If non-null, will be set to indicate if the caller should |
14027 | /// skip the definition of this tag and treat it as if it were a declaration. |
14028 | Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, |
14029 | SourceLocation KWLoc, CXXScopeSpec &SS, |
14030 | IdentifierInfo *Name, SourceLocation NameLoc, |
14031 | const ParsedAttributesView &Attrs, AccessSpecifier AS, |
14032 | SourceLocation ModulePrivateLoc, |
14033 | MultiTemplateParamsArg TemplateParameterLists, |
14034 | bool &OwnedDecl, bool &IsDependent, |
14035 | SourceLocation ScopedEnumKWLoc, |
14036 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, |
14037 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, |
14038 | SkipBodyInfo *SkipBody) { |
14039 | // If this is not a definition, it must have a name. |
14040 | IdentifierInfo *OrigName = Name; |
14041 | assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14042, __PRETTY_FUNCTION__)) |
14042 | "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14042, __PRETTY_FUNCTION__)); |
14043 | assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference) ? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14043, __PRETTY_FUNCTION__)); |
14044 | |
14045 | OwnedDecl = false; |
14046 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); |
14047 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); |
14048 | |
14049 | // FIXME: Check member specializations more carefully. |
14050 | bool isMemberSpecialization = false; |
14051 | bool Invalid = false; |
14052 | |
14053 | // We only need to do this matching if we have template parameters |
14054 | // or a scope specifier, which also conveniently avoids this work |
14055 | // for non-C++ cases. |
14056 | if (TemplateParameterLists.size() > 0 || |
14057 | (SS.isNotEmpty() && TUK != TUK_Reference)) { |
14058 | if (TemplateParameterList *TemplateParams = |
14059 | MatchTemplateParametersToScopeSpecifier( |
14060 | KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, |
14061 | TUK == TUK_Friend, isMemberSpecialization, Invalid)) { |
14062 | if (Kind == TTK_Enum) { |
14063 | Diag(KWLoc, diag::err_enum_template); |
14064 | return nullptr; |
14065 | } |
14066 | |
14067 | if (TemplateParams->size() > 0) { |
14068 | // This is a declaration or definition of a class template (which may |
14069 | // be a member of another template). |
14070 | |
14071 | if (Invalid) |
14072 | return nullptr; |
14073 | |
14074 | OwnedDecl = false; |
14075 | DeclResult Result = CheckClassTemplate( |
14076 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, |
14077 | AS, ModulePrivateLoc, |
14078 | /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, |
14079 | TemplateParameterLists.data(), SkipBody); |
14080 | return Result.get(); |
14081 | } else { |
14082 | // The "template<>" header is extraneous. |
14083 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) |
14084 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; |
14085 | isMemberSpecialization = true; |
14086 | } |
14087 | } |
14088 | } |
14089 | |
14090 | // Figure out the underlying type if this a enum declaration. We need to do |
14091 | // this early, because it's needed to detect if this is an incompatible |
14092 | // redeclaration. |
14093 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; |
14094 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; |
14095 | |
14096 | if (Kind == TTK_Enum) { |
14097 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { |
14098 | // No underlying type explicitly specified, or we failed to parse the |
14099 | // type, default to int. |
14100 | EnumUnderlying = Context.IntTy.getTypePtr(); |
14101 | } else if (UnderlyingType.get()) { |
14102 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an |
14103 | // integral type; any cv-qualification is ignored. |
14104 | TypeSourceInfo *TI = nullptr; |
14105 | GetTypeFromParser(UnderlyingType.get(), &TI); |
14106 | EnumUnderlying = TI; |
14107 | |
14108 | if (CheckEnumUnderlyingType(TI)) |
14109 | // Recover by falling back to int. |
14110 | EnumUnderlying = Context.IntTy.getTypePtr(); |
14111 | |
14112 | if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, |
14113 | UPPC_FixedUnderlyingType)) |
14114 | EnumUnderlying = Context.IntTy.getTypePtr(); |
14115 | |
14116 | } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
14117 | // For MSVC ABI compatibility, unfixed enums must use an underlying type |
14118 | // of 'int'. However, if this is an unfixed forward declaration, don't set |
14119 | // the underlying type unless the user enables -fms-compatibility. This |
14120 | // makes unfixed forward declared enums incomplete and is more conforming. |
14121 | if (TUK == TUK_Definition || getLangOpts().MSVCCompat) |
14122 | EnumUnderlying = Context.IntTy.getTypePtr(); |
14123 | } |
14124 | } |
14125 | |
14126 | DeclContext *SearchDC = CurContext; |
14127 | DeclContext *DC = CurContext; |
14128 | bool isStdBadAlloc = false; |
14129 | bool isStdAlignValT = false; |
14130 | |
14131 | RedeclarationKind Redecl = forRedeclarationInCurContext(); |
14132 | if (TUK == TUK_Friend || TUK == TUK_Reference) |
14133 | Redecl = NotForRedeclaration; |
14134 | |
14135 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C |
14136 | /// implemented asks for structural equivalence checking, the returned decl |
14137 | /// here is passed back to the parser, allowing the tag body to be parsed. |
14138 | auto createTagFromNewDecl = [&]() -> TagDecl * { |
14139 | assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage" ) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14139, __PRETTY_FUNCTION__)); |
14140 | // If there is an identifier, use the location of the identifier as the |
14141 | // location of the decl, otherwise use the location of the struct/union |
14142 | // keyword. |
14143 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; |
14144 | TagDecl *New = nullptr; |
14145 | |
14146 | if (Kind == TTK_Enum) { |
14147 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, |
14148 | ScopedEnum, ScopedEnumUsesClassTag, IsFixed); |
14149 | // If this is an undefined enum, bail. |
14150 | if (TUK != TUK_Definition && !Invalid) |
14151 | return nullptr; |
14152 | if (EnumUnderlying) { |
14153 | EnumDecl *ED = cast<EnumDecl>(New); |
14154 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) |
14155 | ED->setIntegerTypeSourceInfo(TI); |
14156 | else |
14157 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); |
14158 | ED->setPromotionType(ED->getIntegerType()); |
14159 | } |
14160 | } else { // struct/union |
14161 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, |
14162 | nullptr); |
14163 | } |
14164 | |
14165 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { |
14166 | // Add alignment attributes if necessary; these attributes are checked |
14167 | // when the ASTContext lays out the structure. |
14168 | // |
14169 | // It is important for implementing the correct semantics that this |
14170 | // happen here (in ActOnTag). The #pragma pack stack is |
14171 | // maintained as a result of parser callbacks which can occur at |
14172 | // many points during the parsing of a struct declaration (because |
14173 | // the #pragma tokens are effectively skipped over during the |
14174 | // parsing of the struct). |
14175 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { |
14176 | AddAlignmentAttributesForRecord(RD); |
14177 | AddMsStructLayoutForRecord(RD); |
14178 | } |
14179 | } |
14180 | New->setLexicalDeclContext(CurContext); |
14181 | return New; |
14182 | }; |
14183 | |
14184 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); |
14185 | if (Name && SS.isNotEmpty()) { |
14186 | // We have a nested-name tag ('struct foo::bar'). |
14187 | |
14188 | // Check for invalid 'foo::'. |
14189 | if (SS.isInvalid()) { |
14190 | Name = nullptr; |
14191 | goto CreateNewDecl; |
14192 | } |
14193 | |
14194 | // If this is a friend or a reference to a class in a dependent |
14195 | // context, don't try to make a decl for it. |
14196 | if (TUK == TUK_Friend || TUK == TUK_Reference) { |
14197 | DC = computeDeclContext(SS, false); |
14198 | if (!DC) { |
14199 | IsDependent = true; |
14200 | return nullptr; |
14201 | } |
14202 | } else { |
14203 | DC = computeDeclContext(SS, true); |
14204 | if (!DC) { |
14205 | Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) |
14206 | << SS.getRange(); |
14207 | return nullptr; |
14208 | } |
14209 | } |
14210 | |
14211 | if (RequireCompleteDeclContext(SS, DC)) |
14212 | return nullptr; |
14213 | |
14214 | SearchDC = DC; |
14215 | // Look-up name inside 'foo::'. |
14216 | LookupQualifiedName(Previous, DC); |
14217 | |
14218 | if (Previous.isAmbiguous()) |
14219 | return nullptr; |
14220 | |
14221 | if (Previous.empty()) { |
14222 | // Name lookup did not find anything. However, if the |
14223 | // nested-name-specifier refers to the current instantiation, |
14224 | // and that current instantiation has any dependent base |
14225 | // classes, we might find something at instantiation time: treat |
14226 | // this as a dependent elaborated-type-specifier. |
14227 | // But this only makes any sense for reference-like lookups. |
14228 | if (Previous.wasNotFoundInCurrentInstantiation() && |
14229 | (TUK == TUK_Reference || TUK == TUK_Friend)) { |
14230 | IsDependent = true; |
14231 | return nullptr; |
14232 | } |
14233 | |
14234 | // A tag 'foo::bar' must already exist. |
14235 | Diag(NameLoc, diag::err_not_tag_in_scope) |
14236 | << Kind << Name << DC << SS.getRange(); |
14237 | Name = nullptr; |
14238 | Invalid = true; |
14239 | goto CreateNewDecl; |
14240 | } |
14241 | } else if (Name) { |
14242 | // C++14 [class.mem]p14: |
14243 | // If T is the name of a class, then each of the following shall have a |
14244 | // name different from T: |
14245 | // -- every member of class T that is itself a type |
14246 | if (TUK != TUK_Reference && TUK != TUK_Friend && |
14247 | DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) |
14248 | return nullptr; |
14249 | |
14250 | // If this is a named struct, check to see if there was a previous forward |
14251 | // declaration or definition. |
14252 | // FIXME: We're looking into outer scopes here, even when we |
14253 | // shouldn't be. Doing so can result in ambiguities that we |
14254 | // shouldn't be diagnosing. |
14255 | LookupName(Previous, S); |
14256 | |
14257 | // When declaring or defining a tag, ignore ambiguities introduced |
14258 | // by types using'ed into this scope. |
14259 | if (Previous.isAmbiguous() && |
14260 | (TUK == TUK_Definition || TUK == TUK_Declaration)) { |
14261 | LookupResult::Filter F = Previous.makeFilter(); |
14262 | while (F.hasNext()) { |
14263 | NamedDecl *ND = F.next(); |
14264 | if (!ND->getDeclContext()->getRedeclContext()->Equals( |
14265 | SearchDC->getRedeclContext())) |
14266 | F.erase(); |
14267 | } |
14268 | F.done(); |
14269 | } |
14270 | |
14271 | // C++11 [namespace.memdef]p3: |
14272 | // If the name in a friend declaration is neither qualified nor |
14273 | // a template-id and the declaration is a function or an |
14274 | // elaborated-type-specifier, the lookup to determine whether |
14275 | // the entity has been previously declared shall not consider |
14276 | // any scopes outside the innermost enclosing namespace. |
14277 | // |
14278 | // MSVC doesn't implement the above rule for types, so a friend tag |
14279 | // declaration may be a redeclaration of a type declared in an enclosing |
14280 | // scope. They do implement this rule for friend functions. |
14281 | // |
14282 | // Does it matter that this should be by scope instead of by |
14283 | // semantic context? |
14284 | if (!Previous.empty() && TUK == TUK_Friend) { |
14285 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); |
14286 | LookupResult::Filter F = Previous.makeFilter(); |
14287 | bool FriendSawTagOutsideEnclosingNamespace = false; |
14288 | while (F.hasNext()) { |
14289 | NamedDecl *ND = F.next(); |
14290 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); |
14291 | if (DC->isFileContext() && |
14292 | !EnclosingNS->Encloses(ND->getDeclContext())) { |
14293 | if (getLangOpts().MSVCCompat) |
14294 | FriendSawTagOutsideEnclosingNamespace = true; |
14295 | else |
14296 | F.erase(); |
14297 | } |
14298 | } |
14299 | F.done(); |
14300 | |
14301 | // Diagnose this MSVC extension in the easy case where lookup would have |
14302 | // unambiguously found something outside the enclosing namespace. |
14303 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { |
14304 | NamedDecl *ND = Previous.getFoundDecl(); |
14305 | Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) |
14306 | << createFriendTagNNSFixIt(*this, ND, S, NameLoc); |
14307 | } |
14308 | } |
14309 | |
14310 | // Note: there used to be some attempt at recovery here. |
14311 | if (Previous.isAmbiguous()) |
14312 | return nullptr; |
14313 | |
14314 | if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { |
14315 | // FIXME: This makes sure that we ignore the contexts associated |
14316 | // with C structs, unions, and enums when looking for a matching |
14317 | // tag declaration or definition. See the similar lookup tweak |
14318 | // in Sema::LookupName; is there a better way to deal with this? |
14319 | while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) |
14320 | SearchDC = SearchDC->getParent(); |
14321 | } |
14322 | } |
14323 | |
14324 | if (Previous.isSingleResult() && |
14325 | Previous.getFoundDecl()->isTemplateParameter()) { |
14326 | // Maybe we will complain about the shadowed template parameter. |
14327 | DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); |
14328 | // Just pretend that we didn't see the previous declaration. |
14329 | Previous.clear(); |
14330 | } |
14331 | |
14332 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && |
14333 | DC->Equals(getStdNamespace())) { |
14334 | if (Name->isStr("bad_alloc")) { |
14335 | // This is a declaration of or a reference to "std::bad_alloc". |
14336 | isStdBadAlloc = true; |
14337 | |
14338 | // If std::bad_alloc has been implicitly declared (but made invisible to |
14339 | // name lookup), fill in this implicit declaration as the previous |
14340 | // declaration, so that the declarations get chained appropriately. |
14341 | if (Previous.empty() && StdBadAlloc) |
14342 | Previous.addDecl(getStdBadAlloc()); |
14343 | } else if (Name->isStr("align_val_t")) { |
14344 | isStdAlignValT = true; |
14345 | if (Previous.empty() && StdAlignValT) |
14346 | Previous.addDecl(getStdAlignValT()); |
14347 | } |
14348 | } |
14349 | |
14350 | // If we didn't find a previous declaration, and this is a reference |
14351 | // (or friend reference), move to the correct scope. In C++, we |
14352 | // also need to do a redeclaration lookup there, just in case |
14353 | // there's a shadow friend decl. |
14354 | if (Name && Previous.empty() && |
14355 | (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { |
14356 | if (Invalid) goto CreateNewDecl; |
14357 | assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14357, __PRETTY_FUNCTION__)); |
14358 | |
14359 | if (TUK == TUK_Reference || IsTemplateParamOrArg) { |
14360 | // C++ [basic.scope.pdecl]p5: |
14361 | // -- for an elaborated-type-specifier of the form |
14362 | // |
14363 | // class-key identifier |
14364 | // |
14365 | // if the elaborated-type-specifier is used in the |
14366 | // decl-specifier-seq or parameter-declaration-clause of a |
14367 | // function defined in namespace scope, the identifier is |
14368 | // declared as a class-name in the namespace that contains |
14369 | // the declaration; otherwise, except as a friend |
14370 | // declaration, the identifier is declared in the smallest |
14371 | // non-class, non-function-prototype scope that contains the |
14372 | // declaration. |
14373 | // |
14374 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for |
14375 | // C structs and unions. |
14376 | // |
14377 | // It is an error in C++ to declare (rather than define) an enum |
14378 | // type, including via an elaborated type specifier. We'll |
14379 | // diagnose that later; for now, declare the enum in the same |
14380 | // scope as we would have picked for any other tag type. |
14381 | // |
14382 | // GNU C also supports this behavior as part of its incomplete |
14383 | // enum types extension, while GNU C++ does not. |
14384 | // |
14385 | // Find the context where we'll be declaring the tag. |
14386 | // FIXME: We would like to maintain the current DeclContext as the |
14387 | // lexical context, |
14388 | SearchDC = getTagInjectionContext(SearchDC); |
14389 | |
14390 | // Find the scope where we'll be declaring the tag. |
14391 | S = getTagInjectionScope(S, getLangOpts()); |
14392 | } else { |
14393 | assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14393, __PRETTY_FUNCTION__)); |
14394 | // C++ [namespace.memdef]p3: |
14395 | // If a friend declaration in a non-local class first declares a |
14396 | // class or function, the friend class or function is a member of |
14397 | // the innermost enclosing namespace. |
14398 | SearchDC = SearchDC->getEnclosingNamespaceContext(); |
14399 | } |
14400 | |
14401 | // In C++, we need to do a redeclaration lookup to properly |
14402 | // diagnose some problems. |
14403 | // FIXME: redeclaration lookup is also used (with and without C++) to find a |
14404 | // hidden declaration so that we don't get ambiguity errors when using a |
14405 | // type declared by an elaborated-type-specifier. In C that is not correct |
14406 | // and we should instead merge compatible types found by lookup. |
14407 | if (getLangOpts().CPlusPlus) { |
14408 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); |
14409 | LookupQualifiedName(Previous, SearchDC); |
14410 | } else { |
14411 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); |
14412 | LookupName(Previous, S); |
14413 | } |
14414 | } |
14415 | |
14416 | // If we have a known previous declaration to use, then use it. |
14417 | if (Previous.empty() && SkipBody && SkipBody->Previous) |
14418 | Previous.addDecl(SkipBody->Previous); |
14419 | |
14420 | if (!Previous.empty()) { |
14421 | NamedDecl *PrevDecl = Previous.getFoundDecl(); |
14422 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); |
14423 | |
14424 | // It's okay to have a tag decl in the same scope as a typedef |
14425 | // which hides a tag decl in the same scope. Finding this |
14426 | // insanity with a redeclaration lookup can only actually happen |
14427 | // in C++. |
14428 | // |
14429 | // This is also okay for elaborated-type-specifiers, which is |
14430 | // technically forbidden by the current standard but which is |
14431 | // okay according to the likely resolution of an open issue; |
14432 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 |
14433 | if (getLangOpts().CPlusPlus) { |
14434 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { |
14435 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { |
14436 | TagDecl *Tag = TT->getDecl(); |
14437 | if (Tag->getDeclName() == Name && |
14438 | Tag->getDeclContext()->getRedeclContext() |
14439 | ->Equals(TD->getDeclContext()->getRedeclContext())) { |
14440 | PrevDecl = Tag; |
14441 | Previous.clear(); |
14442 | Previous.addDecl(Tag); |
14443 | Previous.resolveKind(); |
14444 | } |
14445 | } |
14446 | } |
14447 | } |
14448 | |
14449 | // If this is a redeclaration of a using shadow declaration, it must |
14450 | // declare a tag in the same context. In MSVC mode, we allow a |
14451 | // redefinition if either context is within the other. |
14452 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { |
14453 | auto *OldTag = dyn_cast<TagDecl>(PrevDecl); |
14454 | if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && |
14455 | isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && |
14456 | !(OldTag && isAcceptableTagRedeclContext( |
14457 | *this, OldTag->getDeclContext(), SearchDC))) { |
14458 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); |
14459 | Diag(Shadow->getTargetDecl()->getLocation(), |
14460 | diag::note_using_decl_target); |
14461 | Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) |
14462 | << 0; |
14463 | // Recover by ignoring the old declaration. |
14464 | Previous.clear(); |
14465 | goto CreateNewDecl; |
14466 | } |
14467 | } |
14468 | |
14469 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { |
14470 | // If this is a use of a previous tag, or if the tag is already declared |
14471 | // in the same scope (so that the definition/declaration completes or |
14472 | // rementions the tag), reuse the decl. |
14473 | if (TUK == TUK_Reference || TUK == TUK_Friend || |
14474 | isDeclInScope(DirectPrevDecl, SearchDC, S, |
14475 | SS.isNotEmpty() || isMemberSpecialization)) { |
14476 | // Make sure that this wasn't declared as an enum and now used as a |
14477 | // struct or something similar. |
14478 | if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, |
14479 | TUK == TUK_Definition, KWLoc, |
14480 | Name)) { |
14481 | bool SafeToContinue |
14482 | = (PrevTagDecl->getTagKind() != TTK_Enum && |
14483 | Kind != TTK_Enum); |
14484 | if (SafeToContinue) |
14485 | Diag(KWLoc, diag::err_use_with_wrong_tag) |
14486 | << Name |
14487 | << FixItHint::CreateReplacement(SourceRange(KWLoc), |
14488 | PrevTagDecl->getKindName()); |
14489 | else |
14490 | Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; |
14491 | Diag(PrevTagDecl->getLocation(), diag::note_previous_use); |
14492 | |
14493 | if (SafeToContinue) |
14494 | Kind = PrevTagDecl->getTagKind(); |
14495 | else { |
14496 | // Recover by making this an anonymous redefinition. |
14497 | Name = nullptr; |
14498 | Previous.clear(); |
14499 | Invalid = true; |
14500 | } |
14501 | } |
14502 | |
14503 | if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { |
14504 | const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); |
14505 | |
14506 | // If this is an elaborated-type-specifier for a scoped enumeration, |
14507 | // the 'class' keyword is not necessary and not permitted. |
14508 | if (TUK == TUK_Reference || TUK == TUK_Friend) { |
14509 | if (ScopedEnum) |
14510 | Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) |
14511 | << PrevEnum->isScoped() |
14512 | << FixItHint::CreateRemoval(ScopedEnumKWLoc); |
14513 | return PrevTagDecl; |
14514 | } |
14515 | |
14516 | QualType EnumUnderlyingTy; |
14517 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) |
14518 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); |
14519 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) |
14520 | EnumUnderlyingTy = QualType(T, 0); |
14521 | |
14522 | // All conflicts with previous declarations are recovered by |
14523 | // returning the previous declaration, unless this is a definition, |
14524 | // in which case we want the caller to bail out. |
14525 | if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, |
14526 | ScopedEnum, EnumUnderlyingTy, |
14527 | IsFixed, PrevEnum)) |
14528 | return TUK == TUK_Declaration ? PrevTagDecl : nullptr; |
14529 | } |
14530 | |
14531 | // C++11 [class.mem]p1: |
14532 | // A member shall not be declared twice in the member-specification, |
14533 | // except that a nested class or member class template can be declared |
14534 | // and then later defined. |
14535 | if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && |
14536 | S->isDeclScope(PrevDecl)) { |
14537 | Diag(NameLoc, diag::ext_member_redeclared); |
14538 | Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); |
14539 | } |
14540 | |
14541 | if (!Invalid) { |
14542 | // If this is a use, just return the declaration we found, unless |
14543 | // we have attributes. |
14544 | if (TUK == TUK_Reference || TUK == TUK_Friend) { |
14545 | if (!Attrs.empty()) { |
14546 | // FIXME: Diagnose these attributes. For now, we create a new |
14547 | // declaration to hold them. |
14548 | } else if (TUK == TUK_Reference && |
14549 | (PrevTagDecl->getFriendObjectKind() == |
14550 | Decl::FOK_Undeclared || |
14551 | PrevDecl->getOwningModule() != getCurrentModule()) && |
14552 | SS.isEmpty()) { |
14553 | // This declaration is a reference to an existing entity, but |
14554 | // has different visibility from that entity: it either makes |
14555 | // a friend visible or it makes a type visible in a new module. |
14556 | // In either case, create a new declaration. We only do this if |
14557 | // the declaration would have meant the same thing if no prior |
14558 | // declaration were found, that is, if it was found in the same |
14559 | // scope where we would have injected a declaration. |
14560 | if (!getTagInjectionContext(CurContext)->getRedeclContext() |
14561 | ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) |
14562 | return PrevTagDecl; |
14563 | // This is in the injected scope, create a new declaration in |
14564 | // that scope. |
14565 | S = getTagInjectionScope(S, getLangOpts()); |
14566 | } else { |
14567 | return PrevTagDecl; |
14568 | } |
14569 | } |
14570 | |
14571 | // Diagnose attempts to redefine a tag. |
14572 | if (TUK == TUK_Definition) { |
14573 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { |
14574 | // If we're defining a specialization and the previous definition |
14575 | // is from an implicit instantiation, don't emit an error |
14576 | // here; we'll catch this in the general case below. |
14577 | bool IsExplicitSpecializationAfterInstantiation = false; |
14578 | if (isMemberSpecialization) { |
14579 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) |
14580 | IsExplicitSpecializationAfterInstantiation = |
14581 | RD->getTemplateSpecializationKind() != |
14582 | TSK_ExplicitSpecialization; |
14583 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) |
14584 | IsExplicitSpecializationAfterInstantiation = |
14585 | ED->getTemplateSpecializationKind() != |
14586 | TSK_ExplicitSpecialization; |
14587 | } |
14588 | |
14589 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do |
14590 | // not keep more that one definition around (merge them). However, |
14591 | // ensure the decl passes the structural compatibility check in |
14592 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). |
14593 | NamedDecl *Hidden = nullptr; |
14594 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { |
14595 | // There is a definition of this tag, but it is not visible. We |
14596 | // explicitly make use of C++'s one definition rule here, and |
14597 | // assume that this definition is identical to the hidden one |
14598 | // we already have. Make the existing definition visible and |
14599 | // use it in place of this one. |
14600 | if (!getLangOpts().CPlusPlus) { |
14601 | // Postpone making the old definition visible until after we |
14602 | // complete parsing the new one and do the structural |
14603 | // comparison. |
14604 | SkipBody->CheckSameAsPrevious = true; |
14605 | SkipBody->New = createTagFromNewDecl(); |
14606 | SkipBody->Previous = Def; |
14607 | return Def; |
14608 | } else { |
14609 | SkipBody->ShouldSkip = true; |
14610 | SkipBody->Previous = Def; |
14611 | makeMergedDefinitionVisible(Hidden); |
14612 | // Carry on and handle it like a normal definition. We'll |
14613 | // skip starting the definitiion later. |
14614 | } |
14615 | } else if (!IsExplicitSpecializationAfterInstantiation) { |
14616 | // A redeclaration in function prototype scope in C isn't |
14617 | // visible elsewhere, so merely issue a warning. |
14618 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) |
14619 | Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; |
14620 | else |
14621 | Diag(NameLoc, diag::err_redefinition) << Name; |
14622 | notePreviousDefinition(Def, |
14623 | NameLoc.isValid() ? NameLoc : KWLoc); |
14624 | // If this is a redefinition, recover by making this |
14625 | // struct be anonymous, which will make any later |
14626 | // references get the previous definition. |
14627 | Name = nullptr; |
14628 | Previous.clear(); |
14629 | Invalid = true; |
14630 | } |
14631 | } else { |
14632 | // If the type is currently being defined, complain |
14633 | // about a nested redefinition. |
14634 | auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); |
14635 | if (TD->isBeingDefined()) { |
14636 | Diag(NameLoc, diag::err_nested_redefinition) << Name; |
14637 | Diag(PrevTagDecl->getLocation(), |
14638 | diag::note_previous_definition); |
14639 | Name = nullptr; |
14640 | Previous.clear(); |
14641 | Invalid = true; |
14642 | } |
14643 | } |
14644 | |
14645 | // Okay, this is definition of a previously declared or referenced |
14646 | // tag. We're going to create a new Decl for it. |
14647 | } |
14648 | |
14649 | // Okay, we're going to make a redeclaration. If this is some kind |
14650 | // of reference, make sure we build the redeclaration in the same DC |
14651 | // as the original, and ignore the current access specifier. |
14652 | if (TUK == TUK_Friend || TUK == TUK_Reference) { |
14653 | SearchDC = PrevTagDecl->getDeclContext(); |
14654 | AS = AS_none; |
14655 | } |
14656 | } |
14657 | // If we get here we have (another) forward declaration or we |
14658 | // have a definition. Just create a new decl. |
14659 | |
14660 | } else { |
14661 | // If we get here, this is a definition of a new tag type in a nested |
14662 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a |
14663 | // new decl/type. We set PrevDecl to NULL so that the entities |
14664 | // have distinct types. |
14665 | Previous.clear(); |
14666 | } |
14667 | // If we get here, we're going to create a new Decl. If PrevDecl |
14668 | // is non-NULL, it's a definition of the tag declared by |
14669 | // PrevDecl. If it's NULL, we have a new definition. |
14670 | |
14671 | // Otherwise, PrevDecl is not a tag, but was found with tag |
14672 | // lookup. This is only actually possible in C++, where a few |
14673 | // things like templates still live in the tag namespace. |
14674 | } else { |
14675 | // Use a better diagnostic if an elaborated-type-specifier |
14676 | // found the wrong kind of type on the first |
14677 | // (non-redeclaration) lookup. |
14678 | if ((TUK == TUK_Reference || TUK == TUK_Friend) && |
14679 | !Previous.isForRedeclaration()) { |
14680 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); |
14681 | Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK |
14682 | << Kind; |
14683 | Diag(PrevDecl->getLocation(), diag::note_declared_at); |
14684 | Invalid = true; |
14685 | |
14686 | // Otherwise, only diagnose if the declaration is in scope. |
14687 | } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, |
14688 | SS.isNotEmpty() || isMemberSpecialization)) { |
14689 | // do nothing |
14690 | |
14691 | // Diagnose implicit declarations introduced by elaborated types. |
14692 | } else if (TUK == TUK_Reference || TUK == TUK_Friend) { |
14693 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); |
14694 | Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; |
14695 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; |
14696 | Invalid = true; |
14697 | |
14698 | // Otherwise it's a declaration. Call out a particularly common |
14699 | // case here. |
14700 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { |
14701 | unsigned Kind = 0; |
14702 | if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; |
14703 | Diag(NameLoc, diag::err_tag_definition_of_typedef) |
14704 | << Name << Kind << TND->getUnderlyingType(); |
14705 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; |
14706 | Invalid = true; |
14707 | |
14708 | // Otherwise, diagnose. |
14709 | } else { |
14710 | // The tag name clashes with something else in the target scope, |
14711 | // issue an error and recover by making this tag be anonymous. |
14712 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; |
14713 | notePreviousDefinition(PrevDecl, NameLoc); |
14714 | Name = nullptr; |
14715 | Invalid = true; |
14716 | } |
14717 | |
14718 | // The existing declaration isn't relevant to us; we're in a |
14719 | // new scope, so clear out the previous declaration. |
14720 | Previous.clear(); |
14721 | } |
14722 | } |
14723 | |
14724 | CreateNewDecl: |
14725 | |
14726 | TagDecl *PrevDecl = nullptr; |
14727 | if (Previous.isSingleResult()) |
14728 | PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); |
14729 | |
14730 | // If there is an identifier, use the location of the identifier as the |
14731 | // location of the decl, otherwise use the location of the struct/union |
14732 | // keyword. |
14733 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; |
14734 | |
14735 | // Otherwise, create a new declaration. If there is a previous |
14736 | // declaration of the same entity, the two will be linked via |
14737 | // PrevDecl. |
14738 | TagDecl *New; |
14739 | |
14740 | if (Kind == TTK_Enum) { |
14741 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: |
14742 | // enum X { A, B, C } D; D should chain to X. |
14743 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, |
14744 | cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, |
14745 | ScopedEnumUsesClassTag, IsFixed); |
14746 | |
14747 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) |
14748 | StdAlignValT = cast<EnumDecl>(New); |
14749 | |
14750 | // If this is an undefined enum, warn. |
14751 | if (TUK != TUK_Definition && !Invalid) { |
14752 | TagDecl *Def; |
14753 | if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC) && |
14754 | cast<EnumDecl>(New)->isFixed()) { |
14755 | // C++0x: 7.2p2: opaque-enum-declaration. |
14756 | // Conflicts are diagnosed above. Do nothing. |
14757 | } |
14758 | else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { |
14759 | Diag(Loc, diag::ext_forward_ref_enum_def) |
14760 | << New; |
14761 | Diag(Def->getLocation(), diag::note_previous_definition); |
14762 | } else { |
14763 | unsigned DiagID = diag::ext_forward_ref_enum; |
14764 | if (getLangOpts().MSVCCompat) |
14765 | DiagID = diag::ext_ms_forward_ref_enum; |
14766 | else if (getLangOpts().CPlusPlus) |
14767 | DiagID = diag::err_forward_ref_enum; |
14768 | Diag(Loc, DiagID); |
14769 | } |
14770 | } |
14771 | |
14772 | if (EnumUnderlying) { |
14773 | EnumDecl *ED = cast<EnumDecl>(New); |
14774 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) |
14775 | ED->setIntegerTypeSourceInfo(TI); |
14776 | else |
14777 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); |
14778 | ED->setPromotionType(ED->getIntegerType()); |
14779 | assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete" ) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14779, __PRETTY_FUNCTION__)); |
14780 | } |
14781 | } else { |
14782 | // struct/union/class |
14783 | |
14784 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: |
14785 | // struct X { int A; } D; D should chain to X. |
14786 | if (getLangOpts().CPlusPlus) { |
14787 | // FIXME: Look for a way to use RecordDecl for simple structs. |
14788 | New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, |
14789 | cast_or_null<CXXRecordDecl>(PrevDecl)); |
14790 | |
14791 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) |
14792 | StdBadAlloc = cast<CXXRecordDecl>(New); |
14793 | } else |
14794 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, |
14795 | cast_or_null<RecordDecl>(PrevDecl)); |
14796 | } |
14797 | |
14798 | // C++11 [dcl.type]p3: |
14799 | // A type-specifier-seq shall not define a class or enumeration [...]. |
14800 | if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && |
14801 | TUK == TUK_Definition) { |
14802 | Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) |
14803 | << Context.getTagDeclType(New); |
14804 | Invalid = true; |
14805 | } |
14806 | |
14807 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && |
14808 | DC->getDeclKind() == Decl::Enum) { |
14809 | Diag(New->getLocation(), diag::err_type_defined_in_enum) |
14810 | << Context.getTagDeclType(New); |
14811 | Invalid = true; |
14812 | } |
14813 | |
14814 | // Maybe add qualifier info. |
14815 | if (SS.isNotEmpty()) { |
14816 | if (SS.isSet()) { |
14817 | // If this is either a declaration or a definition, check the |
14818 | // nested-name-specifier against the current context. |
14819 | if ((TUK == TUK_Definition || TUK == TUK_Declaration) && |
14820 | diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, |
14821 | isMemberSpecialization)) |
14822 | Invalid = true; |
14823 | |
14824 | New->setQualifierInfo(SS.getWithLocInContext(Context)); |
14825 | if (TemplateParameterLists.size() > 0) { |
14826 | New->setTemplateParameterListsInfo(Context, TemplateParameterLists); |
14827 | } |
14828 | } |
14829 | else |
14830 | Invalid = true; |
14831 | } |
14832 | |
14833 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { |
14834 | // Add alignment attributes if necessary; these attributes are checked when |
14835 | // the ASTContext lays out the structure. |
14836 | // |
14837 | // It is important for implementing the correct semantics that this |
14838 | // happen here (in ActOnTag). The #pragma pack stack is |
14839 | // maintained as a result of parser callbacks which can occur at |
14840 | // many points during the parsing of a struct declaration (because |
14841 | // the #pragma tokens are effectively skipped over during the |
14842 | // parsing of the struct). |
14843 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { |
14844 | AddAlignmentAttributesForRecord(RD); |
14845 | AddMsStructLayoutForRecord(RD); |
14846 | } |
14847 | } |
14848 | |
14849 | if (ModulePrivateLoc.isValid()) { |
14850 | if (isMemberSpecialization) |
14851 | Diag(New->getLocation(), diag::err_module_private_specialization) |
14852 | << 2 |
14853 | << FixItHint::CreateRemoval(ModulePrivateLoc); |
14854 | // __module_private__ does not apply to local classes. However, we only |
14855 | // diagnose this as an error when the declaration specifiers are |
14856 | // freestanding. Here, we just ignore the __module_private__. |
14857 | else if (!SearchDC->isFunctionOrMethod()) |
14858 | New->setModulePrivate(); |
14859 | } |
14860 | |
14861 | // If this is a specialization of a member class (of a class template), |
14862 | // check the specialization. |
14863 | if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) |
14864 | Invalid = true; |
14865 | |
14866 | // If we're declaring or defining a tag in function prototype scope in C, |
14867 | // note that this type can only be used within the function and add it to |
14868 | // the list of decls to inject into the function definition scope. |
14869 | if ((Name || Kind == TTK_Enum) && |
14870 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { |
14871 | if (getLangOpts().CPlusPlus) { |
14872 | // C++ [dcl.fct]p6: |
14873 | // Types shall not be defined in return or parameter types. |
14874 | if (TUK == TUK_Definition && !IsTypeSpecifier) { |
14875 | Diag(Loc, diag::err_type_defined_in_param_type) |
14876 | << Name; |
14877 | Invalid = true; |
14878 | } |
14879 | } else if (!PrevDecl) { |
14880 | Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); |
14881 | } |
14882 | } |
14883 | |
14884 | if (Invalid) |
14885 | New->setInvalidDecl(); |
14886 | |
14887 | // Set the lexical context. If the tag has a C++ scope specifier, the |
14888 | // lexical context will be different from the semantic context. |
14889 | New->setLexicalDeclContext(CurContext); |
14890 | |
14891 | // Mark this as a friend decl if applicable. |
14892 | // In Microsoft mode, a friend declaration also acts as a forward |
14893 | // declaration so we always pass true to setObjectOfFriendDecl to make |
14894 | // the tag name visible. |
14895 | if (TUK == TUK_Friend) |
14896 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); |
14897 | |
14898 | // Set the access specifier. |
14899 | if (!Invalid && SearchDC->isRecord()) |
14900 | SetMemberAccessSpecifier(New, PrevDecl, AS); |
14901 | |
14902 | if (PrevDecl) |
14903 | CheckRedeclarationModuleOwnership(New, PrevDecl); |
14904 | |
14905 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) |
14906 | New->startDefinition(); |
14907 | |
14908 | ProcessDeclAttributeList(S, New, Attrs); |
14909 | AddPragmaAttributes(S, New); |
14910 | |
14911 | // If this has an identifier, add it to the scope stack. |
14912 | if (TUK == TUK_Friend) { |
14913 | // We might be replacing an existing declaration in the lookup tables; |
14914 | // if so, borrow its access specifier. |
14915 | if (PrevDecl) |
14916 | New->setAccess(PrevDecl->getAccess()); |
14917 | |
14918 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); |
14919 | DC->makeDeclVisibleInContext(New); |
14920 | if (Name) // can be null along some error paths |
14921 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) |
14922 | PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); |
14923 | } else if (Name) { |
14924 | S = getNonFieldDeclScope(S); |
14925 | PushOnScopeChains(New, S, true); |
14926 | } else { |
14927 | CurContext->addDecl(New); |
14928 | } |
14929 | |
14930 | // If this is the C FILE type, notify the AST context. |
14931 | if (IdentifierInfo *II = New->getIdentifier()) |
14932 | if (!New->isInvalidDecl() && |
14933 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && |
14934 | II->isStr("FILE")) |
14935 | Context.setFILEDecl(New); |
14936 | |
14937 | if (PrevDecl) |
14938 | mergeDeclAttributes(New, PrevDecl); |
14939 | |
14940 | // If there's a #pragma GCC visibility in scope, set the visibility of this |
14941 | // record. |
14942 | AddPushedVisibilityAttribute(New); |
14943 | |
14944 | if (isMemberSpecialization && !New->isInvalidDecl()) |
14945 | CompleteMemberSpecialization(New, Previous); |
14946 | |
14947 | OwnedDecl = true; |
14948 | // In C++, don't return an invalid declaration. We can't recover well from |
14949 | // the cases where we make the type anonymous. |
14950 | if (Invalid && getLangOpts().CPlusPlus) { |
14951 | if (New->isBeingDefined()) |
14952 | if (auto RD = dyn_cast<RecordDecl>(New)) |
14953 | RD->completeDefinition(); |
14954 | return nullptr; |
14955 | } else if (SkipBody && SkipBody->ShouldSkip) { |
14956 | return SkipBody->Previous; |
14957 | } else { |
14958 | return New; |
14959 | } |
14960 | } |
14961 | |
14962 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { |
14963 | AdjustDeclIfTemplate(TagD); |
14964 | TagDecl *Tag = cast<TagDecl>(TagD); |
14965 | |
14966 | // Enter the tag context. |
14967 | PushDeclContext(S, Tag); |
14968 | |
14969 | ActOnDocumentableDecl(TagD); |
14970 | |
14971 | // If there's a #pragma GCC visibility in scope, set the visibility of this |
14972 | // record. |
14973 | AddPushedVisibilityAttribute(Tag); |
14974 | } |
14975 | |
14976 | bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, |
14977 | SkipBodyInfo &SkipBody) { |
14978 | if (!hasStructuralCompatLayout(Prev, SkipBody.New)) |
14979 | return false; |
14980 | |
14981 | // Make the previous decl visible. |
14982 | makeMergedDefinitionVisible(SkipBody.Previous); |
14983 | return true; |
14984 | } |
14985 | |
14986 | Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { |
14987 | assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14988, __PRETTY_FUNCTION__)) |
14988 | "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14988, __PRETTY_FUNCTION__)); |
14989 | DeclContext *OCD = cast<DeclContext>(IDecl); |
14990 | assert(getContainingDC(OCD) == CurContext &&((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14991, __PRETTY_FUNCTION__)) |
14991 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 14991, __PRETTY_FUNCTION__)); |
14992 | CurContext = OCD; |
14993 | return IDecl; |
14994 | } |
14995 | |
14996 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, |
14997 | SourceLocation FinalLoc, |
14998 | bool IsFinalSpelledSealed, |
14999 | SourceLocation LBraceLoc) { |
15000 | AdjustDeclIfTemplate(TagD); |
15001 | CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); |
15002 | |
15003 | FieldCollector->StartClass(); |
15004 | |
15005 | if (!Record->getIdentifier()) |
15006 | return; |
15007 | |
15008 | if (FinalLoc.isValid()) |
15009 | Record->addAttr(new (Context) |
15010 | FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); |
15011 | |
15012 | // C++ [class]p2: |
15013 | // [...] The class-name is also inserted into the scope of the |
15014 | // class itself; this is known as the injected-class-name. For |
15015 | // purposes of access checking, the injected-class-name is treated |
15016 | // as if it were a public member name. |
15017 | CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( |
15018 | Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), |
15019 | Record->getLocation(), Record->getIdentifier(), |
15020 | /*PrevDecl=*/nullptr, |
15021 | /*DelayTypeCreation=*/true); |
15022 | Context.getTypeDeclType(InjectedClassName, Record); |
15023 | InjectedClassName->setImplicit(); |
15024 | InjectedClassName->setAccess(AS_public); |
15025 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) |
15026 | InjectedClassName->setDescribedClassTemplate(Template); |
15027 | PushOnScopeChains(InjectedClassName, S); |
15028 | assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15029, __PRETTY_FUNCTION__)) |
15029 | "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15029, __PRETTY_FUNCTION__)); |
15030 | } |
15031 | |
15032 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, |
15033 | SourceRange BraceRange) { |
15034 | AdjustDeclIfTemplate(TagD); |
15035 | TagDecl *Tag = cast<TagDecl>(TagD); |
15036 | Tag->setBraceRange(BraceRange); |
15037 | |
15038 | // Make sure we "complete" the definition even it is invalid. |
15039 | if (Tag->isBeingDefined()) { |
15040 | assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it" ) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15040, __PRETTY_FUNCTION__)); |
15041 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) |
15042 | RD->completeDefinition(); |
15043 | } |
15044 | |
15045 | if (isa<CXXRecordDecl>(Tag)) { |
15046 | FieldCollector->FinishClass(); |
15047 | } |
15048 | |
15049 | // Exit this scope of this tag's definition. |
15050 | PopDeclContext(); |
15051 | |
15052 | if (getCurLexicalContext()->isObjCContainer() && |
15053 | Tag->getDeclContext()->isFileContext()) |
15054 | Tag->setTopLevelDeclInObjCContainer(); |
15055 | |
15056 | // Notify the consumer that we've defined a tag. |
15057 | if (!Tag->isInvalidDecl()) |
15058 | Consumer.HandleTagDeclDefinition(Tag); |
15059 | } |
15060 | |
15061 | void Sema::ActOnObjCContainerFinishDefinition() { |
15062 | // Exit this scope of this interface definition. |
15063 | PopDeclContext(); |
15064 | } |
15065 | |
15066 | void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { |
15067 | assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts" ) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15067, __PRETTY_FUNCTION__)); |
15068 | OriginalLexicalContext = DC; |
15069 | ActOnObjCContainerFinishDefinition(); |
15070 | } |
15071 | |
15072 | void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { |
15073 | ActOnObjCContainerStartDefinition(cast<Decl>(DC)); |
15074 | OriginalLexicalContext = nullptr; |
15075 | } |
15076 | |
15077 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { |
15078 | AdjustDeclIfTemplate(TagD); |
15079 | TagDecl *Tag = cast<TagDecl>(TagD); |
15080 | Tag->setInvalidDecl(); |
15081 | |
15082 | // Make sure we "complete" the definition even it is invalid. |
15083 | if (Tag->isBeingDefined()) { |
15084 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) |
15085 | RD->completeDefinition(); |
15086 | } |
15087 | |
15088 | // We're undoing ActOnTagStartDefinition here, not |
15089 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with |
15090 | // the FieldCollector. |
15091 | |
15092 | PopDeclContext(); |
15093 | } |
15094 | |
15095 | // Note that FieldName may be null for anonymous bitfields. |
15096 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, |
15097 | IdentifierInfo *FieldName, |
15098 | QualType FieldTy, bool IsMsStruct, |
15099 | Expr *BitWidth, bool *ZeroWidth) { |
15100 | // Default to true; that shouldn't confuse checks for emptiness |
15101 | if (ZeroWidth) |
15102 | *ZeroWidth = true; |
15103 | |
15104 | // C99 6.7.2.1p4 - verify the field type. |
15105 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. |
15106 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { |
15107 | // Handle incomplete types with specific error. |
15108 | if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) |
15109 | return ExprError(); |
15110 | if (FieldName) |
15111 | return Diag(FieldLoc, diag::err_not_integral_type_bitfield) |
15112 | << FieldName << FieldTy << BitWidth->getSourceRange(); |
15113 | return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) |
15114 | << FieldTy << BitWidth->getSourceRange(); |
15115 | } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), |
15116 | UPPC_BitFieldWidth)) |
15117 | return ExprError(); |
15118 | |
15119 | // If the bit-width is type- or value-dependent, don't try to check |
15120 | // it now. |
15121 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) |
15122 | return BitWidth; |
15123 | |
15124 | llvm::APSInt Value; |
15125 | ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); |
15126 | if (ICE.isInvalid()) |
15127 | return ICE; |
15128 | BitWidth = ICE.get(); |
15129 | |
15130 | if (Value != 0 && ZeroWidth) |
15131 | *ZeroWidth = false; |
15132 | |
15133 | // Zero-width bitfield is ok for anonymous field. |
15134 | if (Value == 0 && FieldName) |
15135 | return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; |
15136 | |
15137 | if (Value.isSigned() && Value.isNegative()) { |
15138 | if (FieldName) |
15139 | return Diag(FieldLoc, diag::err_bitfield_has_negative_width) |
15140 | << FieldName << Value.toString(10); |
15141 | return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) |
15142 | << Value.toString(10); |
15143 | } |
15144 | |
15145 | if (!FieldTy->isDependentType()) { |
15146 | uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); |
15147 | uint64_t TypeWidth = Context.getIntWidth(FieldTy); |
15148 | bool BitfieldIsOverwide = Value.ugt(TypeWidth); |
15149 | |
15150 | // Over-wide bitfields are an error in C or when using the MSVC bitfield |
15151 | // ABI. |
15152 | bool CStdConstraintViolation = |
15153 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; |
15154 | bool MSBitfieldViolation = |
15155 | Value.ugt(TypeStorageSize) && |
15156 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); |
15157 | if (CStdConstraintViolation || MSBitfieldViolation) { |
15158 | unsigned DiagWidth = |
15159 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; |
15160 | if (FieldName) |
15161 | return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) |
15162 | << FieldName << (unsigned)Value.getZExtValue() |
15163 | << !CStdConstraintViolation << DiagWidth; |
15164 | |
15165 | return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) |
15166 | << (unsigned)Value.getZExtValue() << !CStdConstraintViolation |
15167 | << DiagWidth; |
15168 | } |
15169 | |
15170 | // Warn on types where the user might conceivably expect to get all |
15171 | // specified bits as value bits: that's all integral types other than |
15172 | // 'bool'. |
15173 | if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { |
15174 | if (FieldName) |
15175 | Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) |
15176 | << FieldName << (unsigned)Value.getZExtValue() |
15177 | << (unsigned)TypeWidth; |
15178 | else |
15179 | Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) |
15180 | << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; |
15181 | } |
15182 | } |
15183 | |
15184 | return BitWidth; |
15185 | } |
15186 | |
15187 | /// ActOnField - Each field of a C struct/union is passed into this in order |
15188 | /// to create a FieldDecl object for it. |
15189 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, |
15190 | Declarator &D, Expr *BitfieldWidth) { |
15191 | FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), |
15192 | DeclStart, D, static_cast<Expr*>(BitfieldWidth), |
15193 | /*InitStyle=*/ICIS_NoInit, AS_public); |
15194 | return Res; |
15195 | } |
15196 | |
15197 | /// HandleField - Analyze a field of a C struct or a C++ data member. |
15198 | /// |
15199 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, |
15200 | SourceLocation DeclStart, |
15201 | Declarator &D, Expr *BitWidth, |
15202 | InClassInitStyle InitStyle, |
15203 | AccessSpecifier AS) { |
15204 | if (D.isDecompositionDeclarator()) { |
15205 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); |
15206 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) |
15207 | << Decomp.getSourceRange(); |
15208 | return nullptr; |
15209 | } |
15210 | |
15211 | IdentifierInfo *II = D.getIdentifier(); |
15212 | SourceLocation Loc = DeclStart; |
15213 | if (II) Loc = D.getIdentifierLoc(); |
15214 | |
15215 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
15216 | QualType T = TInfo->getType(); |
15217 | if (getLangOpts().CPlusPlus) { |
15218 | CheckExtraCXXDefaultArguments(D); |
15219 | |
15220 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, |
15221 | UPPC_DataMemberType)) { |
15222 | D.setInvalidType(); |
15223 | T = Context.IntTy; |
15224 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); |
15225 | } |
15226 | } |
15227 | |
15228 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); |
15229 | |
15230 | if (D.getDeclSpec().isInlineSpecified()) |
15231 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) |
15232 | << getLangOpts().CPlusPlus17; |
15233 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) |
15234 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), |
15235 | diag::err_invalid_thread) |
15236 | << DeclSpec::getSpecifierName(TSCS); |
15237 | |
15238 | // Check to see if this name was declared as a member previously |
15239 | NamedDecl *PrevDecl = nullptr; |
15240 | LookupResult Previous(*this, II, Loc, LookupMemberName, |
15241 | ForVisibleRedeclaration); |
15242 | LookupName(Previous, S); |
15243 | switch (Previous.getResultKind()) { |
15244 | case LookupResult::Found: |
15245 | case LookupResult::FoundUnresolvedValue: |
15246 | PrevDecl = Previous.getAsSingle<NamedDecl>(); |
15247 | break; |
15248 | |
15249 | case LookupResult::FoundOverloaded: |
15250 | PrevDecl = Previous.getRepresentativeDecl(); |
15251 | break; |
15252 | |
15253 | case LookupResult::NotFound: |
15254 | case LookupResult::NotFoundInCurrentInstantiation: |
15255 | case LookupResult::Ambiguous: |
15256 | break; |
15257 | } |
15258 | Previous.suppressDiagnostics(); |
15259 | |
15260 | if (PrevDecl && PrevDecl->isTemplateParameter()) { |
15261 | // Maybe we will complain about the shadowed template parameter. |
15262 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); |
15263 | // Just pretend that we didn't see the previous declaration. |
15264 | PrevDecl = nullptr; |
15265 | } |
15266 | |
15267 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) |
15268 | PrevDecl = nullptr; |
15269 | |
15270 | bool Mutable |
15271 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); |
15272 | SourceLocation TSSL = D.getBeginLoc(); |
15273 | FieldDecl *NewFD |
15274 | = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, |
15275 | TSSL, AS, PrevDecl, &D); |
15276 | |
15277 | if (NewFD->isInvalidDecl()) |
15278 | Record->setInvalidDecl(); |
15279 | |
15280 | if (D.getDeclSpec().isModulePrivateSpecified()) |
15281 | NewFD->setModulePrivate(); |
15282 | |
15283 | if (NewFD->isInvalidDecl() && PrevDecl) { |
15284 | // Don't introduce NewFD into scope; there's already something |
15285 | // with the same name in the same scope. |
15286 | } else if (II) { |
15287 | PushOnScopeChains(NewFD, S); |
15288 | } else |
15289 | Record->addDecl(NewFD); |
15290 | |
15291 | return NewFD; |
15292 | } |
15293 | |
15294 | /// Build a new FieldDecl and check its well-formedness. |
15295 | /// |
15296 | /// This routine builds a new FieldDecl given the fields name, type, |
15297 | /// record, etc. \p PrevDecl should refer to any previous declaration |
15298 | /// with the same name and in the same scope as the field to be |
15299 | /// created. |
15300 | /// |
15301 | /// \returns a new FieldDecl. |
15302 | /// |
15303 | /// \todo The Declarator argument is a hack. It will be removed once |
15304 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, |
15305 | TypeSourceInfo *TInfo, |
15306 | RecordDecl *Record, SourceLocation Loc, |
15307 | bool Mutable, Expr *BitWidth, |
15308 | InClassInitStyle InitStyle, |
15309 | SourceLocation TSSL, |
15310 | AccessSpecifier AS, NamedDecl *PrevDecl, |
15311 | Declarator *D) { |
15312 | IdentifierInfo *II = Name.getAsIdentifierInfo(); |
15313 | bool InvalidDecl = false; |
15314 | if (D) InvalidDecl = D->isInvalidType(); |
15315 | |
15316 | // If we receive a broken type, recover by assuming 'int' and |
15317 | // marking this declaration as invalid. |
15318 | if (T.isNull()) { |
15319 | InvalidDecl = true; |
15320 | T = Context.IntTy; |
15321 | } |
15322 | |
15323 | QualType EltTy = Context.getBaseElementType(T); |
15324 | if (!EltTy->isDependentType()) { |
15325 | if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { |
15326 | // Fields of incomplete type force their record to be invalid. |
15327 | Record->setInvalidDecl(); |
15328 | InvalidDecl = true; |
15329 | } else { |
15330 | NamedDecl *Def; |
15331 | EltTy->isIncompleteType(&Def); |
15332 | if (Def && Def->isInvalidDecl()) { |
15333 | Record->setInvalidDecl(); |
15334 | InvalidDecl = true; |
15335 | } |
15336 | } |
15337 | } |
15338 | |
15339 | // TR 18037 does not allow fields to be declared with address space |
15340 | if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || |
15341 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { |
15342 | Diag(Loc, diag::err_field_with_address_space); |
15343 | Record->setInvalidDecl(); |
15344 | InvalidDecl = true; |
15345 | } |
15346 | |
15347 | if (LangOpts.OpenCL) { |
15348 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be |
15349 | // used as structure or union field: image, sampler, event or block types. |
15350 | if (T->isEventT() || T->isImageType() || T->isSamplerT() || |
15351 | T->isBlockPointerType()) { |
15352 | Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; |
15353 | Record->setInvalidDecl(); |
15354 | InvalidDecl = true; |
15355 | } |
15356 | // OpenCL v1.2 s6.9.c: bitfields are not supported. |
15357 | if (BitWidth) { |
15358 | Diag(Loc, diag::err_opencl_bitfields); |
15359 | InvalidDecl = true; |
15360 | } |
15361 | } |
15362 | |
15363 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). |
15364 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && |
15365 | T.hasQualifiers()) { |
15366 | InvalidDecl = true; |
15367 | Diag(Loc, diag::err_anon_bitfield_qualifiers); |
15368 | } |
15369 | |
15370 | // C99 6.7.2.1p8: A member of a structure or union may have any type other |
15371 | // than a variably modified type. |
15372 | if (!InvalidDecl && T->isVariablyModifiedType()) { |
15373 | bool SizeIsNegative; |
15374 | llvm::APSInt Oversized; |
15375 | |
15376 | TypeSourceInfo *FixedTInfo = |
15377 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, |
15378 | SizeIsNegative, |
15379 | Oversized); |
15380 | if (FixedTInfo) { |
15381 | Diag(Loc, diag::warn_illegal_constant_array_size); |
15382 | TInfo = FixedTInfo; |
15383 | T = FixedTInfo->getType(); |
15384 | } else { |
15385 | if (SizeIsNegative) |
15386 | Diag(Loc, diag::err_typecheck_negative_array_size); |
15387 | else if (Oversized.getBoolValue()) |
15388 | Diag(Loc, diag::err_array_too_large) |
15389 | << Oversized.toString(10); |
15390 | else |
15391 | Diag(Loc, diag::err_typecheck_field_variable_size); |
15392 | InvalidDecl = true; |
15393 | } |
15394 | } |
15395 | |
15396 | // Fields can not have abstract class types |
15397 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, |
15398 | diag::err_abstract_type_in_decl, |
15399 | AbstractFieldType)) |
15400 | InvalidDecl = true; |
15401 | |
15402 | bool ZeroWidth = false; |
15403 | if (InvalidDecl) |
15404 | BitWidth = nullptr; |
15405 | // If this is declared as a bit-field, check the bit-field. |
15406 | if (BitWidth) { |
15407 | BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, |
15408 | &ZeroWidth).get(); |
15409 | if (!BitWidth) { |
15410 | InvalidDecl = true; |
15411 | BitWidth = nullptr; |
15412 | ZeroWidth = false; |
15413 | } |
15414 | } |
15415 | |
15416 | // Check that 'mutable' is consistent with the type of the declaration. |
15417 | if (!InvalidDecl && Mutable) { |
15418 | unsigned DiagID = 0; |
15419 | if (T->isReferenceType()) |
15420 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference |
15421 | : diag::err_mutable_reference; |
15422 | else if (T.isConstQualified()) |
15423 | DiagID = diag::err_mutable_const; |
15424 | |
15425 | if (DiagID) { |
15426 | SourceLocation ErrLoc = Loc; |
15427 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) |
15428 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); |
15429 | Diag(ErrLoc, DiagID); |
15430 | if (DiagID != diag::ext_mutable_reference) { |
15431 | Mutable = false; |
15432 | InvalidDecl = true; |
15433 | } |
15434 | } |
15435 | } |
15436 | |
15437 | // C++11 [class.union]p8 (DR1460): |
15438 | // At most one variant member of a union may have a |
15439 | // brace-or-equal-initializer. |
15440 | if (InitStyle != ICIS_NoInit) |
15441 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); |
15442 | |
15443 | FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, |
15444 | BitWidth, Mutable, InitStyle); |
15445 | if (InvalidDecl) |
15446 | NewFD->setInvalidDecl(); |
15447 | |
15448 | if (PrevDecl && !isa<TagDecl>(PrevDecl)) { |
15449 | Diag(Loc, diag::err_duplicate_member) << II; |
15450 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); |
15451 | NewFD->setInvalidDecl(); |
15452 | } |
15453 | |
15454 | if (!InvalidDecl && getLangOpts().CPlusPlus) { |
15455 | if (Record->isUnion()) { |
15456 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { |
15457 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); |
15458 | if (RDecl->getDefinition()) { |
15459 | // C++ [class.union]p1: An object of a class with a non-trivial |
15460 | // constructor, a non-trivial copy constructor, a non-trivial |
15461 | // destructor, or a non-trivial copy assignment operator |
15462 | // cannot be a member of a union, nor can an array of such |
15463 | // objects. |
15464 | if (CheckNontrivialField(NewFD)) |
15465 | NewFD->setInvalidDecl(); |
15466 | } |
15467 | } |
15468 | |
15469 | // C++ [class.union]p1: If a union contains a member of reference type, |
15470 | // the program is ill-formed, except when compiling with MSVC extensions |
15471 | // enabled. |
15472 | if (EltTy->isReferenceType()) { |
15473 | Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? |
15474 | diag::ext_union_member_of_reference_type : |
15475 | diag::err_union_member_of_reference_type) |
15476 | << NewFD->getDeclName() << EltTy; |
15477 | if (!getLangOpts().MicrosoftExt) |
15478 | NewFD->setInvalidDecl(); |
15479 | } |
15480 | } |
15481 | } |
15482 | |
15483 | // FIXME: We need to pass in the attributes given an AST |
15484 | // representation, not a parser representation. |
15485 | if (D) { |
15486 | // FIXME: The current scope is almost... but not entirely... correct here. |
15487 | ProcessDeclAttributes(getCurScope(), NewFD, *D); |
15488 | |
15489 | if (NewFD->hasAttrs()) |
15490 | CheckAlignasUnderalignment(NewFD); |
15491 | } |
15492 | |
15493 | // In auto-retain/release, infer strong retension for fields of |
15494 | // retainable type. |
15495 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) |
15496 | NewFD->setInvalidDecl(); |
15497 | |
15498 | if (T.isObjCGCWeak()) |
15499 | Diag(Loc, diag::warn_attribute_weak_on_field); |
15500 | |
15501 | NewFD->setAccess(AS); |
15502 | return NewFD; |
15503 | } |
15504 | |
15505 | bool Sema::CheckNontrivialField(FieldDecl *FD) { |
15506 | assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15506, __PRETTY_FUNCTION__)); |
15507 | assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15507, __PRETTY_FUNCTION__)); |
15508 | |
15509 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) |
15510 | return false; |
15511 | |
15512 | QualType EltTy = Context.getBaseElementType(FD->getType()); |
15513 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { |
15514 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); |
15515 | if (RDecl->getDefinition()) { |
15516 | // We check for copy constructors before constructors |
15517 | // because otherwise we'll never get complaints about |
15518 | // copy constructors. |
15519 | |
15520 | CXXSpecialMember member = CXXInvalid; |
15521 | // We're required to check for any non-trivial constructors. Since the |
15522 | // implicit default constructor is suppressed if there are any |
15523 | // user-declared constructors, we just need to check that there is a |
15524 | // trivial default constructor and a trivial copy constructor. (We don't |
15525 | // worry about move constructors here, since this is a C++98 check.) |
15526 | if (RDecl->hasNonTrivialCopyConstructor()) |
15527 | member = CXXCopyConstructor; |
15528 | else if (!RDecl->hasTrivialDefaultConstructor()) |
15529 | member = CXXDefaultConstructor; |
15530 | else if (RDecl->hasNonTrivialCopyAssignment()) |
15531 | member = CXXCopyAssignment; |
15532 | else if (RDecl->hasNonTrivialDestructor()) |
15533 | member = CXXDestructor; |
15534 | |
15535 | if (member != CXXInvalid) { |
15536 | if (!getLangOpts().CPlusPlus11 && |
15537 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { |
15538 | // Objective-C++ ARC: it is an error to have a non-trivial field of |
15539 | // a union. However, system headers in Objective-C programs |
15540 | // occasionally have Objective-C lifetime objects within unions, |
15541 | // and rather than cause the program to fail, we make those |
15542 | // members unavailable. |
15543 | SourceLocation Loc = FD->getLocation(); |
15544 | if (getSourceManager().isInSystemHeader(Loc)) { |
15545 | if (!FD->hasAttr<UnavailableAttr>()) |
15546 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", |
15547 | UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); |
15548 | return false; |
15549 | } |
15550 | } |
15551 | |
15552 | Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? |
15553 | diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : |
15554 | diag::err_illegal_union_or_anon_struct_member) |
15555 | << FD->getParent()->isUnion() << FD->getDeclName() << member; |
15556 | DiagnoseNontrivial(RDecl, member); |
15557 | return !getLangOpts().CPlusPlus11; |
15558 | } |
15559 | } |
15560 | } |
15561 | |
15562 | return false; |
15563 | } |
15564 | |
15565 | /// TranslateIvarVisibility - Translate visibility from a token ID to an |
15566 | /// AST enum value. |
15567 | static ObjCIvarDecl::AccessControl |
15568 | TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { |
15569 | switch (ivarVisibility) { |
15570 | default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15570); |
15571 | case tok::objc_private: return ObjCIvarDecl::Private; |
15572 | case tok::objc_public: return ObjCIvarDecl::Public; |
15573 | case tok::objc_protected: return ObjCIvarDecl::Protected; |
15574 | case tok::objc_package: return ObjCIvarDecl::Package; |
15575 | } |
15576 | } |
15577 | |
15578 | /// ActOnIvar - Each ivar field of an objective-c class is passed into this |
15579 | /// in order to create an IvarDecl object for it. |
15580 | Decl *Sema::ActOnIvar(Scope *S, |
15581 | SourceLocation DeclStart, |
15582 | Declarator &D, Expr *BitfieldWidth, |
15583 | tok::ObjCKeywordKind Visibility) { |
15584 | |
15585 | IdentifierInfo *II = D.getIdentifier(); |
15586 | Expr *BitWidth = (Expr*)BitfieldWidth; |
15587 | SourceLocation Loc = DeclStart; |
15588 | if (II) Loc = D.getIdentifierLoc(); |
15589 | |
15590 | // FIXME: Unnamed fields can be handled in various different ways, for |
15591 | // example, unnamed unions inject all members into the struct namespace! |
15592 | |
15593 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); |
15594 | QualType T = TInfo->getType(); |
15595 | |
15596 | if (BitWidth) { |
15597 | // 6.7.2.1p3, 6.7.2.1p4 |
15598 | BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); |
15599 | if (!BitWidth) |
15600 | D.setInvalidType(); |
15601 | } else { |
15602 | // Not a bitfield. |
15603 | |
15604 | // validate II. |
15605 | |
15606 | } |
15607 | if (T->isReferenceType()) { |
15608 | Diag(Loc, diag::err_ivar_reference_type); |
15609 | D.setInvalidType(); |
15610 | } |
15611 | // C99 6.7.2.1p8: A member of a structure or union may have any type other |
15612 | // than a variably modified type. |
15613 | else if (T->isVariablyModifiedType()) { |
15614 | Diag(Loc, diag::err_typecheck_ivar_variable_size); |
15615 | D.setInvalidType(); |
15616 | } |
15617 | |
15618 | // Get the visibility (access control) for this ivar. |
15619 | ObjCIvarDecl::AccessControl ac = |
15620 | Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) |
15621 | : ObjCIvarDecl::None; |
15622 | // Must set ivar's DeclContext to its enclosing interface. |
15623 | ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); |
15624 | if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) |
15625 | return nullptr; |
15626 | ObjCContainerDecl *EnclosingContext; |
15627 | if (ObjCImplementationDecl *IMPDecl = |
15628 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { |
15629 | if (LangOpts.ObjCRuntime.isFragile()) { |
15630 | // Case of ivar declared in an implementation. Context is that of its class. |
15631 | EnclosingContext = IMPDecl->getClassInterface(); |
15632 | assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!" ) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15632, __PRETTY_FUNCTION__)); |
15633 | } |
15634 | else |
15635 | EnclosingContext = EnclosingDecl; |
15636 | } else { |
15637 | if (ObjCCategoryDecl *CDecl = |
15638 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { |
15639 | if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { |
15640 | Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); |
15641 | return nullptr; |
15642 | } |
15643 | } |
15644 | EnclosingContext = EnclosingDecl; |
15645 | } |
15646 | |
15647 | // Construct the decl. |
15648 | ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, |
15649 | DeclStart, Loc, II, T, |
15650 | TInfo, ac, (Expr *)BitfieldWidth); |
15651 | |
15652 | if (II) { |
15653 | NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, |
15654 | ForVisibleRedeclaration); |
15655 | if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) |
15656 | && !isa<TagDecl>(PrevDecl)) { |
15657 | Diag(Loc, diag::err_duplicate_member) << II; |
15658 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); |
15659 | NewID->setInvalidDecl(); |
15660 | } |
15661 | } |
15662 | |
15663 | // Process attributes attached to the ivar. |
15664 | ProcessDeclAttributes(S, NewID, D); |
15665 | |
15666 | if (D.isInvalidType()) |
15667 | NewID->setInvalidDecl(); |
15668 | |
15669 | // In ARC, infer 'retaining' for ivars of retainable type. |
15670 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) |
15671 | NewID->setInvalidDecl(); |
15672 | |
15673 | if (D.getDeclSpec().isModulePrivateSpecified()) |
15674 | NewID->setModulePrivate(); |
15675 | |
15676 | if (II) { |
15677 | // FIXME: When interfaces are DeclContexts, we'll need to add |
15678 | // these to the interface. |
15679 | S->AddDecl(NewID); |
15680 | IdResolver.AddDecl(NewID); |
15681 | } |
15682 | |
15683 | if (LangOpts.ObjCRuntime.isNonFragile() && |
15684 | !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) |
15685 | Diag(Loc, diag::warn_ivars_in_interface); |
15686 | |
15687 | return NewID; |
15688 | } |
15689 | |
15690 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for |
15691 | /// class and class extensions. For every class \@interface and class |
15692 | /// extension \@interface, if the last ivar is a bitfield of any type, |
15693 | /// then add an implicit `char :0` ivar to the end of that interface. |
15694 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, |
15695 | SmallVectorImpl<Decl *> &AllIvarDecls) { |
15696 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) |
15697 | return; |
15698 | |
15699 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; |
15700 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); |
15701 | |
15702 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) |
15703 | return; |
15704 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); |
15705 | if (!ID) { |
15706 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { |
15707 | if (!CD->IsClassExtension()) |
15708 | return; |
15709 | } |
15710 | // No need to add this to end of @implementation. |
15711 | else |
15712 | return; |
15713 | } |
15714 | // All conditions are met. Add a new bitfield to the tail end of ivars. |
15715 | llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); |
15716 | Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); |
15717 | |
15718 | Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), |
15719 | DeclLoc, DeclLoc, nullptr, |
15720 | Context.CharTy, |
15721 | Context.getTrivialTypeSourceInfo(Context.CharTy, |
15722 | DeclLoc), |
15723 | ObjCIvarDecl::Private, BW, |
15724 | true); |
15725 | AllIvarDecls.push_back(Ivar); |
15726 | } |
15727 | |
15728 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, |
15729 | ArrayRef<Decl *> Fields, SourceLocation LBrac, |
15730 | SourceLocation RBrac, |
15731 | const ParsedAttributesView &Attrs) { |
15732 | assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl" ) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 15732, __PRETTY_FUNCTION__)); |
15733 | |
15734 | // If this is an Objective-C @implementation or category and we have |
15735 | // new fields here we should reset the layout of the interface since |
15736 | // it will now change. |
15737 | if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { |
15738 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); |
15739 | switch (DC->getKind()) { |
15740 | default: break; |
15741 | case Decl::ObjCCategory: |
15742 | Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); |
15743 | break; |
15744 | case Decl::ObjCImplementation: |
15745 | Context. |
15746 | ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); |
15747 | break; |
15748 | } |
15749 | } |
15750 | |
15751 | RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); |
15752 | CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); |
15753 | |
15754 | // Start counting up the number of named members; make sure to include |
15755 | // members of anonymous structs and unions in the total. |
15756 | unsigned NumNamedMembers = 0; |
15757 | if (Record) { |
15758 | for (const auto *I : Record->decls()) { |
15759 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) |
15760 | if (IFD->getDeclName()) |
15761 | ++NumNamedMembers; |
15762 | } |
15763 | } |
15764 | |
15765 | // Verify that all the fields are okay. |
15766 | SmallVector<FieldDecl*, 32> RecFields; |
15767 | |
15768 | bool ObjCFieldLifetimeErrReported = false; |
15769 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); |
15770 | i != end; ++i) { |
15771 | FieldDecl *FD = cast<FieldDecl>(*i); |
15772 | |
15773 | // Get the type for the field. |
15774 | const Type *FDTy = FD->getType().getTypePtr(); |
15775 | |
15776 | if (!FD->isAnonymousStructOrUnion()) { |
15777 | // Remember all fields written by the user. |
15778 | RecFields.push_back(FD); |
15779 | } |
15780 | |
15781 | // If the field is already invalid for some reason, don't emit more |
15782 | // diagnostics about it. |
15783 | if (FD->isInvalidDecl()) { |
15784 | EnclosingDecl->setInvalidDecl(); |
15785 | continue; |
15786 | } |
15787 | |
15788 | // C99 6.7.2.1p2: |
15789 | // A structure or union shall not contain a member with |
15790 | // incomplete or function type (hence, a structure shall not |
15791 | // contain an instance of itself, but may contain a pointer to |
15792 | // an instance of itself), except that the last member of a |
15793 | // structure with more than one named member may have incomplete |
15794 | // array type; such a structure (and any union containing, |
15795 | // possibly recursively, a member that is such a structure) |
15796 | // shall not be a member of a structure or an element of an |
15797 | // array. |
15798 | bool IsLastField = (i + 1 == Fields.end()); |
15799 | if (FDTy->isFunctionType()) { |
15800 | // Field declared as a function. |
15801 | Diag(FD->getLocation(), diag::err_field_declared_as_function) |
15802 | << FD->getDeclName(); |
15803 | FD->setInvalidDecl(); |
15804 | EnclosingDecl->setInvalidDecl(); |
15805 | continue; |
15806 | } else if (FDTy->isIncompleteArrayType() && |
15807 | (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { |
15808 | if (Record) { |
15809 | // Flexible array member. |
15810 | // Microsoft and g++ is more permissive regarding flexible array. |
15811 | // It will accept flexible array in union and also |
15812 | // as the sole element of a struct/class. |
15813 | unsigned DiagID = 0; |
15814 | if (!Record->isUnion() && !IsLastField) { |
15815 | Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) |
15816 | << FD->getDeclName() << FD->getType() << Record->getTagKind(); |
15817 | Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); |
15818 | FD->setInvalidDecl(); |
15819 | EnclosingDecl->setInvalidDecl(); |
15820 | continue; |
15821 | } else if (Record->isUnion()) |
15822 | DiagID = getLangOpts().MicrosoftExt |
15823 | ? diag::ext_flexible_array_union_ms |
15824 | : getLangOpts().CPlusPlus |
15825 | ? diag::ext_flexible_array_union_gnu |
15826 | : diag::err_flexible_array_union; |
15827 | else if (NumNamedMembers < 1) |
15828 | DiagID = getLangOpts().MicrosoftExt |
15829 | ? diag::ext_flexible_array_empty_aggregate_ms |
15830 | : getLangOpts().CPlusPlus |
15831 | ? diag::ext_flexible_array_empty_aggregate_gnu |
15832 | : diag::err_flexible_array_empty_aggregate; |
15833 | |
15834 | if (DiagID) |
15835 | Diag(FD->getLocation(), DiagID) << FD->getDeclName() |
15836 | << Record->getTagKind(); |
15837 | // While the layout of types that contain virtual bases is not specified |
15838 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place |
15839 | // virtual bases after the derived members. This would make a flexible |
15840 | // array member declared at the end of an object not adjacent to the end |
15841 | // of the type. |
15842 | if (CXXRecord && CXXRecord->getNumVBases() != 0) |
15843 | Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) |
15844 | << FD->getDeclName() << Record->getTagKind(); |
15845 | if (!getLangOpts().C99) |
15846 | Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) |
15847 | << FD->getDeclName() << Record->getTagKind(); |
15848 | |
15849 | // If the element type has a non-trivial destructor, we would not |
15850 | // implicitly destroy the elements, so disallow it for now. |
15851 | // |
15852 | // FIXME: GCC allows this. We should probably either implicitly delete |
15853 | // the destructor of the containing class, or just allow this. |
15854 | QualType BaseElem = Context.getBaseElementType(FD->getType()); |
15855 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { |
15856 | Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) |
15857 | << FD->getDeclName() << FD->getType(); |
15858 | FD->setInvalidDecl(); |
15859 | EnclosingDecl->setInvalidDecl(); |
15860 | continue; |
15861 | } |
15862 | // Okay, we have a legal flexible array member at the end of the struct. |
15863 | Record->setHasFlexibleArrayMember(true); |
15864 | } else { |
15865 | // In ObjCContainerDecl ivars with incomplete array type are accepted, |
15866 | // unless they are followed by another ivar. That check is done |
15867 | // elsewhere, after synthesized ivars are known. |
15868 | } |
15869 | } else if (!FDTy->isDependentType() && |
15870 | RequireCompleteType(FD->getLocation(), FD->getType(), |
15871 | diag::err_field_incomplete)) { |
15872 | // Incomplete type |
15873 | FD->setInvalidDecl(); |
15874 | EnclosingDecl->setInvalidDecl(); |
15875 | continue; |
15876 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { |
15877 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { |
15878 | // A type which contains a flexible array member is considered to be a |
15879 | // flexible array member. |
15880 | Record->setHasFlexibleArrayMember(true); |
15881 | if (!Record->isUnion()) { |
15882 | // If this is a struct/class and this is not the last element, reject |
15883 | // it. Note that GCC supports variable sized arrays in the middle of |
15884 | // structures. |
15885 | if (!IsLastField) |
15886 | Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) |
15887 | << FD->getDeclName() << FD->getType(); |
15888 | else { |
15889 | // We support flexible arrays at the end of structs in |
15890 | // other structs as an extension. |
15891 | Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) |
15892 | << FD->getDeclName(); |
15893 | } |
15894 | } |
15895 | } |
15896 | if (isa<ObjCContainerDecl>(EnclosingDecl) && |
15897 | RequireNonAbstractType(FD->getLocation(), FD->getType(), |
15898 | diag::err_abstract_type_in_decl, |
15899 | AbstractIvarType)) { |
15900 | // Ivars can not have abstract class types |
15901 | FD->setInvalidDecl(); |
15902 | } |
15903 | if (Record && FDTTy->getDecl()->hasObjectMember()) |
15904 | Record->setHasObjectMember(true); |
15905 | if (Record && FDTTy->getDecl()->hasVolatileMember()) |
15906 | Record->setHasVolatileMember(true); |
15907 | } else if (FDTy->isObjCObjectType()) { |
15908 | /// A field cannot be an Objective-c object |
15909 | Diag(FD->getLocation(), diag::err_statically_allocated_object) |
15910 | << FixItHint::CreateInsertion(FD->getLocation(), "*"); |
15911 | QualType T = Context.getObjCObjectPointerType(FD->getType()); |
15912 | FD->setType(T); |
15913 | } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
15914 | Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { |
15915 | // It's an error in ARC or Weak if a field has lifetime. |
15916 | // We don't want to report this in a system header, though, |
15917 | // so we just make the field unavailable. |
15918 | // FIXME: that's really not sufficient; we need to make the type |
15919 | // itself invalid to, say, initialize or copy. |
15920 | QualType T = FD->getType(); |
15921 | if (T.hasNonTrivialObjCLifetime()) { |
15922 | SourceLocation loc = FD->getLocation(); |
15923 | if (getSourceManager().isInSystemHeader(loc)) { |
15924 | if (!FD->hasAttr<UnavailableAttr>()) { |
15925 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", |
15926 | UnavailableAttr::IR_ARCFieldWithOwnership, loc)); |
15927 | } |
15928 | } else { |
15929 | Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) |
15930 | << T->isBlockPointerType() << Record->getTagKind(); |
15931 | } |
15932 | ObjCFieldLifetimeErrReported = true; |
15933 | } |
15934 | } else if (getLangOpts().ObjC && |
15935 | getLangOpts().getGC() != LangOptions::NonGC && |
15936 | Record && !Record->hasObjectMember()) { |
15937 | if (FD->getType()->isObjCObjectPointerType() || |
15938 | FD->getType().isObjCGCStrong()) |
15939 | Record->setHasObjectMember(true); |
15940 | else if (Context.getAsArrayType(FD->getType())) { |
15941 | QualType BaseType = Context.getBaseElementType(FD->getType()); |
15942 | if (BaseType->isRecordType() && |
15943 | BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) |
15944 | Record->setHasObjectMember(true); |
15945 | else if (BaseType->isObjCObjectPointerType() || |
15946 | BaseType.isObjCGCStrong()) |
15947 | Record->setHasObjectMember(true); |
15948 | } |
15949 | } |
15950 | |
15951 | if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { |
15952 | QualType FT = FD->getType(); |
15953 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) |
15954 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); |
15955 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); |
15956 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) |
15957 | Record->setNonTrivialToPrimitiveCopy(true); |
15958 | if (FT.isDestructedType()) { |
15959 | Record->setNonTrivialToPrimitiveDestroy(true); |
15960 | Record->setParamDestroyedInCallee(true); |
15961 | } |
15962 | |
15963 | if (const auto *RT = FT->getAs<RecordType>()) { |
15964 | if (RT->getDecl()->getArgPassingRestrictions() == |
15965 | RecordDecl::APK_CanNeverPassInRegs) |
15966 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); |
15967 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) |
15968 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); |
15969 | } |
15970 | |
15971 | if (Record && FD->getType().isVolatileQualified()) |
15972 | Record->setHasVolatileMember(true); |
15973 | // Keep track of the number of named members. |
15974 | if (FD->getIdentifier()) |
15975 | ++NumNamedMembers; |
15976 | } |
15977 | |
15978 | // Okay, we successfully defined 'Record'. |
15979 | if (Record) { |
15980 | bool Completed = false; |
15981 | if (CXXRecord) { |
15982 | if (!CXXRecord->isInvalidDecl()) { |
15983 | // Set access bits correctly on the directly-declared conversions. |
15984 | for (CXXRecordDecl::conversion_iterator |
15985 | I = CXXRecord->conversion_begin(), |
15986 | E = CXXRecord->conversion_end(); I != E; ++I) |
15987 | I.setAccess((*I)->getAccess()); |
15988 | } |
15989 | |
15990 | if (!CXXRecord->isDependentType()) { |
15991 | // Add any implicitly-declared members to this class. |
15992 | AddImplicitlyDeclaredMembersToClass(CXXRecord); |
15993 | |
15994 | if (!CXXRecord->isInvalidDecl()) { |
15995 | // If we have virtual base classes, we may end up finding multiple |
15996 | // final overriders for a given virtual function. Check for this |
15997 | // problem now. |
15998 | if (CXXRecord->getNumVBases()) { |
15999 | CXXFinalOverriderMap FinalOverriders; |
16000 | CXXRecord->getFinalOverriders(FinalOverriders); |
16001 | |
16002 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), |
16003 | MEnd = FinalOverriders.end(); |
16004 | M != MEnd; ++M) { |
16005 | for (OverridingMethods::iterator SO = M->second.begin(), |
16006 | SOEnd = M->second.end(); |
16007 | SO != SOEnd; ++SO) { |
16008 | assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16009, __PRETTY_FUNCTION__)) |
16009 | "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16009, __PRETTY_FUNCTION__)); |
16010 | if (SO->second.size() == 1) |
16011 | continue; |
16012 | |
16013 | // C++ [class.virtual]p2: |
16014 | // In a derived class, if a virtual member function of a base |
16015 | // class subobject has more than one final overrider the |
16016 | // program is ill-formed. |
16017 | Diag(Record->getLocation(), diag::err_multiple_final_overriders) |
16018 | << (const NamedDecl *)M->first << Record; |
16019 | Diag(M->first->getLocation(), |
16020 | diag::note_overridden_virtual_function); |
16021 | for (OverridingMethods::overriding_iterator |
16022 | OM = SO->second.begin(), |
16023 | OMEnd = SO->second.end(); |
16024 | OM != OMEnd; ++OM) |
16025 | Diag(OM->Method->getLocation(), diag::note_final_overrider) |
16026 | << (const NamedDecl *)M->first << OM->Method->getParent(); |
16027 | |
16028 | Record->setInvalidDecl(); |
16029 | } |
16030 | } |
16031 | CXXRecord->completeDefinition(&FinalOverriders); |
16032 | Completed = true; |
16033 | } |
16034 | } |
16035 | } |
16036 | } |
16037 | |
16038 | if (!Completed) |
16039 | Record->completeDefinition(); |
16040 | |
16041 | // Handle attributes before checking the layout. |
16042 | ProcessDeclAttributeList(S, Record, Attrs); |
16043 | |
16044 | // We may have deferred checking for a deleted destructor. Check now. |
16045 | if (CXXRecord) { |
16046 | auto *Dtor = CXXRecord->getDestructor(); |
16047 | if (Dtor && Dtor->isImplicit() && |
16048 | ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { |
16049 | CXXRecord->setImplicitDestructorIsDeleted(); |
16050 | SetDeclDeleted(Dtor, CXXRecord->getLocation()); |
16051 | } |
16052 | } |
16053 | |
16054 | if (Record->hasAttrs()) { |
16055 | CheckAlignasUnderalignment(Record); |
16056 | |
16057 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) |
16058 | checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), |
16059 | IA->getRange(), IA->getBestCase(), |
16060 | IA->getSemanticSpelling()); |
16061 | } |
16062 | |
16063 | // Check if the structure/union declaration is a type that can have zero |
16064 | // size in C. For C this is a language extension, for C++ it may cause |
16065 | // compatibility problems. |
16066 | bool CheckForZeroSize; |
16067 | if (!getLangOpts().CPlusPlus) { |
16068 | CheckForZeroSize = true; |
16069 | } else { |
16070 | // For C++ filter out types that cannot be referenced in C code. |
16071 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); |
16072 | CheckForZeroSize = |
16073 | CXXRecord->getLexicalDeclContext()->isExternCContext() && |
16074 | !CXXRecord->isDependentType() && |
16075 | CXXRecord->isCLike(); |
16076 | } |
16077 | if (CheckForZeroSize) { |
16078 | bool ZeroSize = true; |
16079 | bool IsEmpty = true; |
16080 | unsigned NonBitFields = 0; |
16081 | for (RecordDecl::field_iterator I = Record->field_begin(), |
16082 | E = Record->field_end(); |
16083 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { |
16084 | IsEmpty = false; |
16085 | if (I->isUnnamedBitfield()) { |
16086 | if (!I->isZeroLengthBitField(Context)) |
16087 | ZeroSize = false; |
16088 | } else { |
16089 | ++NonBitFields; |
16090 | QualType FieldType = I->getType(); |
16091 | if (FieldType->isIncompleteType() || |
16092 | !Context.getTypeSizeInChars(FieldType).isZero()) |
16093 | ZeroSize = false; |
16094 | } |
16095 | } |
16096 | |
16097 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are |
16098 | // allowed in C++, but warn if its declaration is inside |
16099 | // extern "C" block. |
16100 | if (ZeroSize) { |
16101 | Diag(RecLoc, getLangOpts().CPlusPlus ? |
16102 | diag::warn_zero_size_struct_union_in_extern_c : |
16103 | diag::warn_zero_size_struct_union_compat) |
16104 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); |
16105 | } |
16106 | |
16107 | // Structs without named members are extension in C (C99 6.7.2.1p7), |
16108 | // but are accepted by GCC. |
16109 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { |
16110 | Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : |
16111 | diag::ext_no_named_members_in_struct_union) |
16112 | << Record->isUnion(); |
16113 | } |
16114 | } |
16115 | } else { |
16116 | ObjCIvarDecl **ClsFields = |
16117 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); |
16118 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { |
16119 | ID->setEndOfDefinitionLoc(RBrac); |
16120 | // Add ivar's to class's DeclContext. |
16121 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { |
16122 | ClsFields[i]->setLexicalDeclContext(ID); |
16123 | ID->addDecl(ClsFields[i]); |
16124 | } |
16125 | // Must enforce the rule that ivars in the base classes may not be |
16126 | // duplicates. |
16127 | if (ID->getSuperClass()) |
16128 | DiagnoseDuplicateIvars(ID, ID->getSuperClass()); |
16129 | } else if (ObjCImplementationDecl *IMPDecl = |
16130 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { |
16131 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16131, __PRETTY_FUNCTION__)); |
16132 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) |
16133 | // Ivar declared in @implementation never belongs to the implementation. |
16134 | // Only it is in implementation's lexical context. |
16135 | ClsFields[I]->setLexicalDeclContext(IMPDecl); |
16136 | CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); |
16137 | IMPDecl->setIvarLBraceLoc(LBrac); |
16138 | IMPDecl->setIvarRBraceLoc(RBrac); |
16139 | } else if (ObjCCategoryDecl *CDecl = |
16140 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { |
16141 | // case of ivars in class extension; all other cases have been |
16142 | // reported as errors elsewhere. |
16143 | // FIXME. Class extension does not have a LocEnd field. |
16144 | // CDecl->setLocEnd(RBrac); |
16145 | // Add ivar's to class extension's DeclContext. |
16146 | // Diagnose redeclaration of private ivars. |
16147 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); |
16148 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { |
16149 | if (IDecl) { |
16150 | if (const ObjCIvarDecl *ClsIvar = |
16151 | IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { |
16152 | Diag(ClsFields[i]->getLocation(), |
16153 | diag::err_duplicate_ivar_declaration); |
16154 | Diag(ClsIvar->getLocation(), diag::note_previous_definition); |
16155 | continue; |
16156 | } |
16157 | for (const auto *Ext : IDecl->known_extensions()) { |
16158 | if (const ObjCIvarDecl *ClsExtIvar |
16159 | = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { |
16160 | Diag(ClsFields[i]->getLocation(), |
16161 | diag::err_duplicate_ivar_declaration); |
16162 | Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); |
16163 | continue; |
16164 | } |
16165 | } |
16166 | } |
16167 | ClsFields[i]->setLexicalDeclContext(CDecl); |
16168 | CDecl->addDecl(ClsFields[i]); |
16169 | } |
16170 | CDecl->setIvarLBraceLoc(LBrac); |
16171 | CDecl->setIvarRBraceLoc(RBrac); |
16172 | } |
16173 | } |
16174 | } |
16175 | |
16176 | /// Determine whether the given integral value is representable within |
16177 | /// the given type T. |
16178 | static bool isRepresentableIntegerValue(ASTContext &Context, |
16179 | llvm::APSInt &Value, |
16180 | QualType T) { |
16181 | assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16182, __PRETTY_FUNCTION__)) |
16182 | "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16182, __PRETTY_FUNCTION__)); |
16183 | unsigned BitWidth = Context.getIntWidth(T); |
16184 | |
16185 | if (Value.isUnsigned() || Value.isNonNegative()) { |
16186 | if (T->isSignedIntegerOrEnumerationType()) |
16187 | --BitWidth; |
16188 | return Value.getActiveBits() <= BitWidth; |
16189 | } |
16190 | return Value.getMinSignedBits() <= BitWidth; |
16191 | } |
16192 | |
16193 | // Given an integral type, return the next larger integral type |
16194 | // (or a NULL type of no such type exists). |
16195 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { |
16196 | // FIXME: Int128/UInt128 support, which also needs to be introduced into |
16197 | // enum checking below. |
16198 | assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16199, __PRETTY_FUNCTION__)) |
16199 | T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16199, __PRETTY_FUNCTION__)); |
16200 | const unsigned NumTypes = 4; |
16201 | QualType SignedIntegralTypes[NumTypes] = { |
16202 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy |
16203 | }; |
16204 | QualType UnsignedIntegralTypes[NumTypes] = { |
16205 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, |
16206 | Context.UnsignedLongLongTy |
16207 | }; |
16208 | |
16209 | unsigned BitWidth = Context.getTypeSize(T); |
16210 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes |
16211 | : UnsignedIntegralTypes; |
16212 | for (unsigned I = 0; I != NumTypes; ++I) |
16213 | if (Context.getTypeSize(Types[I]) > BitWidth) |
16214 | return Types[I]; |
16215 | |
16216 | return QualType(); |
16217 | } |
16218 | |
16219 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, |
16220 | EnumConstantDecl *LastEnumConst, |
16221 | SourceLocation IdLoc, |
16222 | IdentifierInfo *Id, |
16223 | Expr *Val) { |
16224 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); |
16225 | llvm::APSInt EnumVal(IntWidth); |
16226 | QualType EltTy; |
16227 | |
16228 | if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) |
16229 | Val = nullptr; |
16230 | |
16231 | if (Val) |
16232 | Val = DefaultLvalueConversion(Val).get(); |
16233 | |
16234 | if (Val) { |
16235 | if (Enum->isDependentType() || Val->isTypeDependent()) |
16236 | EltTy = Context.DependentTy; |
16237 | else { |
16238 | if (getLangOpts().CPlusPlus11 && Enum->isFixed() && |
16239 | !getLangOpts().MSVCCompat) { |
16240 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the |
16241 | // constant-expression in the enumerator-definition shall be a converted |
16242 | // constant expression of the underlying type. |
16243 | EltTy = Enum->getIntegerType(); |
16244 | ExprResult Converted = |
16245 | CheckConvertedConstantExpression(Val, EltTy, EnumVal, |
16246 | CCEK_Enumerator); |
16247 | if (Converted.isInvalid()) |
16248 | Val = nullptr; |
16249 | else |
16250 | Val = Converted.get(); |
16251 | } else if (!Val->isValueDependent() && |
16252 | !(Val = VerifyIntegerConstantExpression(Val, |
16253 | &EnumVal).get())) { |
16254 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. |
16255 | } else { |
16256 | if (Enum->isComplete()) { |
16257 | EltTy = Enum->getIntegerType(); |
16258 | |
16259 | // In Obj-C and Microsoft mode, require the enumeration value to be |
16260 | // representable in the underlying type of the enumeration. In C++11, |
16261 | // we perform a non-narrowing conversion as part of converted constant |
16262 | // expression checking. |
16263 | if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { |
16264 | if (getLangOpts().MSVCCompat) { |
16265 | Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; |
16266 | Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); |
16267 | } else |
16268 | Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; |
16269 | } else |
16270 | Val = ImpCastExprToType(Val, EltTy, |
16271 | EltTy->isBooleanType() ? |
16272 | CK_IntegralToBoolean : CK_IntegralCast) |
16273 | .get(); |
16274 | } else if (getLangOpts().CPlusPlus) { |
16275 | // C++11 [dcl.enum]p5: |
16276 | // If the underlying type is not fixed, the type of each enumerator |
16277 | // is the type of its initializing value: |
16278 | // - If an initializer is specified for an enumerator, the |
16279 | // initializing value has the same type as the expression. |
16280 | EltTy = Val->getType(); |
16281 | } else { |
16282 | // C99 6.7.2.2p2: |
16283 | // The expression that defines the value of an enumeration constant |
16284 | // shall be an integer constant expression that has a value |
16285 | // representable as an int. |
16286 | |
16287 | // Complain if the value is not representable in an int. |
16288 | if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) |
16289 | Diag(IdLoc, diag::ext_enum_value_not_int) |
16290 | << EnumVal.toString(10) << Val->getSourceRange() |
16291 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); |
16292 | else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { |
16293 | // Force the type of the expression to 'int'. |
16294 | Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); |
16295 | } |
16296 | EltTy = Val->getType(); |
16297 | } |
16298 | } |
16299 | } |
16300 | } |
16301 | |
16302 | if (!Val) { |
16303 | if (Enum->isDependentType()) |
16304 | EltTy = Context.DependentTy; |
16305 | else if (!LastEnumConst) { |
16306 | // C++0x [dcl.enum]p5: |
16307 | // If the underlying type is not fixed, the type of each enumerator |
16308 | // is the type of its initializing value: |
16309 | // - If no initializer is specified for the first enumerator, the |
16310 | // initializing value has an unspecified integral type. |
16311 | // |
16312 | // GCC uses 'int' for its unspecified integral type, as does |
16313 | // C99 6.7.2.2p3. |
16314 | if (Enum->isFixed()) { |
16315 | EltTy = Enum->getIntegerType(); |
16316 | } |
16317 | else { |
16318 | EltTy = Context.IntTy; |
16319 | } |
16320 | } else { |
16321 | // Assign the last value + 1. |
16322 | EnumVal = LastEnumConst->getInitVal(); |
16323 | ++EnumVal; |
16324 | EltTy = LastEnumConst->getType(); |
16325 | |
16326 | // Check for overflow on increment. |
16327 | if (EnumVal < LastEnumConst->getInitVal()) { |
16328 | // C++0x [dcl.enum]p5: |
16329 | // If the underlying type is not fixed, the type of each enumerator |
16330 | // is the type of its initializing value: |
16331 | // |
16332 | // - Otherwise the type of the initializing value is the same as |
16333 | // the type of the initializing value of the preceding enumerator |
16334 | // unless the incremented value is not representable in that type, |
16335 | // in which case the type is an unspecified integral type |
16336 | // sufficient to contain the incremented value. If no such type |
16337 | // exists, the program is ill-formed. |
16338 | QualType T = getNextLargerIntegralType(Context, EltTy); |
16339 | if (T.isNull() || Enum->isFixed()) { |
16340 | // There is no integral type larger enough to represent this |
16341 | // value. Complain, then allow the value to wrap around. |
16342 | EnumVal = LastEnumConst->getInitVal(); |
16343 | EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); |
16344 | ++EnumVal; |
16345 | if (Enum->isFixed()) |
16346 | // When the underlying type is fixed, this is ill-formed. |
16347 | Diag(IdLoc, diag::err_enumerator_wrapped) |
16348 | << EnumVal.toString(10) |
16349 | << EltTy; |
16350 | else |
16351 | Diag(IdLoc, diag::ext_enumerator_increment_too_large) |
16352 | << EnumVal.toString(10); |
16353 | } else { |
16354 | EltTy = T; |
16355 | } |
16356 | |
16357 | // Retrieve the last enumerator's value, extent that type to the |
16358 | // type that is supposed to be large enough to represent the incremented |
16359 | // value, then increment. |
16360 | EnumVal = LastEnumConst->getInitVal(); |
16361 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); |
16362 | EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); |
16363 | ++EnumVal; |
16364 | |
16365 | // If we're not in C++, diagnose the overflow of enumerator values, |
16366 | // which in C99 means that the enumerator value is not representable in |
16367 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that |
16368 | // permits enumerator values that are representable in some larger |
16369 | // integral type. |
16370 | if (!getLangOpts().CPlusPlus && !T.isNull()) |
16371 | Diag(IdLoc, diag::warn_enum_value_overflow); |
16372 | } else if (!getLangOpts().CPlusPlus && |
16373 | !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { |
16374 | // Enforce C99 6.7.2.2p2 even when we compute the next value. |
16375 | Diag(IdLoc, diag::ext_enum_value_not_int) |
16376 | << EnumVal.toString(10) << 1; |
16377 | } |
16378 | } |
16379 | } |
16380 | |
16381 | if (!EltTy->isDependentType()) { |
16382 | // Make the enumerator value match the signedness and size of the |
16383 | // enumerator's type. |
16384 | EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); |
16385 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); |
16386 | } |
16387 | |
16388 | return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, |
16389 | Val, EnumVal); |
16390 | } |
16391 | |
16392 | Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, |
16393 | SourceLocation IILoc) { |
16394 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || |
16395 | !getLangOpts().CPlusPlus) |
16396 | return SkipBodyInfo(); |
16397 | |
16398 | // We have an anonymous enum definition. Look up the first enumerator to |
16399 | // determine if we should merge the definition with an existing one and |
16400 | // skip the body. |
16401 | NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, |
16402 | forRedeclarationInCurContext()); |
16403 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); |
16404 | if (!PrevECD) |
16405 | return SkipBodyInfo(); |
16406 | |
16407 | EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); |
16408 | NamedDecl *Hidden; |
16409 | if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { |
16410 | SkipBodyInfo Skip; |
16411 | Skip.Previous = Hidden; |
16412 | return Skip; |
16413 | } |
16414 | |
16415 | return SkipBodyInfo(); |
16416 | } |
16417 | |
16418 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, |
16419 | SourceLocation IdLoc, IdentifierInfo *Id, |
16420 | const ParsedAttributesView &Attrs, |
16421 | SourceLocation EqualLoc, Expr *Val) { |
16422 | EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); |
16423 | EnumConstantDecl *LastEnumConst = |
16424 | cast_or_null<EnumConstantDecl>(lastEnumConst); |
16425 | |
16426 | // The scope passed in may not be a decl scope. Zip up the scope tree until |
16427 | // we find one that is. |
16428 | S = getNonFieldDeclScope(S); |
16429 | |
16430 | // Verify that there isn't already something declared with this name in this |
16431 | // scope. |
16432 | LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); |
16433 | LookupName(R, S); |
16434 | NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); |
16435 | |
16436 | if (PrevDecl && PrevDecl->isTemplateParameter()) { |
16437 | // Maybe we will complain about the shadowed template parameter. |
16438 | DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); |
16439 | // Just pretend that we didn't see the previous declaration. |
16440 | PrevDecl = nullptr; |
16441 | } |
16442 | |
16443 | // C++ [class.mem]p15: |
16444 | // If T is the name of a class, then each of the following shall have a name |
16445 | // different from T: |
16446 | // - every enumerator of every member of class T that is an unscoped |
16447 | // enumerated type |
16448 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) |
16449 | DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), |
16450 | DeclarationNameInfo(Id, IdLoc)); |
16451 | |
16452 | EnumConstantDecl *New = |
16453 | CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); |
16454 | if (!New) |
16455 | return nullptr; |
16456 | |
16457 | if (PrevDecl) { |
16458 | if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { |
16459 | // Check for other kinds of shadowing not already handled. |
16460 | CheckShadow(New, PrevDecl, R); |
16461 | } |
16462 | |
16463 | // When in C++, we may get a TagDecl with the same name; in this case the |
16464 | // enum constant will 'hide' the tag. |
16465 | assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16466, __PRETTY_FUNCTION__)) |
16466 | "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16466, __PRETTY_FUNCTION__)); |
16467 | if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { |
16468 | if (isa<EnumConstantDecl>(PrevDecl)) |
16469 | Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; |
16470 | else |
16471 | Diag(IdLoc, diag::err_redefinition) << Id; |
16472 | notePreviousDefinition(PrevDecl, IdLoc); |
16473 | return nullptr; |
16474 | } |
16475 | } |
16476 | |
16477 | // Process attributes. |
16478 | ProcessDeclAttributeList(S, New, Attrs); |
16479 | AddPragmaAttributes(S, New); |
16480 | |
16481 | // Register this decl in the current scope stack. |
16482 | New->setAccess(TheEnumDecl->getAccess()); |
16483 | PushOnScopeChains(New, S); |
16484 | |
16485 | ActOnDocumentableDecl(New); |
16486 | |
16487 | return New; |
16488 | } |
16489 | |
16490 | // Returns true when the enum initial expression does not trigger the |
16491 | // duplicate enum warning. A few common cases are exempted as follows: |
16492 | // Element2 = Element1 |
16493 | // Element2 = Element1 + 1 |
16494 | // Element2 = Element1 - 1 |
16495 | // Where Element2 and Element1 are from the same enum. |
16496 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { |
16497 | Expr *InitExpr = ECD->getInitExpr(); |
16498 | if (!InitExpr) |
16499 | return true; |
16500 | InitExpr = InitExpr->IgnoreImpCasts(); |
16501 | |
16502 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { |
16503 | if (!BO->isAdditiveOp()) |
16504 | return true; |
16505 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); |
16506 | if (!IL) |
16507 | return true; |
16508 | if (IL->getValue() != 1) |
16509 | return true; |
16510 | |
16511 | InitExpr = BO->getLHS(); |
16512 | } |
16513 | |
16514 | // This checks if the elements are from the same enum. |
16515 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); |
16516 | if (!DRE) |
16517 | return true; |
16518 | |
16519 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); |
16520 | if (!EnumConstant) |
16521 | return true; |
16522 | |
16523 | if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != |
16524 | Enum) |
16525 | return true; |
16526 | |
16527 | return false; |
16528 | } |
16529 | |
16530 | // Emits a warning when an element is implicitly set a value that |
16531 | // a previous element has already been set to. |
16532 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, |
16533 | EnumDecl *Enum, QualType EnumType) { |
16534 | // Avoid anonymous enums |
16535 | if (!Enum->getIdentifier()) |
16536 | return; |
16537 | |
16538 | // Only check for small enums. |
16539 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) |
16540 | return; |
16541 | |
16542 | if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) |
16543 | return; |
16544 | |
16545 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; |
16546 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; |
16547 | |
16548 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; |
16549 | typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; |
16550 | |
16551 | // Use int64_t as a key to avoid needing special handling for DenseMap keys. |
16552 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { |
16553 | llvm::APSInt Val = D->getInitVal(); |
16554 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); |
16555 | }; |
16556 | |
16557 | DuplicatesVector DupVector; |
16558 | ValueToVectorMap EnumMap; |
16559 | |
16560 | // Populate the EnumMap with all values represented by enum constants without |
16561 | // an initializer. |
16562 | for (auto *Element : Elements) { |
16563 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); |
16564 | |
16565 | // Null EnumConstantDecl means a previous diagnostic has been emitted for |
16566 | // this constant. Skip this enum since it may be ill-formed. |
16567 | if (!ECD) { |
16568 | return; |
16569 | } |
16570 | |
16571 | // Constants with initalizers are handled in the next loop. |
16572 | if (ECD->getInitExpr()) |
16573 | continue; |
16574 | |
16575 | // Duplicate values are handled in the next loop. |
16576 | EnumMap.insert({EnumConstantToKey(ECD), ECD}); |
16577 | } |
16578 | |
16579 | if (EnumMap.size() == 0) |
16580 | return; |
16581 | |
16582 | // Create vectors for any values that has duplicates. |
16583 | for (auto *Element : Elements) { |
16584 | // The last loop returned if any constant was null. |
16585 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); |
16586 | if (!ValidDuplicateEnum(ECD, Enum)) |
16587 | continue; |
16588 | |
16589 | auto Iter = EnumMap.find(EnumConstantToKey(ECD)); |
16590 | if (Iter == EnumMap.end()) |
16591 | continue; |
16592 | |
16593 | DeclOrVector& Entry = Iter->second; |
16594 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { |
16595 | // Ensure constants are different. |
16596 | if (D == ECD) |
16597 | continue; |
16598 | |
16599 | // Create new vector and push values onto it. |
16600 | auto Vec = llvm::make_unique<ECDVector>(); |
16601 | Vec->push_back(D); |
16602 | Vec->push_back(ECD); |
16603 | |
16604 | // Update entry to point to the duplicates vector. |
16605 | Entry = Vec.get(); |
16606 | |
16607 | // Store the vector somewhere we can consult later for quick emission of |
16608 | // diagnostics. |
16609 | DupVector.emplace_back(std::move(Vec)); |
16610 | continue; |
16611 | } |
16612 | |
16613 | ECDVector *Vec = Entry.get<ECDVector*>(); |
16614 | // Make sure constants are not added more than once. |
16615 | if (*Vec->begin() == ECD) |
16616 | continue; |
16617 | |
16618 | Vec->push_back(ECD); |
16619 | } |
16620 | |
16621 | // Emit diagnostics. |
16622 | for (const auto &Vec : DupVector) { |
16623 | assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements." ) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16623, __PRETTY_FUNCTION__)); |
16624 | |
16625 | // Emit warning for one enum constant. |
16626 | auto *FirstECD = Vec->front(); |
16627 | S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) |
16628 | << FirstECD << FirstECD->getInitVal().toString(10) |
16629 | << FirstECD->getSourceRange(); |
16630 | |
16631 | // Emit one note for each of the remaining enum constants with |
16632 | // the same value. |
16633 | for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) |
16634 | S.Diag(ECD->getLocation(), diag::note_duplicate_element) |
16635 | << ECD << ECD->getInitVal().toString(10) |
16636 | << ECD->getSourceRange(); |
16637 | } |
16638 | } |
16639 | |
16640 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, |
16641 | bool AllowMask) const { |
16642 | assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum" ) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16642, __PRETTY_FUNCTION__)); |
16643 | assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition" ) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16643, __PRETTY_FUNCTION__)); |
16644 | |
16645 | auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); |
16646 | llvm::APInt &FlagBits = R.first->second; |
16647 | |
16648 | if (R.second) { |
16649 | for (auto *E : ED->enumerators()) { |
16650 | const auto &EVal = E->getInitVal(); |
16651 | // Only single-bit enumerators introduce new flag values. |
16652 | if (EVal.isPowerOf2()) |
16653 | FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; |
16654 | } |
16655 | } |
16656 | |
16657 | // A value is in a flag enum if either its bits are a subset of the enum's |
16658 | // flag bits (the first condition) or we are allowing masks and the same is |
16659 | // true of its complement (the second condition). When masks are allowed, we |
16660 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. |
16661 | // |
16662 | // While it's true that any value could be used as a mask, the assumption is |
16663 | // that a mask will have all of the insignificant bits set. Anything else is |
16664 | // likely a logic error. |
16665 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); |
16666 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); |
16667 | } |
16668 | |
16669 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, |
16670 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, |
16671 | const ParsedAttributesView &Attrs) { |
16672 | EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); |
16673 | QualType EnumType = Context.getTypeDeclType(Enum); |
16674 | |
16675 | ProcessDeclAttributeList(S, Enum, Attrs); |
16676 | |
16677 | if (Enum->isDependentType()) { |
16678 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { |
16679 | EnumConstantDecl *ECD = |
16680 | cast_or_null<EnumConstantDecl>(Elements[i]); |
16681 | if (!ECD) continue; |
16682 | |
16683 | ECD->setType(EnumType); |
16684 | } |
16685 | |
16686 | Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); |
16687 | return; |
16688 | } |
16689 | |
16690 | // TODO: If the result value doesn't fit in an int, it must be a long or long |
16691 | // long value. ISO C does not support this, but GCC does as an extension, |
16692 | // emit a warning. |
16693 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); |
16694 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); |
16695 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); |
16696 | |
16697 | // Verify that all the values are okay, compute the size of the values, and |
16698 | // reverse the list. |
16699 | unsigned NumNegativeBits = 0; |
16700 | unsigned NumPositiveBits = 0; |
16701 | |
16702 | // Keep track of whether all elements have type int. |
16703 | bool AllElementsInt = true; |
16704 | |
16705 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { |
16706 | EnumConstantDecl *ECD = |
16707 | cast_or_null<EnumConstantDecl>(Elements[i]); |
16708 | if (!ECD) continue; // Already issued a diagnostic. |
16709 | |
16710 | const llvm::APSInt &InitVal = ECD->getInitVal(); |
16711 | |
16712 | // Keep track of the size of positive and negative values. |
16713 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) |
16714 | NumPositiveBits = std::max(NumPositiveBits, |
16715 | (unsigned)InitVal.getActiveBits()); |
16716 | else |
16717 | NumNegativeBits = std::max(NumNegativeBits, |
16718 | (unsigned)InitVal.getMinSignedBits()); |
16719 | |
16720 | // Keep track of whether every enum element has type int (very common). |
16721 | if (AllElementsInt) |
16722 | AllElementsInt = ECD->getType() == Context.IntTy; |
16723 | } |
16724 | |
16725 | // Figure out the type that should be used for this enum. |
16726 | QualType BestType; |
16727 | unsigned BestWidth; |
16728 | |
16729 | // C++0x N3000 [conv.prom]p3: |
16730 | // An rvalue of an unscoped enumeration type whose underlying |
16731 | // type is not fixed can be converted to an rvalue of the first |
16732 | // of the following types that can represent all the values of |
16733 | // the enumeration: int, unsigned int, long int, unsigned long |
16734 | // int, long long int, or unsigned long long int. |
16735 | // C99 6.4.4.3p2: |
16736 | // An identifier declared as an enumeration constant has type int. |
16737 | // The C99 rule is modified by a gcc extension |
16738 | QualType BestPromotionType; |
16739 | |
16740 | bool Packed = Enum->hasAttr<PackedAttr>(); |
16741 | // -fshort-enums is the equivalent to specifying the packed attribute on all |
16742 | // enum definitions. |
16743 | if (LangOpts.ShortEnums) |
16744 | Packed = true; |
16745 | |
16746 | // If the enum already has a type because it is fixed or dictated by the |
16747 | // target, promote that type instead of analyzing the enumerators. |
16748 | if (Enum->isComplete()) { |
16749 | BestType = Enum->getIntegerType(); |
16750 | if (BestType->isPromotableIntegerType()) |
16751 | BestPromotionType = Context.getPromotedIntegerType(BestType); |
16752 | else |
16753 | BestPromotionType = BestType; |
16754 | |
16755 | BestWidth = Context.getIntWidth(BestType); |
16756 | } |
16757 | else if (NumNegativeBits) { |
16758 | // If there is a negative value, figure out the smallest integer type (of |
16759 | // int/long/longlong) that fits. |
16760 | // If it's packed, check also if it fits a char or a short. |
16761 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { |
16762 | BestType = Context.SignedCharTy; |
16763 | BestWidth = CharWidth; |
16764 | } else if (Packed && NumNegativeBits <= ShortWidth && |
16765 | NumPositiveBits < ShortWidth) { |
16766 | BestType = Context.ShortTy; |
16767 | BestWidth = ShortWidth; |
16768 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { |
16769 | BestType = Context.IntTy; |
16770 | BestWidth = IntWidth; |
16771 | } else { |
16772 | BestWidth = Context.getTargetInfo().getLongWidth(); |
16773 | |
16774 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { |
16775 | BestType = Context.LongTy; |
16776 | } else { |
16777 | BestWidth = Context.getTargetInfo().getLongLongWidth(); |
16778 | |
16779 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) |
16780 | Diag(Enum->getLocation(), diag::ext_enum_too_large); |
16781 | BestType = Context.LongLongTy; |
16782 | } |
16783 | } |
16784 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); |
16785 | } else { |
16786 | // If there is no negative value, figure out the smallest type that fits |
16787 | // all of the enumerator values. |
16788 | // If it's packed, check also if it fits a char or a short. |
16789 | if (Packed && NumPositiveBits <= CharWidth) { |
16790 | BestType = Context.UnsignedCharTy; |
16791 | BestPromotionType = Context.IntTy; |
16792 | BestWidth = CharWidth; |
16793 | } else if (Packed && NumPositiveBits <= ShortWidth) { |
16794 | BestType = Context.UnsignedShortTy; |
16795 | BestPromotionType = Context.IntTy; |
16796 | BestWidth = ShortWidth; |
16797 | } else if (NumPositiveBits <= IntWidth) { |
16798 | BestType = Context.UnsignedIntTy; |
16799 | BestWidth = IntWidth; |
16800 | BestPromotionType |
16801 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) |
16802 | ? Context.UnsignedIntTy : Context.IntTy; |
16803 | } else if (NumPositiveBits <= |
16804 | (BestWidth = Context.getTargetInfo().getLongWidth())) { |
16805 | BestType = Context.UnsignedLongTy; |
16806 | BestPromotionType |
16807 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) |
16808 | ? Context.UnsignedLongTy : Context.LongTy; |
16809 | } else { |
16810 | BestWidth = Context.getTargetInfo().getLongLongWidth(); |
16811 | assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16812, __PRETTY_FUNCTION__)) |
16812 | "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16812, __PRETTY_FUNCTION__)); |
16813 | BestType = Context.UnsignedLongLongTy; |
16814 | BestPromotionType |
16815 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) |
16816 | ? Context.UnsignedLongLongTy : Context.LongLongTy; |
16817 | } |
16818 | } |
16819 | |
16820 | // Loop over all of the enumerator constants, changing their types to match |
16821 | // the type of the enum if needed. |
16822 | for (auto *D : Elements) { |
16823 | auto *ECD = cast_or_null<EnumConstantDecl>(D); |
16824 | if (!ECD) continue; // Already issued a diagnostic. |
16825 | |
16826 | // Standard C says the enumerators have int type, but we allow, as an |
16827 | // extension, the enumerators to be larger than int size. If each |
16828 | // enumerator value fits in an int, type it as an int, otherwise type it the |
16829 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" |
16830 | // that X has type 'int', not 'unsigned'. |
16831 | |
16832 | // Determine whether the value fits into an int. |
16833 | llvm::APSInt InitVal = ECD->getInitVal(); |
16834 | |
16835 | // If it fits into an integer type, force it. Otherwise force it to match |
16836 | // the enum decl type. |
16837 | QualType NewTy; |
16838 | unsigned NewWidth; |
16839 | bool NewSign; |
16840 | if (!getLangOpts().CPlusPlus && |
16841 | !Enum->isFixed() && |
16842 | isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { |
16843 | NewTy = Context.IntTy; |
16844 | NewWidth = IntWidth; |
16845 | NewSign = true; |
16846 | } else if (ECD->getType() == BestType) { |
16847 | // Already the right type! |
16848 | if (getLangOpts().CPlusPlus) |
16849 | // C++ [dcl.enum]p4: Following the closing brace of an |
16850 | // enum-specifier, each enumerator has the type of its |
16851 | // enumeration. |
16852 | ECD->setType(EnumType); |
16853 | continue; |
16854 | } else { |
16855 | NewTy = BestType; |
16856 | NewWidth = BestWidth; |
16857 | NewSign = BestType->isSignedIntegerOrEnumerationType(); |
16858 | } |
16859 | |
16860 | // Adjust the APSInt value. |
16861 | InitVal = InitVal.extOrTrunc(NewWidth); |
16862 | InitVal.setIsSigned(NewSign); |
16863 | ECD->setInitVal(InitVal); |
16864 | |
16865 | // Adjust the Expr initializer and type. |
16866 | if (ECD->getInitExpr() && |
16867 | !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) |
16868 | ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, |
16869 | CK_IntegralCast, |
16870 | ECD->getInitExpr(), |
16871 | /*base paths*/ nullptr, |
16872 | VK_RValue)); |
16873 | if (getLangOpts().CPlusPlus) |
16874 | // C++ [dcl.enum]p4: Following the closing brace of an |
16875 | // enum-specifier, each enumerator has the type of its |
16876 | // enumeration. |
16877 | ECD->setType(EnumType); |
16878 | else |
16879 | ECD->setType(NewTy); |
16880 | } |
16881 | |
16882 | Enum->completeDefinition(BestType, BestPromotionType, |
16883 | NumPositiveBits, NumNegativeBits); |
16884 | |
16885 | CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); |
16886 | |
16887 | if (Enum->isClosedFlag()) { |
16888 | for (Decl *D : Elements) { |
16889 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); |
16890 | if (!ECD) continue; // Already issued a diagnostic. |
16891 | |
16892 | llvm::APSInt InitVal = ECD->getInitVal(); |
16893 | if (InitVal != 0 && !InitVal.isPowerOf2() && |
16894 | !IsValueInFlagEnum(Enum, InitVal, true)) |
16895 | Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) |
16896 | << ECD << Enum; |
16897 | } |
16898 | } |
16899 | |
16900 | // Now that the enum type is defined, ensure it's not been underaligned. |
16901 | if (Enum->hasAttrs()) |
16902 | CheckAlignasUnderalignment(Enum); |
16903 | } |
16904 | |
16905 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, |
16906 | SourceLocation StartLoc, |
16907 | SourceLocation EndLoc) { |
16908 | StringLiteral *AsmString = cast<StringLiteral>(expr); |
16909 | |
16910 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, |
16911 | AsmString, StartLoc, |
16912 | EndLoc); |
16913 | CurContext->addDecl(New); |
16914 | return New; |
16915 | } |
16916 | |
16917 | static void checkModuleImportContext(Sema &S, Module *M, |
16918 | SourceLocation ImportLoc, DeclContext *DC, |
16919 | bool FromInclude = false) { |
16920 | SourceLocation ExternCLoc; |
16921 | |
16922 | if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { |
16923 | switch (LSD->getLanguage()) { |
16924 | case LinkageSpecDecl::lang_c: |
16925 | if (ExternCLoc.isInvalid()) |
16926 | ExternCLoc = LSD->getBeginLoc(); |
16927 | break; |
16928 | case LinkageSpecDecl::lang_cxx: |
16929 | break; |
16930 | } |
16931 | DC = LSD->getParent(); |
16932 | } |
16933 | |
16934 | while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) |
16935 | DC = DC->getParent(); |
16936 | |
16937 | if (!isa<TranslationUnitDecl>(DC)) { |
16938 | S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) |
16939 | ? diag::ext_module_import_not_at_top_level_noop |
16940 | : diag::err_module_import_not_at_top_level_fatal) |
16941 | << M->getFullModuleName() << DC; |
16942 | S.Diag(cast<Decl>(DC)->getBeginLoc(), |
16943 | diag::note_module_import_not_at_top_level) |
16944 | << DC; |
16945 | } else if (!M->IsExternC && ExternCLoc.isValid()) { |
16946 | S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) |
16947 | << M->getFullModuleName(); |
16948 | S.Diag(ExternCLoc, diag::note_extern_c_begins_here); |
16949 | } |
16950 | } |
16951 | |
16952 | Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, |
16953 | SourceLocation ModuleLoc, |
16954 | ModuleDeclKind MDK, |
16955 | ModuleIdPath Path) { |
16956 | assert(getLangOpts().ModulesTS &&((getLangOpts().ModulesTS && "should only have module decl in modules TS" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().ModulesTS && \"should only have module decl in modules TS\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16957, __PRETTY_FUNCTION__)) |
16957 | "should only have module decl in modules TS")((getLangOpts().ModulesTS && "should only have module decl in modules TS" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().ModulesTS && \"should only have module decl in modules TS\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16957, __PRETTY_FUNCTION__)); |
16958 | |
16959 | // A module implementation unit requires that we are not compiling a module |
16960 | // of any kind. A module interface unit requires that we are not compiling a |
16961 | // module map. |
16962 | switch (getLangOpts().getCompilingModule()) { |
16963 | case LangOptions::CMK_None: |
16964 | // It's OK to compile a module interface as a normal translation unit. |
16965 | break; |
16966 | |
16967 | case LangOptions::CMK_ModuleInterface: |
16968 | if (MDK != ModuleDeclKind::Implementation) |
16969 | break; |
16970 | |
16971 | // We were asked to compile a module interface unit but this is a module |
16972 | // implementation unit. That indicates the 'export' is missing. |
16973 | Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) |
16974 | << FixItHint::CreateInsertion(ModuleLoc, "export "); |
16975 | MDK = ModuleDeclKind::Interface; |
16976 | break; |
16977 | |
16978 | case LangOptions::CMK_ModuleMap: |
16979 | Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); |
16980 | return nullptr; |
16981 | |
16982 | case LangOptions::CMK_HeaderModule: |
16983 | Diag(ModuleLoc, diag::err_module_decl_in_header_module); |
16984 | return nullptr; |
16985 | } |
16986 | |
16987 | assert(ModuleScopes.size() == 1 && "expected to be at global module scope")((ModuleScopes.size() == 1 && "expected to be at global module scope" ) ? static_cast<void> (0) : __assert_fail ("ModuleScopes.size() == 1 && \"expected to be at global module scope\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 16987, __PRETTY_FUNCTION__)); |
16988 | |
16989 | // FIXME: Most of this work should be done by the preprocessor rather than |
16990 | // here, in order to support macro import. |
16991 | |
16992 | // Only one module-declaration is permitted per source file. |
16993 | if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { |
16994 | Diag(ModuleLoc, diag::err_module_redeclaration); |
16995 | Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), |
16996 | diag::note_prev_module_declaration); |
16997 | return nullptr; |
16998 | } |
16999 | |
17000 | // Flatten the dots in a module name. Unlike Clang's hierarchical module map |
17001 | // modules, the dots here are just another character that can appear in a |
17002 | // module name. |
17003 | std::string ModuleName; |
17004 | for (auto &Piece : Path) { |
17005 | if (!ModuleName.empty()) |
17006 | ModuleName += "."; |
17007 | ModuleName += Piece.first->getName(); |
17008 | } |
17009 | |
17010 | // If a module name was explicitly specified on the command line, it must be |
17011 | // correct. |
17012 | if (!getLangOpts().CurrentModule.empty() && |
17013 | getLangOpts().CurrentModule != ModuleName) { |
17014 | Diag(Path.front().second, diag::err_current_module_name_mismatch) |
17015 | << SourceRange(Path.front().second, Path.back().second) |
17016 | << getLangOpts().CurrentModule; |
17017 | return nullptr; |
17018 | } |
17019 | const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; |
17020 | |
17021 | auto &Map = PP.getHeaderSearchInfo().getModuleMap(); |
17022 | Module *Mod; |
17023 | |
17024 | switch (MDK) { |
17025 | case ModuleDeclKind::Interface: { |
17026 | // We can't have parsed or imported a definition of this module or parsed a |
17027 | // module map defining it already. |
17028 | if (auto *M = Map.findModule(ModuleName)) { |
17029 | Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; |
17030 | if (M->DefinitionLoc.isValid()) |
17031 | Diag(M->DefinitionLoc, diag::note_prev_module_definition); |
17032 | else if (const auto *FE = M->getASTFile()) |
17033 | Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) |
17034 | << FE->getName(); |
17035 | Mod = M; |
17036 | break; |
17037 | } |
17038 | |
17039 | // Create a Module for the module that we're defining. |
17040 | Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, |
17041 | ModuleScopes.front().Module); |
17042 | assert(Mod && "module creation should not fail")((Mod && "module creation should not fail") ? static_cast <void> (0) : __assert_fail ("Mod && \"module creation should not fail\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 17042, __PRETTY_FUNCTION__)); |
17043 | break; |
17044 | } |
17045 | |
17046 | case ModuleDeclKind::Partition: |
17047 | // FIXME: Check we are in a submodule of the named module. |
17048 | return nullptr; |
17049 | |
17050 | case ModuleDeclKind::Implementation: |
17051 | std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( |
17052 | PP.getIdentifierInfo(ModuleName), Path[0].second); |
17053 | Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc}, |
17054 | Module::AllVisible, |
17055 | /*IsIncludeDirective=*/false); |
17056 | if (!Mod) { |
17057 | Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; |
17058 | // Create an empty module interface unit for error recovery. |
17059 | Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, |
17060 | ModuleScopes.front().Module); |
17061 | } |
17062 | break; |
17063 | } |
17064 | |
17065 | // Switch from the global module to the named module. |
17066 | ModuleScopes.back().Module = Mod; |
17067 | ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; |
17068 | VisibleModules.setVisible(Mod, ModuleLoc); |
17069 | |
17070 | // From now on, we have an owning module for all declarations we see. |
17071 | // However, those declarations are module-private unless explicitly |
17072 | // exported. |
17073 | auto *TU = Context.getTranslationUnitDecl(); |
17074 | TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); |
17075 | TU->setLocalOwningModule(Mod); |
17076 | |
17077 | // FIXME: Create a ModuleDecl. |
17078 | return nullptr; |
17079 | } |
17080 | |
17081 | DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, |
17082 | SourceLocation ImportLoc, |
17083 | ModuleIdPath Path) { |
17084 | // Flatten the module path for a Modules TS module name. |
17085 | std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc; |
17086 | if (getLangOpts().ModulesTS) { |
17087 | std::string ModuleName; |
17088 | for (auto &Piece : Path) { |
17089 | if (!ModuleName.empty()) |
17090 | ModuleName += "."; |
17091 | ModuleName += Piece.first->getName(); |
17092 | } |
17093 | ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second}; |
17094 | Path = ModuleIdPath(ModuleNameLoc); |
17095 | } |
17096 | |
17097 | Module *Mod = |
17098 | getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, |
17099 | /*IsIncludeDirective=*/false); |
17100 | if (!Mod) |
17101 | return true; |
17102 | |
17103 | VisibleModules.setVisible(Mod, ImportLoc); |
17104 | |
17105 | checkModuleImportContext(*this, Mod, ImportLoc, CurContext); |
17106 | |
17107 | // FIXME: we should support importing a submodule within a different submodule |
17108 | // of the same top-level module. Until we do, make it an error rather than |
17109 | // silently ignoring the import. |
17110 | // Import-from-implementation is valid in the Modules TS. FIXME: Should we |
17111 | // warn on a redundant import of the current module? |
17112 | if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && |
17113 | (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) |
17114 | Diag(ImportLoc, getLangOpts().isCompilingModule() |
17115 | ? diag::err_module_self_import |
17116 | : diag::err_module_import_in_implementation) |
17117 | << Mod->getFullModuleName() << getLangOpts().CurrentModule; |
17118 | |
17119 | SmallVector<SourceLocation, 2> IdentifierLocs; |
17120 | Module *ModCheck = Mod; |
17121 | for (unsigned I = 0, N = Path.size(); I != N; ++I) { |
17122 | // If we've run out of module parents, just drop the remaining identifiers. |
17123 | // We need the length to be consistent. |
17124 | if (!ModCheck) |
17125 | break; |
17126 | ModCheck = ModCheck->Parent; |
17127 | |
17128 | IdentifierLocs.push_back(Path[I].second); |
17129 | } |
17130 | |
17131 | ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, |
17132 | Mod, IdentifierLocs); |
17133 | if (!ModuleScopes.empty()) |
17134 | Context.addModuleInitializer(ModuleScopes.back().Module, Import); |
17135 | CurContext->addDecl(Import); |
17136 | |
17137 | // Re-export the module if needed. |
17138 | if (Import->isExported() && |
17139 | !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) |
17140 | getCurrentModule()->Exports.emplace_back(Mod, false); |
17141 | |
17142 | return Import; |
17143 | } |
17144 | |
17145 | void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { |
17146 | checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); |
17147 | BuildModuleInclude(DirectiveLoc, Mod); |
17148 | } |
17149 | |
17150 | void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { |
17151 | // Determine whether we're in the #include buffer for a module. The #includes |
17152 | // in that buffer do not qualify as module imports; they're just an |
17153 | // implementation detail of us building the module. |
17154 | // |
17155 | // FIXME: Should we even get ActOnModuleInclude calls for those? |
17156 | bool IsInModuleIncludes = |
17157 | TUKind == TU_Module && |
17158 | getSourceManager().isWrittenInMainFile(DirectiveLoc); |
17159 | |
17160 | bool ShouldAddImport = !IsInModuleIncludes; |
17161 | |
17162 | // If this module import was due to an inclusion directive, create an |
17163 | // implicit import declaration to capture it in the AST. |
17164 | if (ShouldAddImport) { |
17165 | TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); |
17166 | ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, |
17167 | DirectiveLoc, Mod, |
17168 | DirectiveLoc); |
17169 | if (!ModuleScopes.empty()) |
17170 | Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); |
17171 | TU->addDecl(ImportD); |
17172 | Consumer.HandleImplicitImportDecl(ImportD); |
17173 | } |
17174 | |
17175 | getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); |
17176 | VisibleModules.setVisible(Mod, DirectiveLoc); |
17177 | } |
17178 | |
17179 | void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { |
17180 | checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); |
17181 | |
17182 | ModuleScopes.push_back({}); |
17183 | ModuleScopes.back().Module = Mod; |
17184 | if (getLangOpts().ModulesLocalVisibility) |
17185 | ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); |
17186 | |
17187 | VisibleModules.setVisible(Mod, DirectiveLoc); |
17188 | |
17189 | // The enclosing context is now part of this module. |
17190 | // FIXME: Consider creating a child DeclContext to hold the entities |
17191 | // lexically within the module. |
17192 | if (getLangOpts().trackLocalOwningModule()) { |
17193 | for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { |
17194 | cast<Decl>(DC)->setModuleOwnershipKind( |
17195 | getLangOpts().ModulesLocalVisibility |
17196 | ? Decl::ModuleOwnershipKind::VisibleWhenImported |
17197 | : Decl::ModuleOwnershipKind::Visible); |
17198 | cast<Decl>(DC)->setLocalOwningModule(Mod); |
17199 | } |
17200 | } |
17201 | } |
17202 | |
17203 | void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { |
17204 | if (getLangOpts().ModulesLocalVisibility) { |
17205 | VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); |
17206 | // Leaving a module hides namespace names, so our visible namespace cache |
17207 | // is now out of date. |
17208 | VisibleNamespaceCache.clear(); |
17209 | } |
17210 | |
17211 | assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&((!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && "left the wrong module scope") ? static_cast <void> (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 17212, __PRETTY_FUNCTION__)) |
17212 | "left the wrong module scope")((!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && "left the wrong module scope") ? static_cast <void> (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 17212, __PRETTY_FUNCTION__)); |
17213 | ModuleScopes.pop_back(); |
17214 | |
17215 | // We got to the end of processing a local module. Create an |
17216 | // ImportDecl as we would for an imported module. |
17217 | FileID File = getSourceManager().getFileID(EomLoc); |
17218 | SourceLocation DirectiveLoc; |
17219 | if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { |
17220 | // We reached the end of a #included module header. Use the #include loc. |
17221 | assert(File != getSourceManager().getMainFileID() &&((File != getSourceManager().getMainFileID() && "end of submodule in main source file" ) ? static_cast<void> (0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 17222, __PRETTY_FUNCTION__)) |
17222 | "end of submodule in main source file")((File != getSourceManager().getMainFileID() && "end of submodule in main source file" ) ? static_cast<void> (0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\"" , "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaDecl.cpp" , 17222, __PRETTY_FUNCTION__)); |
17223 | DirectiveLoc = getSourceManager().getIncludeLoc(File); |
17224 | } else { |
17225 | // We reached an EOM pragma. Use the pragma location. |
17226 | DirectiveLoc = EomLoc; |
17227 | } |
17228 | BuildModuleInclude(DirectiveLoc, Mod); |
17229 | |
17230 | // Any further declarations are in whatever module we returned to. |
17231 | if (getLangOpts().trackLocalOwningModule()) { |
17232 | // The parser guarantees that this is the same context that we entered |
17233 | // the module within. |
17234 | for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { |
17235 | cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); |
17236 | if (!getCurrentModule()) |
17237 | cast<Decl>(DC)->setModuleOwnershipKind( |
17238 | Decl::ModuleOwnershipKind::Unowned); |
17239 | } |
17240 | } |
17241 | } |
17242 | |
17243 | void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, |
17244 | Module *Mod) { |
17245 | // Bail if we're not allowed to implicitly import a module here. |
17246 | if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || |
17247 | VisibleModules.isVisible(Mod)) |
17248 | return; |
17249 | |
17250 | // Create the implicit import declaration. |
17251 | TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); |
17252 | ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, |
17253 | Loc, Mod, Loc); |
17254 | TU->addDecl(ImportD); |
17255 | Consumer.HandleImplicitImportDecl(ImportD); |
17256 | |
17257 | // Make the module visible. |
17258 | getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); |
17259 | VisibleModules.setVisible(Mod, Loc); |
17260 | } |
17261 | |
17262 | /// We have parsed the start of an export declaration, including the '{' |
17263 | /// (if present). |
17264 | Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, |
17265 | SourceLocation LBraceLoc) { |
17266 | ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); |
17267 | |
17268 | // C++ Modules TS draft: |
17269 | // An export-declaration shall appear in the purview of a module other than |
17270 | // the global module. |
17271 | if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) |
17272 | Diag(ExportLoc, diag::err_export_not_in_module_interface); |
17273 | |
17274 | // An export-declaration [...] shall not contain more than one |
17275 | // export keyword. |
17276 | // |
17277 | // The intent here is that an export-declaration cannot appear within another |
17278 | // export-declaration. |
17279 | if (D->isExported()) |
17280 | Diag(ExportLoc, diag::err_export_within_export); |
17281 | |
17282 | CurContext->addDecl(D); |
17283 | PushDeclContext(S, D); |
17284 | D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); |
17285 | return D; |
17286 | } |
17287 | |
17288 | /// Complete the definition of an export declaration. |
17289 | Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { |
17290 | auto *ED = cast<ExportDecl>(D); |
17291 | if (RBraceLoc.isValid()) |
17292 | ED->setRBraceLoc(RBraceLoc); |
17293 | |
17294 | // FIXME: Diagnose export of internal-linkage declaration (including |
17295 | // anonymous namespace). |
17296 | |
17297 | PopDeclContext(); |
17298 | return D; |
17299 | } |
17300 | |
17301 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, |
17302 | IdentifierInfo* AliasName, |
17303 | SourceLocation PragmaLoc, |
17304 | SourceLocation NameLoc, |
17305 | SourceLocation AliasNameLoc) { |
17306 | NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, |
17307 | LookupOrdinaryName); |
17308 | AsmLabelAttr *Attr = |
17309 | AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); |
17310 | |
17311 | // If a declaration that: |
17312 | // 1) declares a function or a variable |
17313 | // 2) has external linkage |
17314 | // already exists, add a label attribute to it. |
17315 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { |
17316 | if (isDeclExternC(PrevDecl)) |
17317 | PrevDecl->addAttr(Attr); |
17318 | else |
17319 | Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) |
17320 | << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; |
17321 | // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. |
17322 | } else |
17323 | (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); |
17324 | } |
17325 | |
17326 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, |
17327 | SourceLocation PragmaLoc, |
17328 | SourceLocation NameLoc) { |
17329 | Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); |
17330 | |
17331 | if (PrevDecl) { |
17332 | PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); |
17333 | } else { |
17334 | (void)WeakUndeclaredIdentifiers.insert( |
17335 | std::pair<IdentifierInfo*,WeakInfo> |
17336 | (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); |
17337 | } |
17338 | } |
17339 | |
17340 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, |
17341 | IdentifierInfo* AliasName, |
17342 | SourceLocation PragmaLoc, |
17343 | SourceLocation NameLoc, |
17344 | SourceLocation AliasNameLoc) { |
17345 | Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, |
17346 | LookupOrdinaryName); |
17347 | WeakInfo W = WeakInfo(Name, NameLoc); |
17348 | |
17349 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { |
17350 | if (!PrevDecl->hasAttr<AliasAttr>()) |
17351 | if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) |
17352 | DeclApplyPragmaWeak(TUScope, ND, W); |
17353 | } else { |
17354 | (void)WeakUndeclaredIdentifiers.insert( |
17355 | std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); |
17356 | } |
17357 | } |
17358 | |
17359 | Decl *Sema::getObjCDeclContext() const { |
17360 | return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); |
17361 | } |