File: | build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaDecl.cpp |
Warning: | line 17360, column 7 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// | |||
2 | // | |||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | |||
4 | // See https://llvm.org/LICENSE.txt for license information. | |||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | |||
6 | // | |||
7 | //===----------------------------------------------------------------------===// | |||
8 | // | |||
9 | // This file implements semantic analysis for declarations. | |||
10 | // | |||
11 | //===----------------------------------------------------------------------===// | |||
12 | ||||
13 | #include "TypeLocBuilder.h" | |||
14 | #include "clang/AST/ASTConsumer.h" | |||
15 | #include "clang/AST/ASTContext.h" | |||
16 | #include "clang/AST/ASTLambda.h" | |||
17 | #include "clang/AST/CXXInheritance.h" | |||
18 | #include "clang/AST/CharUnits.h" | |||
19 | #include "clang/AST/CommentDiagnostic.h" | |||
20 | #include "clang/AST/DeclCXX.h" | |||
21 | #include "clang/AST/DeclObjC.h" | |||
22 | #include "clang/AST/DeclTemplate.h" | |||
23 | #include "clang/AST/EvaluatedExprVisitor.h" | |||
24 | #include "clang/AST/Expr.h" | |||
25 | #include "clang/AST/ExprCXX.h" | |||
26 | #include "clang/AST/NonTrivialTypeVisitor.h" | |||
27 | #include "clang/AST/Randstruct.h" | |||
28 | #include "clang/AST/StmtCXX.h" | |||
29 | #include "clang/Basic/Builtins.h" | |||
30 | #include "clang/Basic/PartialDiagnostic.h" | |||
31 | #include "clang/Basic/SourceManager.h" | |||
32 | #include "clang/Basic/TargetInfo.h" | |||
33 | #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex | |||
34 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. | |||
35 | #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex | |||
36 | #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() | |||
37 | #include "clang/Sema/CXXFieldCollector.h" | |||
38 | #include "clang/Sema/DeclSpec.h" | |||
39 | #include "clang/Sema/DelayedDiagnostic.h" | |||
40 | #include "clang/Sema/Initialization.h" | |||
41 | #include "clang/Sema/Lookup.h" | |||
42 | #include "clang/Sema/ParsedTemplate.h" | |||
43 | #include "clang/Sema/Scope.h" | |||
44 | #include "clang/Sema/ScopeInfo.h" | |||
45 | #include "clang/Sema/SemaInternal.h" | |||
46 | #include "clang/Sema/Template.h" | |||
47 | #include "llvm/ADT/SmallString.h" | |||
48 | #include "llvm/ADT/Triple.h" | |||
49 | #include <algorithm> | |||
50 | #include <cstring> | |||
51 | #include <functional> | |||
52 | #include <unordered_map> | |||
53 | ||||
54 | using namespace clang; | |||
55 | using namespace sema; | |||
56 | ||||
57 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { | |||
58 | if (OwnedType) { | |||
59 | Decl *Group[2] = { OwnedType, Ptr }; | |||
60 | return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); | |||
61 | } | |||
62 | ||||
63 | return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); | |||
64 | } | |||
65 | ||||
66 | namespace { | |||
67 | ||||
68 | class TypeNameValidatorCCC final : public CorrectionCandidateCallback { | |||
69 | public: | |||
70 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, | |||
71 | bool AllowTemplates = false, | |||
72 | bool AllowNonTemplates = true) | |||
73 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), | |||
74 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { | |||
75 | WantExpressionKeywords = false; | |||
76 | WantCXXNamedCasts = false; | |||
77 | WantRemainingKeywords = false; | |||
78 | } | |||
79 | ||||
80 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
81 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | |||
82 | if (!AllowInvalidDecl && ND->isInvalidDecl()) | |||
83 | return false; | |||
84 | ||||
85 | if (getAsTypeTemplateDecl(ND)) | |||
86 | return AllowTemplates; | |||
87 | ||||
88 | bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); | |||
89 | if (!IsType) | |||
90 | return false; | |||
91 | ||||
92 | if (AllowNonTemplates) | |||
93 | return true; | |||
94 | ||||
95 | // An injected-class-name of a class template (specialization) is valid | |||
96 | // as a template or as a non-template. | |||
97 | if (AllowTemplates) { | |||
98 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | |||
99 | if (!RD || !RD->isInjectedClassName()) | |||
100 | return false; | |||
101 | RD = cast<CXXRecordDecl>(RD->getDeclContext()); | |||
102 | return RD->getDescribedClassTemplate() || | |||
103 | isa<ClassTemplateSpecializationDecl>(RD); | |||
104 | } | |||
105 | ||||
106 | return false; | |||
107 | } | |||
108 | ||||
109 | return !WantClassName && candidate.isKeyword(); | |||
110 | } | |||
111 | ||||
112 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
113 | return std::make_unique<TypeNameValidatorCCC>(*this); | |||
114 | } | |||
115 | ||||
116 | private: | |||
117 | bool AllowInvalidDecl; | |||
118 | bool WantClassName; | |||
119 | bool AllowTemplates; | |||
120 | bool AllowNonTemplates; | |||
121 | }; | |||
122 | ||||
123 | } // end anonymous namespace | |||
124 | ||||
125 | /// Determine whether the token kind starts a simple-type-specifier. | |||
126 | bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { | |||
127 | switch (Kind) { | |||
128 | // FIXME: Take into account the current language when deciding whether a | |||
129 | // token kind is a valid type specifier | |||
130 | case tok::kw_short: | |||
131 | case tok::kw_long: | |||
132 | case tok::kw___int64: | |||
133 | case tok::kw___int128: | |||
134 | case tok::kw_signed: | |||
135 | case tok::kw_unsigned: | |||
136 | case tok::kw_void: | |||
137 | case tok::kw_char: | |||
138 | case tok::kw_int: | |||
139 | case tok::kw_half: | |||
140 | case tok::kw_float: | |||
141 | case tok::kw_double: | |||
142 | case tok::kw___bf16: | |||
143 | case tok::kw__Float16: | |||
144 | case tok::kw___float128: | |||
145 | case tok::kw___ibm128: | |||
146 | case tok::kw_wchar_t: | |||
147 | case tok::kw_bool: | |||
148 | case tok::kw___underlying_type: | |||
149 | case tok::kw___auto_type: | |||
150 | return true; | |||
151 | ||||
152 | case tok::annot_typename: | |||
153 | case tok::kw_char16_t: | |||
154 | case tok::kw_char32_t: | |||
155 | case tok::kw_typeof: | |||
156 | case tok::annot_decltype: | |||
157 | case tok::kw_decltype: | |||
158 | return getLangOpts().CPlusPlus; | |||
159 | ||||
160 | case tok::kw_char8_t: | |||
161 | return getLangOpts().Char8; | |||
162 | ||||
163 | default: | |||
164 | break; | |||
165 | } | |||
166 | ||||
167 | return false; | |||
168 | } | |||
169 | ||||
170 | namespace { | |||
171 | enum class UnqualifiedTypeNameLookupResult { | |||
172 | NotFound, | |||
173 | FoundNonType, | |||
174 | FoundType | |||
175 | }; | |||
176 | } // end anonymous namespace | |||
177 | ||||
178 | /// Tries to perform unqualified lookup of the type decls in bases for | |||
179 | /// dependent class. | |||
180 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a | |||
181 | /// type decl, \a FoundType if only type decls are found. | |||
182 | static UnqualifiedTypeNameLookupResult | |||
183 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, | |||
184 | SourceLocation NameLoc, | |||
185 | const CXXRecordDecl *RD) { | |||
186 | if (!RD->hasDefinition()) | |||
187 | return UnqualifiedTypeNameLookupResult::NotFound; | |||
188 | // Look for type decls in base classes. | |||
189 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | |||
190 | UnqualifiedTypeNameLookupResult::NotFound; | |||
191 | for (const auto &Base : RD->bases()) { | |||
192 | const CXXRecordDecl *BaseRD = nullptr; | |||
193 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) | |||
194 | BaseRD = BaseTT->getAsCXXRecordDecl(); | |||
195 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { | |||
196 | // Look for type decls in dependent base classes that have known primary | |||
197 | // templates. | |||
198 | if (!TST || !TST->isDependentType()) | |||
199 | continue; | |||
200 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); | |||
201 | if (!TD) | |||
202 | continue; | |||
203 | if (auto *BasePrimaryTemplate = | |||
204 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { | |||
205 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) | |||
206 | BaseRD = BasePrimaryTemplate; | |||
207 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { | |||
208 | if (const ClassTemplatePartialSpecializationDecl *PS = | |||
209 | CTD->findPartialSpecialization(Base.getType())) | |||
210 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) | |||
211 | BaseRD = PS; | |||
212 | } | |||
213 | } | |||
214 | } | |||
215 | if (BaseRD) { | |||
216 | for (NamedDecl *ND : BaseRD->lookup(&II)) { | |||
217 | if (!isa<TypeDecl>(ND)) | |||
218 | return UnqualifiedTypeNameLookupResult::FoundNonType; | |||
219 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | |||
220 | } | |||
221 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { | |||
222 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { | |||
223 | case UnqualifiedTypeNameLookupResult::FoundNonType: | |||
224 | return UnqualifiedTypeNameLookupResult::FoundNonType; | |||
225 | case UnqualifiedTypeNameLookupResult::FoundType: | |||
226 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | |||
227 | break; | |||
228 | case UnqualifiedTypeNameLookupResult::NotFound: | |||
229 | break; | |||
230 | } | |||
231 | } | |||
232 | } | |||
233 | } | |||
234 | ||||
235 | return FoundTypeDecl; | |||
236 | } | |||
237 | ||||
238 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, | |||
239 | const IdentifierInfo &II, | |||
240 | SourceLocation NameLoc) { | |||
241 | // Lookup in the parent class template context, if any. | |||
242 | const CXXRecordDecl *RD = nullptr; | |||
243 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | |||
244 | UnqualifiedTypeNameLookupResult::NotFound; | |||
245 | for (DeclContext *DC = S.CurContext; | |||
246 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; | |||
247 | DC = DC->getParent()) { | |||
248 | // Look for type decls in dependent base classes that have known primary | |||
249 | // templates. | |||
250 | RD = dyn_cast<CXXRecordDecl>(DC); | |||
251 | if (RD && RD->getDescribedClassTemplate()) | |||
252 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); | |||
253 | } | |||
254 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) | |||
255 | return nullptr; | |||
256 | ||||
257 | // We found some types in dependent base classes. Recover as if the user | |||
258 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the | |||
259 | // lookup during template instantiation. | |||
260 | S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II; | |||
261 | ||||
262 | ASTContext &Context = S.Context; | |||
263 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, | |||
264 | cast<Type>(Context.getRecordType(RD))); | |||
265 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); | |||
266 | ||||
267 | CXXScopeSpec SS; | |||
268 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
269 | ||||
270 | TypeLocBuilder Builder; | |||
271 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | |||
272 | DepTL.setNameLoc(NameLoc); | |||
273 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | |||
274 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
275 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
276 | } | |||
277 | ||||
278 | /// If the identifier refers to a type name within this scope, | |||
279 | /// return the declaration of that type. | |||
280 | /// | |||
281 | /// This routine performs ordinary name lookup of the identifier II | |||
282 | /// within the given scope, with optional C++ scope specifier SS, to | |||
283 | /// determine whether the name refers to a type. If so, returns an | |||
284 | /// opaque pointer (actually a QualType) corresponding to that | |||
285 | /// type. Otherwise, returns NULL. | |||
286 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | |||
287 | Scope *S, CXXScopeSpec *SS, | |||
288 | bool isClassName, bool HasTrailingDot, | |||
289 | ParsedType ObjectTypePtr, | |||
290 | bool IsCtorOrDtorName, | |||
291 | bool WantNontrivialTypeSourceInfo, | |||
292 | bool IsClassTemplateDeductionContext, | |||
293 | IdentifierInfo **CorrectedII) { | |||
294 | // FIXME: Consider allowing this outside C++1z mode as an extension. | |||
295 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && | |||
296 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && | |||
297 | !isClassName && !HasTrailingDot; | |||
298 | ||||
299 | // Determine where we will perform name lookup. | |||
300 | DeclContext *LookupCtx = nullptr; | |||
301 | if (ObjectTypePtr) { | |||
302 | QualType ObjectType = ObjectTypePtr.get(); | |||
303 | if (ObjectType->isRecordType()) | |||
304 | LookupCtx = computeDeclContext(ObjectType); | |||
305 | } else if (SS && SS->isNotEmpty()) { | |||
306 | LookupCtx = computeDeclContext(*SS, false); | |||
307 | ||||
308 | if (!LookupCtx) { | |||
309 | if (isDependentScopeSpecifier(*SS)) { | |||
310 | // C++ [temp.res]p3: | |||
311 | // A qualified-id that refers to a type and in which the | |||
312 | // nested-name-specifier depends on a template-parameter (14.6.2) | |||
313 | // shall be prefixed by the keyword typename to indicate that the | |||
314 | // qualified-id denotes a type, forming an | |||
315 | // elaborated-type-specifier (7.1.5.3). | |||
316 | // | |||
317 | // We therefore do not perform any name lookup if the result would | |||
318 | // refer to a member of an unknown specialization. | |||
319 | if (!isClassName && !IsCtorOrDtorName) | |||
320 | return nullptr; | |||
321 | ||||
322 | // We know from the grammar that this name refers to a type, | |||
323 | // so build a dependent node to describe the type. | |||
324 | if (WantNontrivialTypeSourceInfo) | |||
325 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); | |||
326 | ||||
327 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); | |||
328 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, | |||
329 | II, NameLoc); | |||
330 | return ParsedType::make(T); | |||
331 | } | |||
332 | ||||
333 | return nullptr; | |||
334 | } | |||
335 | ||||
336 | if (!LookupCtx->isDependentContext() && | |||
337 | RequireCompleteDeclContext(*SS, LookupCtx)) | |||
338 | return nullptr; | |||
339 | } | |||
340 | ||||
341 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of | |||
342 | // lookup for class-names. | |||
343 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : | |||
344 | LookupOrdinaryName; | |||
345 | LookupResult Result(*this, &II, NameLoc, Kind); | |||
346 | if (LookupCtx) { | |||
347 | // Perform "qualified" name lookup into the declaration context we | |||
348 | // computed, which is either the type of the base of a member access | |||
349 | // expression or the declaration context associated with a prior | |||
350 | // nested-name-specifier. | |||
351 | LookupQualifiedName(Result, LookupCtx); | |||
352 | ||||
353 | if (ObjectTypePtr && Result.empty()) { | |||
354 | // C++ [basic.lookup.classref]p3: | |||
355 | // If the unqualified-id is ~type-name, the type-name is looked up | |||
356 | // in the context of the entire postfix-expression. If the type T of | |||
357 | // the object expression is of a class type C, the type-name is also | |||
358 | // looked up in the scope of class C. At least one of the lookups shall | |||
359 | // find a name that refers to (possibly cv-qualified) T. | |||
360 | LookupName(Result, S); | |||
361 | } | |||
362 | } else { | |||
363 | // Perform unqualified name lookup. | |||
364 | LookupName(Result, S); | |||
365 | ||||
366 | // For unqualified lookup in a class template in MSVC mode, look into | |||
367 | // dependent base classes where the primary class template is known. | |||
368 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { | |||
369 | if (ParsedType TypeInBase = | |||
370 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) | |||
371 | return TypeInBase; | |||
372 | } | |||
373 | } | |||
374 | ||||
375 | NamedDecl *IIDecl = nullptr; | |||
376 | UsingShadowDecl *FoundUsingShadow = nullptr; | |||
377 | switch (Result.getResultKind()) { | |||
378 | case LookupResult::NotFound: | |||
379 | case LookupResult::NotFoundInCurrentInstantiation: | |||
380 | if (CorrectedII) { | |||
381 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, | |||
382 | AllowDeducedTemplate); | |||
383 | TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, | |||
384 | S, SS, CCC, CTK_ErrorRecovery); | |||
385 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); | |||
386 | TemplateTy Template; | |||
387 | bool MemberOfUnknownSpecialization; | |||
388 | UnqualifiedId TemplateName; | |||
389 | TemplateName.setIdentifier(NewII, NameLoc); | |||
390 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); | |||
391 | CXXScopeSpec NewSS, *NewSSPtr = SS; | |||
392 | if (SS && NNS) { | |||
393 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
394 | NewSSPtr = &NewSS; | |||
395 | } | |||
396 | if (Correction && (NNS || NewII != &II) && | |||
397 | // Ignore a correction to a template type as the to-be-corrected | |||
398 | // identifier is not a template (typo correction for template names | |||
399 | // is handled elsewhere). | |||
400 | !(getLangOpts().CPlusPlus && NewSSPtr && | |||
401 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, | |||
402 | Template, MemberOfUnknownSpecialization))) { | |||
403 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, | |||
404 | isClassName, HasTrailingDot, ObjectTypePtr, | |||
405 | IsCtorOrDtorName, | |||
406 | WantNontrivialTypeSourceInfo, | |||
407 | IsClassTemplateDeductionContext); | |||
408 | if (Ty) { | |||
409 | diagnoseTypo(Correction, | |||
410 | PDiag(diag::err_unknown_type_or_class_name_suggest) | |||
411 | << Result.getLookupName() << isClassName); | |||
412 | if (SS && NNS) | |||
413 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
414 | *CorrectedII = NewII; | |||
415 | return Ty; | |||
416 | } | |||
417 | } | |||
418 | } | |||
419 | // If typo correction failed or was not performed, fall through | |||
420 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
421 | case LookupResult::FoundOverloaded: | |||
422 | case LookupResult::FoundUnresolvedValue: | |||
423 | Result.suppressDiagnostics(); | |||
424 | return nullptr; | |||
425 | ||||
426 | case LookupResult::Ambiguous: | |||
427 | // Recover from type-hiding ambiguities by hiding the type. We'll | |||
428 | // do the lookup again when looking for an object, and we can | |||
429 | // diagnose the error then. If we don't do this, then the error | |||
430 | // about hiding the type will be immediately followed by an error | |||
431 | // that only makes sense if the identifier was treated like a type. | |||
432 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { | |||
433 | Result.suppressDiagnostics(); | |||
434 | return nullptr; | |||
435 | } | |||
436 | ||||
437 | // Look to see if we have a type anywhere in the list of results. | |||
438 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); | |||
439 | Res != ResEnd; ++Res) { | |||
440 | NamedDecl *RealRes = (*Res)->getUnderlyingDecl(); | |||
441 | if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>( | |||
442 | RealRes) || | |||
443 | (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) { | |||
444 | if (!IIDecl || | |||
445 | // Make the selection of the recovery decl deterministic. | |||
446 | RealRes->getLocation() < IIDecl->getLocation()) { | |||
447 | IIDecl = RealRes; | |||
448 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res); | |||
449 | } | |||
450 | } | |||
451 | } | |||
452 | ||||
453 | if (!IIDecl) { | |||
454 | // None of the entities we found is a type, so there is no way | |||
455 | // to even assume that the result is a type. In this case, don't | |||
456 | // complain about the ambiguity. The parser will either try to | |||
457 | // perform this lookup again (e.g., as an object name), which | |||
458 | // will produce the ambiguity, or will complain that it expected | |||
459 | // a type name. | |||
460 | Result.suppressDiagnostics(); | |||
461 | return nullptr; | |||
462 | } | |||
463 | ||||
464 | // We found a type within the ambiguous lookup; diagnose the | |||
465 | // ambiguity and then return that type. This might be the right | |||
466 | // answer, or it might not be, but it suppresses any attempt to | |||
467 | // perform the name lookup again. | |||
468 | break; | |||
469 | ||||
470 | case LookupResult::Found: | |||
471 | IIDecl = Result.getFoundDecl(); | |||
472 | FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin()); | |||
473 | break; | |||
474 | } | |||
475 | ||||
476 | assert(IIDecl && "Didn't find decl")(static_cast <bool> (IIDecl && "Didn't find decl" ) ? void (0) : __assert_fail ("IIDecl && \"Didn't find decl\"" , "clang/lib/Sema/SemaDecl.cpp", 476, __extension__ __PRETTY_FUNCTION__ )); | |||
477 | ||||
478 | QualType T; | |||
479 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { | |||
480 | // C++ [class.qual]p2: A lookup that would find the injected-class-name | |||
481 | // instead names the constructors of the class, except when naming a class. | |||
482 | // This is ill-formed when we're not actually forming a ctor or dtor name. | |||
483 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); | |||
484 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); | |||
485 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && | |||
486 | FoundRD->isInjectedClassName() && | |||
487 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) | |||
488 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) | |||
489 | << &II << /*Type*/1; | |||
490 | ||||
491 | DiagnoseUseOfDecl(IIDecl, NameLoc); | |||
492 | ||||
493 | T = Context.getTypeDeclType(TD); | |||
494 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); | |||
495 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { | |||
496 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); | |||
497 | if (!HasTrailingDot) | |||
498 | T = Context.getObjCInterfaceType(IDecl); | |||
499 | FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl. | |||
500 | } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) { | |||
501 | (void)DiagnoseUseOfDecl(UD, NameLoc); | |||
502 | // Recover with 'int' | |||
503 | T = Context.IntTy; | |||
504 | FoundUsingShadow = nullptr; | |||
505 | } else if (AllowDeducedTemplate) { | |||
506 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) { | |||
507 | assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD)(static_cast <bool> (!FoundUsingShadow || FoundUsingShadow ->getTargetDecl() == TD) ? void (0) : __assert_fail ("!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD" , "clang/lib/Sema/SemaDecl.cpp", 507, __extension__ __PRETTY_FUNCTION__ )); | |||
508 | TemplateName Template = | |||
509 | FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); | |||
510 | T = Context.getDeducedTemplateSpecializationType(Template, QualType(), | |||
511 | false); | |||
512 | // Don't wrap in a further UsingType. | |||
513 | FoundUsingShadow = nullptr; | |||
514 | } | |||
515 | } | |||
516 | ||||
517 | if (T.isNull()) { | |||
518 | // If it's not plausibly a type, suppress diagnostics. | |||
519 | Result.suppressDiagnostics(); | |||
520 | return nullptr; | |||
521 | } | |||
522 | ||||
523 | if (FoundUsingShadow) | |||
524 | T = Context.getUsingType(FoundUsingShadow, T); | |||
525 | ||||
526 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a | |||
527 | // constructor or destructor name (in such a case, the scope specifier | |||
528 | // will be attached to the enclosing Expr or Decl node). | |||
529 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && | |||
530 | !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) { | |||
531 | if (WantNontrivialTypeSourceInfo) { | |||
532 | // Construct a type with type-source information. | |||
533 | TypeLocBuilder Builder; | |||
534 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | |||
535 | ||||
536 | T = getElaboratedType(ETK_None, *SS, T); | |||
537 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | |||
538 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | |||
539 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); | |||
540 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
541 | } else { | |||
542 | T = getElaboratedType(ETK_None, *SS, T); | |||
543 | } | |||
544 | } | |||
545 | ||||
546 | return ParsedType::make(T); | |||
547 | } | |||
548 | ||||
549 | // Builds a fake NNS for the given decl context. | |||
550 | static NestedNameSpecifier * | |||
551 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { | |||
552 | for (;; DC = DC->getLookupParent()) { | |||
553 | DC = DC->getPrimaryContext(); | |||
554 | auto *ND = dyn_cast<NamespaceDecl>(DC); | |||
555 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) | |||
556 | return NestedNameSpecifier::Create(Context, nullptr, ND); | |||
557 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) | |||
558 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | |||
559 | RD->getTypeForDecl()); | |||
560 | else if (isa<TranslationUnitDecl>(DC)) | |||
561 | return NestedNameSpecifier::GlobalSpecifier(Context); | |||
562 | } | |||
563 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "clang/lib/Sema/SemaDecl.cpp", 563); | |||
564 | } | |||
565 | ||||
566 | /// Find the parent class with dependent bases of the innermost enclosing method | |||
567 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end | |||
568 | /// up allowing unqualified dependent type names at class-level, which MSVC | |||
569 | /// correctly rejects. | |||
570 | static const CXXRecordDecl * | |||
571 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { | |||
572 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { | |||
573 | DC = DC->getPrimaryContext(); | |||
574 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | |||
575 | if (MD->getParent()->hasAnyDependentBases()) | |||
576 | return MD->getParent(); | |||
577 | } | |||
578 | return nullptr; | |||
579 | } | |||
580 | ||||
581 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | |||
582 | SourceLocation NameLoc, | |||
583 | bool IsTemplateTypeArg) { | |||
584 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")(static_cast <bool> (getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode") ? void (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"" , "clang/lib/Sema/SemaDecl.cpp", 584, __extension__ __PRETTY_FUNCTION__ )); | |||
585 | ||||
586 | NestedNameSpecifier *NNS = nullptr; | |||
587 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { | |||
588 | // If we weren't able to parse a default template argument, delay lookup | |||
589 | // until instantiation time by making a non-dependent DependentTypeName. We | |||
590 | // pretend we saw a NestedNameSpecifier referring to the current scope, and | |||
591 | // lookup is retried. | |||
592 | // FIXME: This hurts our diagnostic quality, since we get errors like "no | |||
593 | // type named 'Foo' in 'current_namespace'" when the user didn't write any | |||
594 | // name specifiers. | |||
595 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); | |||
596 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; | |||
597 | } else if (const CXXRecordDecl *RD = | |||
598 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { | |||
599 | // Build a DependentNameType that will perform lookup into RD at | |||
600 | // instantiation time. | |||
601 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | |||
602 | RD->getTypeForDecl()); | |||
603 | ||||
604 | // Diagnose that this identifier was undeclared, and retry the lookup during | |||
605 | // template instantiation. | |||
606 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II | |||
607 | << RD; | |||
608 | } else { | |||
609 | // This is not a situation that we should recover from. | |||
610 | return ParsedType(); | |||
611 | } | |||
612 | ||||
613 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); | |||
614 | ||||
615 | // Build type location information. We synthesized the qualifier, so we have | |||
616 | // to build a fake NestedNameSpecifierLoc. | |||
617 | NestedNameSpecifierLocBuilder NNSLocBuilder; | |||
618 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | |||
619 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); | |||
620 | ||||
621 | TypeLocBuilder Builder; | |||
622 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | |||
623 | DepTL.setNameLoc(NameLoc); | |||
624 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | |||
625 | DepTL.setQualifierLoc(QualifierLoc); | |||
626 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
627 | } | |||
628 | ||||
629 | /// isTagName() - This method is called *for error recovery purposes only* | |||
630 | /// to determine if the specified name is a valid tag name ("struct foo"). If | |||
631 | /// so, this returns the TST for the tag corresponding to it (TST_enum, | |||
632 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose | |||
633 | /// cases in C where the user forgot to specify the tag. | |||
634 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { | |||
635 | // Do a tag name lookup in this scope. | |||
636 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); | |||
637 | LookupName(R, S, false); | |||
638 | R.suppressDiagnostics(); | |||
639 | if (R.getResultKind() == LookupResult::Found) | |||
640 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { | |||
641 | switch (TD->getTagKind()) { | |||
642 | case TTK_Struct: return DeclSpec::TST_struct; | |||
643 | case TTK_Interface: return DeclSpec::TST_interface; | |||
644 | case TTK_Union: return DeclSpec::TST_union; | |||
645 | case TTK_Class: return DeclSpec::TST_class; | |||
646 | case TTK_Enum: return DeclSpec::TST_enum; | |||
647 | } | |||
648 | } | |||
649 | ||||
650 | return DeclSpec::TST_unspecified; | |||
651 | } | |||
652 | ||||
653 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, | |||
654 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes | |||
655 | /// then downgrade the missing typename error to a warning. | |||
656 | /// This is needed for MSVC compatibility; Example: | |||
657 | /// @code | |||
658 | /// template<class T> class A { | |||
659 | /// public: | |||
660 | /// typedef int TYPE; | |||
661 | /// }; | |||
662 | /// template<class T> class B : public A<T> { | |||
663 | /// public: | |||
664 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. | |||
665 | /// }; | |||
666 | /// @endcode | |||
667 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { | |||
668 | if (CurContext->isRecord()) { | |||
669 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) | |||
670 | return true; | |||
671 | ||||
672 | const Type *Ty = SS->getScopeRep()->getAsType(); | |||
673 | ||||
674 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); | |||
675 | for (const auto &Base : RD->bases()) | |||
676 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) | |||
677 | return true; | |||
678 | return S->isFunctionPrototypeScope(); | |||
679 | } | |||
680 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); | |||
681 | } | |||
682 | ||||
683 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, | |||
684 | SourceLocation IILoc, | |||
685 | Scope *S, | |||
686 | CXXScopeSpec *SS, | |||
687 | ParsedType &SuggestedType, | |||
688 | bool IsTemplateName) { | |||
689 | // Don't report typename errors for editor placeholders. | |||
690 | if (II->isEditorPlaceholder()) | |||
691 | return; | |||
692 | // We don't have anything to suggest (yet). | |||
693 | SuggestedType = nullptr; | |||
694 | ||||
695 | // There may have been a typo in the name of the type. Look up typo | |||
696 | // results, in case we have something that we can suggest. | |||
697 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, | |||
698 | /*AllowTemplates=*/IsTemplateName, | |||
699 | /*AllowNonTemplates=*/!IsTemplateName); | |||
700 | if (TypoCorrection Corrected = | |||
701 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, | |||
702 | CCC, CTK_ErrorRecovery)) { | |||
703 | // FIXME: Support error recovery for the template-name case. | |||
704 | bool CanRecover = !IsTemplateName; | |||
705 | if (Corrected.isKeyword()) { | |||
706 | // We corrected to a keyword. | |||
707 | diagnoseTypo(Corrected, | |||
708 | PDiag(IsTemplateName ? diag::err_no_template_suggest | |||
709 | : diag::err_unknown_typename_suggest) | |||
710 | << II); | |||
711 | II = Corrected.getCorrectionAsIdentifierInfo(); | |||
712 | } else { | |||
713 | // We found a similarly-named type or interface; suggest that. | |||
714 | if (!SS || !SS->isSet()) { | |||
715 | diagnoseTypo(Corrected, | |||
716 | PDiag(IsTemplateName ? diag::err_no_template_suggest | |||
717 | : diag::err_unknown_typename_suggest) | |||
718 | << II, CanRecover); | |||
719 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { | |||
720 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
721 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
722 | II->getName().equals(CorrectedStr); | |||
723 | diagnoseTypo(Corrected, | |||
724 | PDiag(IsTemplateName | |||
725 | ? diag::err_no_member_template_suggest | |||
726 | : diag::err_unknown_nested_typename_suggest) | |||
727 | << II << DC << DroppedSpecifier << SS->getRange(), | |||
728 | CanRecover); | |||
729 | } else { | |||
730 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "clang/lib/Sema/SemaDecl.cpp", 730); | |||
731 | } | |||
732 | ||||
733 | if (!CanRecover) | |||
734 | return; | |||
735 | ||||
736 | CXXScopeSpec tmpSS; | |||
737 | if (Corrected.getCorrectionSpecifier()) | |||
738 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | |||
739 | SourceRange(IILoc)); | |||
740 | // FIXME: Support class template argument deduction here. | |||
741 | SuggestedType = | |||
742 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, | |||
743 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, | |||
744 | /*IsCtorOrDtorName=*/false, | |||
745 | /*WantNontrivialTypeSourceInfo=*/true); | |||
746 | } | |||
747 | return; | |||
748 | } | |||
749 | ||||
750 | if (getLangOpts().CPlusPlus && !IsTemplateName) { | |||
751 | // See if II is a class template that the user forgot to pass arguments to. | |||
752 | UnqualifiedId Name; | |||
753 | Name.setIdentifier(II, IILoc); | |||
754 | CXXScopeSpec EmptySS; | |||
755 | TemplateTy TemplateResult; | |||
756 | bool MemberOfUnknownSpecialization; | |||
757 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, | |||
758 | Name, nullptr, true, TemplateResult, | |||
759 | MemberOfUnknownSpecialization) == TNK_Type_template) { | |||
760 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); | |||
761 | return; | |||
762 | } | |||
763 | } | |||
764 | ||||
765 | // FIXME: Should we move the logic that tries to recover from a missing tag | |||
766 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? | |||
767 | ||||
768 | if (!SS || (!SS->isSet() && !SS->isInvalid())) | |||
769 | Diag(IILoc, IsTemplateName ? diag::err_no_template | |||
770 | : diag::err_unknown_typename) | |||
771 | << II; | |||
772 | else if (DeclContext *DC = computeDeclContext(*SS, false)) | |||
773 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template | |||
774 | : diag::err_typename_nested_not_found) | |||
775 | << II << DC << SS->getRange(); | |||
776 | else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { | |||
777 | SuggestedType = | |||
778 | ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); | |||
779 | } else if (isDependentScopeSpecifier(*SS)) { | |||
780 | unsigned DiagID = diag::err_typename_missing; | |||
781 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) | |||
782 | DiagID = diag::ext_typename_missing; | |||
783 | ||||
784 | Diag(SS->getRange().getBegin(), DiagID) | |||
785 | << SS->getScopeRep() << II->getName() | |||
786 | << SourceRange(SS->getRange().getBegin(), IILoc) | |||
787 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); | |||
788 | SuggestedType = ActOnTypenameType(S, SourceLocation(), | |||
789 | *SS, *II, IILoc).get(); | |||
790 | } else { | |||
791 | assert(SS && SS->isInvalid() &&(static_cast <bool> (SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed") ? void (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "clang/lib/Sema/SemaDecl.cpp", 792, __extension__ __PRETTY_FUNCTION__ )) | |||
792 | "Invalid scope specifier has already been diagnosed")(static_cast <bool> (SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed") ? void (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "clang/lib/Sema/SemaDecl.cpp", 792, __extension__ __PRETTY_FUNCTION__ )); | |||
793 | } | |||
794 | } | |||
795 | ||||
796 | /// Determine whether the given result set contains either a type name | |||
797 | /// or | |||
798 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { | |||
799 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && | |||
800 | NextToken.is(tok::less); | |||
801 | ||||
802 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { | |||
803 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) | |||
804 | return true; | |||
805 | ||||
806 | if (CheckTemplate && isa<TemplateDecl>(*I)) | |||
807 | return true; | |||
808 | } | |||
809 | ||||
810 | return false; | |||
811 | } | |||
812 | ||||
813 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, | |||
814 | Scope *S, CXXScopeSpec &SS, | |||
815 | IdentifierInfo *&Name, | |||
816 | SourceLocation NameLoc) { | |||
817 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); | |||
818 | SemaRef.LookupParsedName(R, S, &SS); | |||
819 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { | |||
820 | StringRef FixItTagName; | |||
821 | switch (Tag->getTagKind()) { | |||
822 | case TTK_Class: | |||
823 | FixItTagName = "class "; | |||
824 | break; | |||
825 | ||||
826 | case TTK_Enum: | |||
827 | FixItTagName = "enum "; | |||
828 | break; | |||
829 | ||||
830 | case TTK_Struct: | |||
831 | FixItTagName = "struct "; | |||
832 | break; | |||
833 | ||||
834 | case TTK_Interface: | |||
835 | FixItTagName = "__interface "; | |||
836 | break; | |||
837 | ||||
838 | case TTK_Union: | |||
839 | FixItTagName = "union "; | |||
840 | break; | |||
841 | } | |||
842 | ||||
843 | StringRef TagName = FixItTagName.drop_back(); | |||
844 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) | |||
845 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus | |||
846 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); | |||
847 | ||||
848 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); | |||
849 | I != IEnd; ++I) | |||
850 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) | |||
851 | << Name << TagName; | |||
852 | ||||
853 | // Replace lookup results with just the tag decl. | |||
854 | Result.clear(Sema::LookupTagName); | |||
855 | SemaRef.LookupParsedName(Result, S, &SS); | |||
856 | return true; | |||
857 | } | |||
858 | ||||
859 | return false; | |||
860 | } | |||
861 | ||||
862 | Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, | |||
863 | IdentifierInfo *&Name, | |||
864 | SourceLocation NameLoc, | |||
865 | const Token &NextToken, | |||
866 | CorrectionCandidateCallback *CCC) { | |||
867 | DeclarationNameInfo NameInfo(Name, NameLoc); | |||
868 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | |||
869 | ||||
870 | assert(NextToken.isNot(tok::coloncolon) &&(static_cast <bool> (NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName") ? void (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\"" , "clang/lib/Sema/SemaDecl.cpp", 871, __extension__ __PRETTY_FUNCTION__ )) | |||
871 | "parse nested name specifiers before calling ClassifyName")(static_cast <bool> (NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName") ? void (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\"" , "clang/lib/Sema/SemaDecl.cpp", 871, __extension__ __PRETTY_FUNCTION__ )); | |||
872 | if (getLangOpts().CPlusPlus && SS.isSet() && | |||
873 | isCurrentClassName(*Name, S, &SS)) { | |||
874 | // Per [class.qual]p2, this names the constructors of SS, not the | |||
875 | // injected-class-name. We don't have a classification for that. | |||
876 | // There's not much point caching this result, since the parser | |||
877 | // will reject it later. | |||
878 | return NameClassification::Unknown(); | |||
879 | } | |||
880 | ||||
881 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | |||
882 | LookupParsedName(Result, S, &SS, !CurMethod); | |||
883 | ||||
884 | if (SS.isInvalid()) | |||
885 | return NameClassification::Error(); | |||
886 | ||||
887 | // For unqualified lookup in a class template in MSVC mode, look into | |||
888 | // dependent base classes where the primary class template is known. | |||
889 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { | |||
890 | if (ParsedType TypeInBase = | |||
891 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) | |||
892 | return TypeInBase; | |||
893 | } | |||
894 | ||||
895 | // Perform lookup for Objective-C instance variables (including automatically | |||
896 | // synthesized instance variables), if we're in an Objective-C method. | |||
897 | // FIXME: This lookup really, really needs to be folded in to the normal | |||
898 | // unqualified lookup mechanism. | |||
899 | if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { | |||
900 | DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); | |||
901 | if (Ivar.isInvalid()) | |||
902 | return NameClassification::Error(); | |||
903 | if (Ivar.isUsable()) | |||
904 | return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); | |||
905 | ||||
906 | // We defer builtin creation until after ivar lookup inside ObjC methods. | |||
907 | if (Result.empty()) | |||
908 | LookupBuiltin(Result); | |||
909 | } | |||
910 | ||||
911 | bool SecondTry = false; | |||
912 | bool IsFilteredTemplateName = false; | |||
913 | ||||
914 | Corrected: | |||
915 | switch (Result.getResultKind()) { | |||
916 | case LookupResult::NotFound: | |||
917 | // If an unqualified-id is followed by a '(', then we have a function | |||
918 | // call. | |||
919 | if (SS.isEmpty() && NextToken.is(tok::l_paren)) { | |||
920 | // In C++, this is an ADL-only call. | |||
921 | // FIXME: Reference? | |||
922 | if (getLangOpts().CPlusPlus) | |||
923 | return NameClassification::UndeclaredNonType(); | |||
924 | ||||
925 | // C90 6.3.2.2: | |||
926 | // If the expression that precedes the parenthesized argument list in a | |||
927 | // function call consists solely of an identifier, and if no | |||
928 | // declaration is visible for this identifier, the identifier is | |||
929 | // implicitly declared exactly as if, in the innermost block containing | |||
930 | // the function call, the declaration | |||
931 | // | |||
932 | // extern int identifier (); | |||
933 | // | |||
934 | // appeared. | |||
935 | // | |||
936 | // We also allow this in C99 as an extension. | |||
937 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) | |||
938 | return NameClassification::NonType(D); | |||
939 | } | |||
940 | ||||
941 | if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { | |||
942 | // In C++20 onwards, this could be an ADL-only call to a function | |||
943 | // template, and we're required to assume that this is a template name. | |||
944 | // | |||
945 | // FIXME: Find a way to still do typo correction in this case. | |||
946 | TemplateName Template = | |||
947 | Context.getAssumedTemplateName(NameInfo.getName()); | |||
948 | return NameClassification::UndeclaredTemplate(Template); | |||
949 | } | |||
950 | ||||
951 | // In C, we first see whether there is a tag type by the same name, in | |||
952 | // which case it's likely that the user just forgot to write "enum", | |||
953 | // "struct", or "union". | |||
954 | if (!getLangOpts().CPlusPlus && !SecondTry && | |||
955 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | |||
956 | break; | |||
957 | } | |||
958 | ||||
959 | // Perform typo correction to determine if there is another name that is | |||
960 | // close to this name. | |||
961 | if (!SecondTry && CCC) { | |||
962 | SecondTry = true; | |||
963 | if (TypoCorrection Corrected = | |||
964 | CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, | |||
965 | &SS, *CCC, CTK_ErrorRecovery)) { | |||
966 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; | |||
967 | unsigned QualifiedDiag = diag::err_no_member_suggest; | |||
968 | ||||
969 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); | |||
970 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); | |||
971 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
972 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { | |||
973 | UnqualifiedDiag = diag::err_no_template_suggest; | |||
974 | QualifiedDiag = diag::err_no_member_template_suggest; | |||
975 | } else if (UnderlyingFirstDecl && | |||
976 | (isa<TypeDecl>(UnderlyingFirstDecl) || | |||
977 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || | |||
978 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { | |||
979 | UnqualifiedDiag = diag::err_unknown_typename_suggest; | |||
980 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; | |||
981 | } | |||
982 | ||||
983 | if (SS.isEmpty()) { | |||
984 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); | |||
985 | } else {// FIXME: is this even reachable? Test it. | |||
986 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | |||
987 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | |||
988 | Name->getName().equals(CorrectedStr); | |||
989 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) | |||
990 | << Name << computeDeclContext(SS, false) | |||
991 | << DroppedSpecifier << SS.getRange()); | |||
992 | } | |||
993 | ||||
994 | // Update the name, so that the caller has the new name. | |||
995 | Name = Corrected.getCorrectionAsIdentifierInfo(); | |||
996 | ||||
997 | // Typo correction corrected to a keyword. | |||
998 | if (Corrected.isKeyword()) | |||
999 | return Name; | |||
1000 | ||||
1001 | // Also update the LookupResult... | |||
1002 | // FIXME: This should probably go away at some point | |||
1003 | Result.clear(); | |||
1004 | Result.setLookupName(Corrected.getCorrection()); | |||
1005 | if (FirstDecl) | |||
1006 | Result.addDecl(FirstDecl); | |||
1007 | ||||
1008 | // If we found an Objective-C instance variable, let | |||
1009 | // LookupInObjCMethod build the appropriate expression to | |||
1010 | // reference the ivar. | |||
1011 | // FIXME: This is a gross hack. | |||
1012 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { | |||
1013 | DeclResult R = | |||
1014 | LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); | |||
1015 | if (R.isInvalid()) | |||
1016 | return NameClassification::Error(); | |||
1017 | if (R.isUsable()) | |||
1018 | return NameClassification::NonType(Ivar); | |||
1019 | } | |||
1020 | ||||
1021 | goto Corrected; | |||
1022 | } | |||
1023 | } | |||
1024 | ||||
1025 | // We failed to correct; just fall through and let the parser deal with it. | |||
1026 | Result.suppressDiagnostics(); | |||
1027 | return NameClassification::Unknown(); | |||
1028 | ||||
1029 | case LookupResult::NotFoundInCurrentInstantiation: { | |||
1030 | // We performed name lookup into the current instantiation, and there were | |||
1031 | // dependent bases, so we treat this result the same way as any other | |||
1032 | // dependent nested-name-specifier. | |||
1033 | ||||
1034 | // C++ [temp.res]p2: | |||
1035 | // A name used in a template declaration or definition and that is | |||
1036 | // dependent on a template-parameter is assumed not to name a type | |||
1037 | // unless the applicable name lookup finds a type name or the name is | |||
1038 | // qualified by the keyword typename. | |||
1039 | // | |||
1040 | // FIXME: If the next token is '<', we might want to ask the parser to | |||
1041 | // perform some heroics to see if we actually have a | |||
1042 | // template-argument-list, which would indicate a missing 'template' | |||
1043 | // keyword here. | |||
1044 | return NameClassification::DependentNonType(); | |||
1045 | } | |||
1046 | ||||
1047 | case LookupResult::Found: | |||
1048 | case LookupResult::FoundOverloaded: | |||
1049 | case LookupResult::FoundUnresolvedValue: | |||
1050 | break; | |||
1051 | ||||
1052 | case LookupResult::Ambiguous: | |||
1053 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
1054 | hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, | |||
1055 | /*AllowDependent=*/false)) { | |||
1056 | // C++ [temp.local]p3: | |||
1057 | // A lookup that finds an injected-class-name (10.2) can result in an | |||
1058 | // ambiguity in certain cases (for example, if it is found in more than | |||
1059 | // one base class). If all of the injected-class-names that are found | |||
1060 | // refer to specializations of the same class template, and if the name | |||
1061 | // is followed by a template-argument-list, the reference refers to the | |||
1062 | // class template itself and not a specialization thereof, and is not | |||
1063 | // ambiguous. | |||
1064 | // | |||
1065 | // This filtering can make an ambiguous result into an unambiguous one, | |||
1066 | // so try again after filtering out template names. | |||
1067 | FilterAcceptableTemplateNames(Result); | |||
1068 | if (!Result.isAmbiguous()) { | |||
1069 | IsFilteredTemplateName = true; | |||
1070 | break; | |||
1071 | } | |||
1072 | } | |||
1073 | ||||
1074 | // Diagnose the ambiguity and return an error. | |||
1075 | return NameClassification::Error(); | |||
1076 | } | |||
1077 | ||||
1078 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | |||
1079 | (IsFilteredTemplateName || | |||
1080 | hasAnyAcceptableTemplateNames( | |||
1081 | Result, /*AllowFunctionTemplates=*/true, | |||
1082 | /*AllowDependent=*/false, | |||
1083 | /*AllowNonTemplateFunctions*/ SS.isEmpty() && | |||
1084 | getLangOpts().CPlusPlus20))) { | |||
1085 | // C++ [temp.names]p3: | |||
1086 | // After name lookup (3.4) finds that a name is a template-name or that | |||
1087 | // an operator-function-id or a literal- operator-id refers to a set of | |||
1088 | // overloaded functions any member of which is a function template if | |||
1089 | // this is followed by a <, the < is always taken as the delimiter of a | |||
1090 | // template-argument-list and never as the less-than operator. | |||
1091 | // C++2a [temp.names]p2: | |||
1092 | // A name is also considered to refer to a template if it is an | |||
1093 | // unqualified-id followed by a < and name lookup finds either one | |||
1094 | // or more functions or finds nothing. | |||
1095 | if (!IsFilteredTemplateName) | |||
1096 | FilterAcceptableTemplateNames(Result); | |||
1097 | ||||
1098 | bool IsFunctionTemplate; | |||
1099 | bool IsVarTemplate; | |||
1100 | TemplateName Template; | |||
1101 | if (Result.end() - Result.begin() > 1) { | |||
1102 | IsFunctionTemplate = true; | |||
1103 | Template = Context.getOverloadedTemplateName(Result.begin(), | |||
1104 | Result.end()); | |||
1105 | } else if (!Result.empty()) { | |||
1106 | auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( | |||
1107 | *Result.begin(), /*AllowFunctionTemplates=*/true, | |||
1108 | /*AllowDependent=*/false)); | |||
1109 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); | |||
1110 | IsVarTemplate = isa<VarTemplateDecl>(TD); | |||
1111 | ||||
1112 | UsingShadowDecl *FoundUsingShadow = | |||
1113 | dyn_cast<UsingShadowDecl>(*Result.begin()); | |||
1114 | ||||
1115 | if (SS.isNotEmpty()) { | |||
1116 | // FIXME: support using shadow-declaration in qualified template name. | |||
1117 | Template = | |||
1118 | Context.getQualifiedTemplateName(SS.getScopeRep(), | |||
1119 | /*TemplateKeyword=*/false, TD); | |||
1120 | } else { | |||
1121 | assert(!FoundUsingShadow ||(static_cast <bool> (!FoundUsingShadow || TD == cast< TemplateDecl>(FoundUsingShadow->getTargetDecl())) ? void (0) : __assert_fail ("!FoundUsingShadow || TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())" , "clang/lib/Sema/SemaDecl.cpp", 1122, __extension__ __PRETTY_FUNCTION__ )) | |||
1122 | TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl()))(static_cast <bool> (!FoundUsingShadow || TD == cast< TemplateDecl>(FoundUsingShadow->getTargetDecl())) ? void (0) : __assert_fail ("!FoundUsingShadow || TD == cast<TemplateDecl>(FoundUsingShadow->getTargetDecl())" , "clang/lib/Sema/SemaDecl.cpp", 1122, __extension__ __PRETTY_FUNCTION__ )); | |||
1123 | Template = FoundUsingShadow ? TemplateName(FoundUsingShadow) | |||
1124 | : TemplateName(TD); | |||
1125 | } | |||
1126 | } else { | |||
1127 | // All results were non-template functions. This is a function template | |||
1128 | // name. | |||
1129 | IsFunctionTemplate = true; | |||
1130 | Template = Context.getAssumedTemplateName(NameInfo.getName()); | |||
1131 | } | |||
1132 | ||||
1133 | if (IsFunctionTemplate) { | |||
1134 | // Function templates always go through overload resolution, at which | |||
1135 | // point we'll perform the various checks (e.g., accessibility) we need | |||
1136 | // to based on which function we selected. | |||
1137 | Result.suppressDiagnostics(); | |||
1138 | ||||
1139 | return NameClassification::FunctionTemplate(Template); | |||
1140 | } | |||
1141 | ||||
1142 | return IsVarTemplate ? NameClassification::VarTemplate(Template) | |||
1143 | : NameClassification::TypeTemplate(Template); | |||
1144 | } | |||
1145 | ||||
1146 | auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) { | |||
1147 | QualType T = Context.getTypeDeclType(Type); | |||
1148 | if (const auto *USD = dyn_cast<UsingShadowDecl>(Found)) | |||
1149 | T = Context.getUsingType(USD, T); | |||
1150 | ||||
1151 | if (SS.isEmpty()) // No elaborated type, trivial location info | |||
1152 | return ParsedType::make(T); | |||
1153 | ||||
1154 | TypeLocBuilder Builder; | |||
1155 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | |||
1156 | T = getElaboratedType(ETK_None, SS, T); | |||
1157 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | |||
1158 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | |||
1159 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); | |||
1160 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | |||
1161 | }; | |||
1162 | ||||
1163 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); | |||
1164 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { | |||
1165 | DiagnoseUseOfDecl(Type, NameLoc); | |||
1166 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | |||
1167 | return BuildTypeFor(Type, *Result.begin()); | |||
1168 | } | |||
1169 | ||||
1170 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); | |||
1171 | if (!Class) { | |||
1172 | // FIXME: It's unfortunate that we don't have a Type node for handling this. | |||
1173 | if (ObjCCompatibleAliasDecl *Alias = | |||
1174 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) | |||
1175 | Class = Alias->getClassInterface(); | |||
1176 | } | |||
1177 | ||||
1178 | if (Class) { | |||
1179 | DiagnoseUseOfDecl(Class, NameLoc); | |||
1180 | ||||
1181 | if (NextToken.is(tok::period)) { | |||
1182 | // Interface. <something> is parsed as a property reference expression. | |||
1183 | // Just return "unknown" as a fall-through for now. | |||
1184 | Result.suppressDiagnostics(); | |||
1185 | return NameClassification::Unknown(); | |||
1186 | } | |||
1187 | ||||
1188 | QualType T = Context.getObjCInterfaceType(Class); | |||
1189 | return ParsedType::make(T); | |||
1190 | } | |||
1191 | ||||
1192 | if (isa<ConceptDecl>(FirstDecl)) | |||
1193 | return NameClassification::Concept( | |||
1194 | TemplateName(cast<TemplateDecl>(FirstDecl))); | |||
1195 | ||||
1196 | if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) { | |||
1197 | (void)DiagnoseUseOfDecl(EmptyD, NameLoc); | |||
1198 | return NameClassification::Error(); | |||
1199 | } | |||
1200 | ||||
1201 | // We can have a type template here if we're classifying a template argument. | |||
1202 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && | |||
1203 | !isa<VarTemplateDecl>(FirstDecl)) | |||
1204 | return NameClassification::TypeTemplate( | |||
1205 | TemplateName(cast<TemplateDecl>(FirstDecl))); | |||
1206 | ||||
1207 | // Check for a tag type hidden by a non-type decl in a few cases where it | |||
1208 | // seems likely a type is wanted instead of the non-type that was found. | |||
1209 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); | |||
1210 | if ((NextToken.is(tok::identifier) || | |||
1211 | (NextIsOp && | |||
1212 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && | |||
1213 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | |||
1214 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); | |||
1215 | DiagnoseUseOfDecl(Type, NameLoc); | |||
1216 | return BuildTypeFor(Type, *Result.begin()); | |||
1217 | } | |||
1218 | ||||
1219 | // If we already know which single declaration is referenced, just annotate | |||
1220 | // that declaration directly. Defer resolving even non-overloaded class | |||
1221 | // member accesses, as we need to defer certain access checks until we know | |||
1222 | // the context. | |||
1223 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | |||
1224 | if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) | |||
1225 | return NameClassification::NonType(Result.getRepresentativeDecl()); | |||
1226 | ||||
1227 | // Otherwise, this is an overload set that we will need to resolve later. | |||
1228 | Result.suppressDiagnostics(); | |||
1229 | return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( | |||
1230 | Context, Result.getNamingClass(), SS.getWithLocInContext(Context), | |||
1231 | Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), | |||
1232 | Result.begin(), Result.end())); | |||
1233 | } | |||
1234 | ||||
1235 | ExprResult | |||
1236 | Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, | |||
1237 | SourceLocation NameLoc) { | |||
1238 | assert(getLangOpts().CPlusPlus && "ADL-only call in C?")(static_cast <bool> (getLangOpts().CPlusPlus && "ADL-only call in C?") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\"" , "clang/lib/Sema/SemaDecl.cpp", 1238, __extension__ __PRETTY_FUNCTION__ )); | |||
1239 | CXXScopeSpec SS; | |||
1240 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | |||
1241 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); | |||
1242 | } | |||
1243 | ||||
1244 | ExprResult | |||
1245 | Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, | |||
1246 | IdentifierInfo *Name, | |||
1247 | SourceLocation NameLoc, | |||
1248 | bool IsAddressOfOperand) { | |||
1249 | DeclarationNameInfo NameInfo(Name, NameLoc); | |||
1250 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), | |||
1251 | NameInfo, IsAddressOfOperand, | |||
1252 | /*TemplateArgs=*/nullptr); | |||
1253 | } | |||
1254 | ||||
1255 | ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, | |||
1256 | NamedDecl *Found, | |||
1257 | SourceLocation NameLoc, | |||
1258 | const Token &NextToken) { | |||
1259 | if (getCurMethodDecl() && SS.isEmpty()) | |||
1260 | if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) | |||
1261 | return BuildIvarRefExpr(S, NameLoc, Ivar); | |||
1262 | ||||
1263 | // Reconstruct the lookup result. | |||
1264 | LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); | |||
1265 | Result.addDecl(Found); | |||
1266 | Result.resolveKind(); | |||
1267 | ||||
1268 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | |||
1269 | return BuildDeclarationNameExpr(SS, Result, ADL); | |||
1270 | } | |||
1271 | ||||
1272 | ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { | |||
1273 | // For an implicit class member access, transform the result into a member | |||
1274 | // access expression if necessary. | |||
1275 | auto *ULE = cast<UnresolvedLookupExpr>(E); | |||
1276 | if ((*ULE->decls_begin())->isCXXClassMember()) { | |||
1277 | CXXScopeSpec SS; | |||
1278 | SS.Adopt(ULE->getQualifierLoc()); | |||
1279 | ||||
1280 | // Reconstruct the lookup result. | |||
1281 | LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), | |||
1282 | LookupOrdinaryName); | |||
1283 | Result.setNamingClass(ULE->getNamingClass()); | |||
1284 | for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) | |||
1285 | Result.addDecl(*I, I.getAccess()); | |||
1286 | Result.resolveKind(); | |||
1287 | return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, | |||
1288 | nullptr, S); | |||
1289 | } | |||
1290 | ||||
1291 | // Otherwise, this is already in the form we needed, and no further checks | |||
1292 | // are necessary. | |||
1293 | return ULE; | |||
1294 | } | |||
1295 | ||||
1296 | Sema::TemplateNameKindForDiagnostics | |||
1297 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { | |||
1298 | auto *TD = Name.getAsTemplateDecl(); | |||
1299 | if (!TD) | |||
1300 | return TemplateNameKindForDiagnostics::DependentTemplate; | |||
1301 | if (isa<ClassTemplateDecl>(TD)) | |||
1302 | return TemplateNameKindForDiagnostics::ClassTemplate; | |||
1303 | if (isa<FunctionTemplateDecl>(TD)) | |||
1304 | return TemplateNameKindForDiagnostics::FunctionTemplate; | |||
1305 | if (isa<VarTemplateDecl>(TD)) | |||
1306 | return TemplateNameKindForDiagnostics::VarTemplate; | |||
1307 | if (isa<TypeAliasTemplateDecl>(TD)) | |||
1308 | return TemplateNameKindForDiagnostics::AliasTemplate; | |||
1309 | if (isa<TemplateTemplateParmDecl>(TD)) | |||
1310 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; | |||
1311 | if (isa<ConceptDecl>(TD)) | |||
1312 | return TemplateNameKindForDiagnostics::Concept; | |||
1313 | return TemplateNameKindForDiagnostics::DependentTemplate; | |||
1314 | } | |||
1315 | ||||
1316 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { | |||
1317 | assert(DC->getLexicalParent() == CurContext &&(static_cast <bool> (DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 1318, __extension__ __PRETTY_FUNCTION__ )) | |||
1318 | "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 1318, __extension__ __PRETTY_FUNCTION__ )); | |||
1319 | CurContext = DC; | |||
1320 | S->setEntity(DC); | |||
1321 | } | |||
1322 | ||||
1323 | void Sema::PopDeclContext() { | |||
1324 | assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!" ) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "clang/lib/Sema/SemaDecl.cpp", 1324, __extension__ __PRETTY_FUNCTION__ )); | |||
1325 | ||||
1326 | CurContext = CurContext->getLexicalParent(); | |||
1327 | assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!" ) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "clang/lib/Sema/SemaDecl.cpp", 1327, __extension__ __PRETTY_FUNCTION__ )); | |||
1328 | } | |||
1329 | ||||
1330 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, | |||
1331 | Decl *D) { | |||
1332 | // Unlike PushDeclContext, the context to which we return is not necessarily | |||
1333 | // the containing DC of TD, because the new context will be some pre-existing | |||
1334 | // TagDecl definition instead of a fresh one. | |||
1335 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); | |||
1336 | CurContext = cast<TagDecl>(D)->getDefinition(); | |||
1337 | assert(CurContext && "skipping definition of undefined tag")(static_cast <bool> (CurContext && "skipping definition of undefined tag" ) ? void (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\"" , "clang/lib/Sema/SemaDecl.cpp", 1337, __extension__ __PRETTY_FUNCTION__ )); | |||
1338 | // Start lookups from the parent of the current context; we don't want to look | |||
1339 | // into the pre-existing complete definition. | |||
1340 | S->setEntity(CurContext->getLookupParent()); | |||
1341 | return Result; | |||
1342 | } | |||
1343 | ||||
1344 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { | |||
1345 | CurContext = static_cast<decltype(CurContext)>(Context); | |||
1346 | } | |||
1347 | ||||
1348 | /// EnterDeclaratorContext - Used when we must lookup names in the context | |||
1349 | /// of a declarator's nested name specifier. | |||
1350 | /// | |||
1351 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { | |||
1352 | // C++0x [basic.lookup.unqual]p13: | |||
1353 | // A name used in the definition of a static data member of class | |||
1354 | // X (after the qualified-id of the static member) is looked up as | |||
1355 | // if the name was used in a member function of X. | |||
1356 | // C++0x [basic.lookup.unqual]p14: | |||
1357 | // If a variable member of a namespace is defined outside of the | |||
1358 | // scope of its namespace then any name used in the definition of | |||
1359 | // the variable member (after the declarator-id) is looked up as | |||
1360 | // if the definition of the variable member occurred in its | |||
1361 | // namespace. | |||
1362 | // Both of these imply that we should push a scope whose context | |||
1363 | // is the semantic context of the declaration. We can't use | |||
1364 | // PushDeclContext here because that context is not necessarily | |||
1365 | // lexically contained in the current context. Fortunately, | |||
1366 | // the containing scope should have the appropriate information. | |||
1367 | ||||
1368 | assert(!S->getEntity() && "scope already has entity")(static_cast <bool> (!S->getEntity() && "scope already has entity" ) ? void (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\"" , "clang/lib/Sema/SemaDecl.cpp", 1368, __extension__ __PRETTY_FUNCTION__ )); | |||
1369 | ||||
1370 | #ifndef NDEBUG | |||
1371 | Scope *Ancestor = S->getParent(); | |||
1372 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | |||
1373 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")(static_cast <bool> (Ancestor->getEntity() == CurContext && "ancestor context mismatch") ? void (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"" , "clang/lib/Sema/SemaDecl.cpp", 1373, __extension__ __PRETTY_FUNCTION__ )); | |||
1374 | #endif | |||
1375 | ||||
1376 | CurContext = DC; | |||
1377 | S->setEntity(DC); | |||
1378 | ||||
1379 | if (S->getParent()->isTemplateParamScope()) { | |||
1380 | // Also set the corresponding entities for all immediately-enclosing | |||
1381 | // template parameter scopes. | |||
1382 | EnterTemplatedContext(S->getParent(), DC); | |||
1383 | } | |||
1384 | } | |||
1385 | ||||
1386 | void Sema::ExitDeclaratorContext(Scope *S) { | |||
1387 | assert(S->getEntity() == CurContext && "Context imbalance!")(static_cast <bool> (S->getEntity() == CurContext && "Context imbalance!") ? void (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"" , "clang/lib/Sema/SemaDecl.cpp", 1387, __extension__ __PRETTY_FUNCTION__ )); | |||
1388 | ||||
1389 | // Switch back to the lexical context. The safety of this is | |||
1390 | // enforced by an assert in EnterDeclaratorContext. | |||
1391 | Scope *Ancestor = S->getParent(); | |||
1392 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | |||
1393 | CurContext = Ancestor->getEntity(); | |||
1394 | ||||
1395 | // We don't need to do anything with the scope, which is going to | |||
1396 | // disappear. | |||
1397 | } | |||
1398 | ||||
1399 | void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { | |||
1400 | assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() && "expected to be initializing a template parameter scope") ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\"" , "clang/lib/Sema/SemaDecl.cpp", 1401, __extension__ __PRETTY_FUNCTION__ )) | |||
1401 | "expected to be initializing a template parameter scope")(static_cast <bool> (S->isTemplateParamScope() && "expected to be initializing a template parameter scope") ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\"" , "clang/lib/Sema/SemaDecl.cpp", 1401, __extension__ __PRETTY_FUNCTION__ )); | |||
1402 | ||||
1403 | // C++20 [temp.local]p7: | |||
1404 | // In the definition of a member of a class template that appears outside | |||
1405 | // of the class template definition, the name of a member of the class | |||
1406 | // template hides the name of a template-parameter of any enclosing class | |||
1407 | // templates (but not a template-parameter of the member if the member is a | |||
1408 | // class or function template). | |||
1409 | // C++20 [temp.local]p9: | |||
1410 | // In the definition of a class template or in the definition of a member | |||
1411 | // of such a template that appears outside of the template definition, for | |||
1412 | // each non-dependent base class (13.8.2.1), if the name of the base class | |||
1413 | // or the name of a member of the base class is the same as the name of a | |||
1414 | // template-parameter, the base class name or member name hides the | |||
1415 | // template-parameter name (6.4.10). | |||
1416 | // | |||
1417 | // This means that a template parameter scope should be searched immediately | |||
1418 | // after searching the DeclContext for which it is a template parameter | |||
1419 | // scope. For example, for | |||
1420 | // template<typename T> template<typename U> template<typename V> | |||
1421 | // void N::A<T>::B<U>::f(...) | |||
1422 | // we search V then B<U> (and base classes) then U then A<T> (and base | |||
1423 | // classes) then T then N then ::. | |||
1424 | unsigned ScopeDepth = getTemplateDepth(S); | |||
1425 | for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { | |||
1426 | DeclContext *SearchDCAfterScope = DC; | |||
1427 | for (; DC; DC = DC->getLookupParent()) { | |||
1428 | if (const TemplateParameterList *TPL = | |||
1429 | cast<Decl>(DC)->getDescribedTemplateParams()) { | |||
1430 | unsigned DCDepth = TPL->getDepth() + 1; | |||
1431 | if (DCDepth > ScopeDepth) | |||
1432 | continue; | |||
1433 | if (ScopeDepth == DCDepth) | |||
1434 | SearchDCAfterScope = DC = DC->getLookupParent(); | |||
1435 | break; | |||
1436 | } | |||
1437 | } | |||
1438 | S->setLookupEntity(SearchDCAfterScope); | |||
1439 | } | |||
1440 | } | |||
1441 | ||||
1442 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { | |||
1443 | // We assume that the caller has already called | |||
1444 | // ActOnReenterTemplateScope so getTemplatedDecl() works. | |||
1445 | FunctionDecl *FD = D->getAsFunction(); | |||
1446 | if (!FD) | |||
1447 | return; | |||
1448 | ||||
1449 | // Same implementation as PushDeclContext, but enters the context | |||
1450 | // from the lexical parent, rather than the top-level class. | |||
1451 | assert(CurContext == FD->getLexicalParent() &&(static_cast <bool> (CurContext == FD->getLexicalParent () && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 1452, __extension__ __PRETTY_FUNCTION__ )) | |||
1452 | "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (CurContext == FD->getLexicalParent () && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 1452, __extension__ __PRETTY_FUNCTION__ )); | |||
1453 | CurContext = FD; | |||
1454 | S->setEntity(CurContext); | |||
1455 | ||||
1456 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { | |||
1457 | ParmVarDecl *Param = FD->getParamDecl(P); | |||
1458 | // If the parameter has an identifier, then add it to the scope | |||
1459 | if (Param->getIdentifier()) { | |||
1460 | S->AddDecl(Param); | |||
1461 | IdResolver.AddDecl(Param); | |||
1462 | } | |||
1463 | } | |||
1464 | } | |||
1465 | ||||
1466 | void Sema::ActOnExitFunctionContext() { | |||
1467 | // Same implementation as PopDeclContext, but returns to the lexical parent, | |||
1468 | // rather than the top-level class. | |||
1469 | assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!" ) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "clang/lib/Sema/SemaDecl.cpp", 1469, __extension__ __PRETTY_FUNCTION__ )); | |||
1470 | CurContext = CurContext->getLexicalParent(); | |||
1471 | assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!" ) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "clang/lib/Sema/SemaDecl.cpp", 1471, __extension__ __PRETTY_FUNCTION__ )); | |||
1472 | } | |||
1473 | ||||
1474 | /// Determine whether overloading is allowed for a new function | |||
1475 | /// declaration considering prior declarations of the same name. | |||
1476 | /// | |||
1477 | /// This routine determines whether overloading is possible, not | |||
1478 | /// whether a new declaration actually overloads a previous one. | |||
1479 | /// It will return true in C++ (where overloads are alway permitted) | |||
1480 | /// or, as a C extension, when either the new declaration or a | |||
1481 | /// previous one is declared with the 'overloadable' attribute. | |||
1482 | static bool AllowOverloadingOfFunction(const LookupResult &Previous, | |||
1483 | ASTContext &Context, | |||
1484 | const FunctionDecl *New) { | |||
1485 | if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>()) | |||
1486 | return true; | |||
1487 | ||||
1488 | // Multiversion function declarations are not overloads in the | |||
1489 | // usual sense of that term, but lookup will report that an | |||
1490 | // overload set was found if more than one multiversion function | |||
1491 | // declaration is present for the same name. It is therefore | |||
1492 | // inadequate to assume that some prior declaration(s) had | |||
1493 | // the overloadable attribute; checking is required. Since one | |||
1494 | // declaration is permitted to omit the attribute, it is necessary | |||
1495 | // to check at least two; hence the 'any_of' check below. Note that | |||
1496 | // the overloadable attribute is implicitly added to declarations | |||
1497 | // that were required to have it but did not. | |||
1498 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) { | |||
1499 | return llvm::any_of(Previous, [](const NamedDecl *ND) { | |||
1500 | return ND->hasAttr<OverloadableAttr>(); | |||
1501 | }); | |||
1502 | } else if (Previous.getResultKind() == LookupResult::Found) | |||
1503 | return Previous.getFoundDecl()->hasAttr<OverloadableAttr>(); | |||
1504 | ||||
1505 | return false; | |||
1506 | } | |||
1507 | ||||
1508 | /// Add this decl to the scope shadowed decl chains. | |||
1509 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { | |||
1510 | // Move up the scope chain until we find the nearest enclosing | |||
1511 | // non-transparent context. The declaration will be introduced into this | |||
1512 | // scope. | |||
1513 | while (S->getEntity() && S->getEntity()->isTransparentContext()) | |||
1514 | S = S->getParent(); | |||
1515 | ||||
1516 | // Add scoped declarations into their context, so that they can be | |||
1517 | // found later. Declarations without a context won't be inserted | |||
1518 | // into any context. | |||
1519 | if (AddToContext) | |||
1520 | CurContext->addDecl(D); | |||
1521 | ||||
1522 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they | |||
1523 | // are function-local declarations. | |||
1524 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent()) | |||
1525 | return; | |||
1526 | ||||
1527 | // Template instantiations should also not be pushed into scope. | |||
1528 | if (isa<FunctionDecl>(D) && | |||
1529 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) | |||
1530 | return; | |||
1531 | ||||
1532 | // If this replaces anything in the current scope, | |||
1533 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), | |||
1534 | IEnd = IdResolver.end(); | |||
1535 | for (; I != IEnd; ++I) { | |||
1536 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { | |||
1537 | S->RemoveDecl(*I); | |||
1538 | IdResolver.RemoveDecl(*I); | |||
1539 | ||||
1540 | // Should only need to replace one decl. | |||
1541 | break; | |||
1542 | } | |||
1543 | } | |||
1544 | ||||
1545 | S->AddDecl(D); | |||
1546 | ||||
1547 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { | |||
1548 | // Implicitly-generated labels may end up getting generated in an order that | |||
1549 | // isn't strictly lexical, which breaks name lookup. Be careful to insert | |||
1550 | // the label at the appropriate place in the identifier chain. | |||
1551 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { | |||
1552 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); | |||
1553 | if (IDC == CurContext) { | |||
1554 | if (!S->isDeclScope(*I)) | |||
1555 | continue; | |||
1556 | } else if (IDC->Encloses(CurContext)) | |||
1557 | break; | |||
1558 | } | |||
1559 | ||||
1560 | IdResolver.InsertDeclAfter(I, D); | |||
1561 | } else { | |||
1562 | IdResolver.AddDecl(D); | |||
1563 | } | |||
1564 | warnOnReservedIdentifier(D); | |||
1565 | } | |||
1566 | ||||
1567 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, | |||
1568 | bool AllowInlineNamespace) { | |||
1569 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); | |||
1570 | } | |||
1571 | ||||
1572 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { | |||
1573 | DeclContext *TargetDC = DC->getPrimaryContext(); | |||
1574 | do { | |||
1575 | if (DeclContext *ScopeDC = S->getEntity()) | |||
1576 | if (ScopeDC->getPrimaryContext() == TargetDC) | |||
1577 | return S; | |||
1578 | } while ((S = S->getParent())); | |||
1579 | ||||
1580 | return nullptr; | |||
1581 | } | |||
1582 | ||||
1583 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, | |||
1584 | DeclContext*, | |||
1585 | ASTContext&); | |||
1586 | ||||
1587 | /// Filters out lookup results that don't fall within the given scope | |||
1588 | /// as determined by isDeclInScope. | |||
1589 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | |||
1590 | bool ConsiderLinkage, | |||
1591 | bool AllowInlineNamespace) { | |||
1592 | LookupResult::Filter F = R.makeFilter(); | |||
1593 | while (F.hasNext()) { | |||
1594 | NamedDecl *D = F.next(); | |||
1595 | ||||
1596 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) | |||
1597 | continue; | |||
1598 | ||||
1599 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) | |||
1600 | continue; | |||
1601 | ||||
1602 | F.erase(); | |||
1603 | } | |||
1604 | ||||
1605 | F.done(); | |||
1606 | } | |||
1607 | ||||
1608 | /// We've determined that \p New is a redeclaration of \p Old. Check that they | |||
1609 | /// have compatible owning modules. | |||
1610 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { | |||
1611 | // [module.interface]p7: | |||
1612 | // A declaration is attached to a module as follows: | |||
1613 | // - If the declaration is a non-dependent friend declaration that nominates a | |||
1614 | // function with a declarator-id that is a qualified-id or template-id or that | |||
1615 | // nominates a class other than with an elaborated-type-specifier with neither | |||
1616 | // a nested-name-specifier nor a simple-template-id, it is attached to the | |||
1617 | // module to which the friend is attached ([basic.link]). | |||
1618 | if (New->getFriendObjectKind() && | |||
1619 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { | |||
1620 | New->setLocalOwningModule(Old->getOwningModule()); | |||
1621 | makeMergedDefinitionVisible(New); | |||
1622 | return false; | |||
1623 | } | |||
1624 | ||||
1625 | Module *NewM = New->getOwningModule(); | |||
1626 | Module *OldM = Old->getOwningModule(); | |||
1627 | ||||
1628 | if (NewM && NewM->Kind == Module::PrivateModuleFragment) | |||
1629 | NewM = NewM->Parent; | |||
1630 | if (OldM && OldM->Kind == Module::PrivateModuleFragment) | |||
1631 | OldM = OldM->Parent; | |||
1632 | ||||
1633 | // If we have a decl in a module partition, it is part of the containing | |||
1634 | // module (which is the only thing that can be importing it). | |||
1635 | if (NewM && OldM && | |||
1636 | (OldM->Kind == Module::ModulePartitionInterface || | |||
1637 | OldM->Kind == Module::ModulePartitionImplementation)) { | |||
1638 | return false; | |||
1639 | } | |||
1640 | ||||
1641 | if (NewM == OldM) | |||
1642 | return false; | |||
1643 | ||||
1644 | bool NewIsModuleInterface = NewM && NewM->isModulePurview(); | |||
1645 | bool OldIsModuleInterface = OldM && OldM->isModulePurview(); | |||
1646 | if (NewIsModuleInterface || OldIsModuleInterface) { | |||
1647 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: | |||
1648 | // if a declaration of D [...] appears in the purview of a module, all | |||
1649 | // other such declarations shall appear in the purview of the same module | |||
1650 | Diag(New->getLocation(), diag::err_mismatched_owning_module) | |||
1651 | << New | |||
1652 | << NewIsModuleInterface | |||
1653 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") | |||
1654 | << OldIsModuleInterface | |||
1655 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); | |||
1656 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
1657 | New->setInvalidDecl(); | |||
1658 | return true; | |||
1659 | } | |||
1660 | ||||
1661 | return false; | |||
1662 | } | |||
1663 | ||||
1664 | // [module.interface]p6: | |||
1665 | // A redeclaration of an entity X is implicitly exported if X was introduced by | |||
1666 | // an exported declaration; otherwise it shall not be exported. | |||
1667 | bool Sema::CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old) { | |||
1668 | // [module.interface]p1: | |||
1669 | // An export-declaration shall inhabit a namespace scope. | |||
1670 | // | |||
1671 | // So it is meaningless to talk about redeclaration which is not at namespace | |||
1672 | // scope. | |||
1673 | if (!New->getLexicalDeclContext() | |||
1674 | ->getNonTransparentContext() | |||
1675 | ->isFileContext() || | |||
1676 | !Old->getLexicalDeclContext() | |||
1677 | ->getNonTransparentContext() | |||
1678 | ->isFileContext()) | |||
1679 | return false; | |||
1680 | ||||
1681 | bool IsNewExported = New->isInExportDeclContext(); | |||
1682 | bool IsOldExported = Old->isInExportDeclContext(); | |||
1683 | ||||
1684 | // It should be irrevelant if both of them are not exported. | |||
1685 | if (!IsNewExported && !IsOldExported) | |||
1686 | return false; | |||
1687 | ||||
1688 | if (IsOldExported) | |||
1689 | return false; | |||
1690 | ||||
1691 | assert(IsNewExported)(static_cast <bool> (IsNewExported) ? void (0) : __assert_fail ("IsNewExported", "clang/lib/Sema/SemaDecl.cpp", 1691, __extension__ __PRETTY_FUNCTION__)); | |||
1692 | ||||
1693 | auto Lk = Old->getFormalLinkage(); | |||
1694 | int S = 0; | |||
1695 | if (Lk == Linkage::InternalLinkage) | |||
1696 | S = 1; | |||
1697 | else if (Lk == Linkage::ModuleLinkage) | |||
1698 | S = 2; | |||
1699 | Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New << S; | |||
1700 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
1701 | return true; | |||
1702 | } | |||
1703 | ||||
1704 | // A wrapper function for checking the semantic restrictions of | |||
1705 | // a redeclaration within a module. | |||
1706 | bool Sema::CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old) { | |||
1707 | if (CheckRedeclarationModuleOwnership(New, Old)) | |||
1708 | return true; | |||
1709 | ||||
1710 | if (CheckRedeclarationExported(New, Old)) | |||
1711 | return true; | |||
1712 | ||||
1713 | return false; | |||
1714 | } | |||
1715 | ||||
1716 | static bool isUsingDecl(NamedDecl *D) { | |||
1717 | return isa<UsingShadowDecl>(D) || | |||
1718 | isa<UnresolvedUsingTypenameDecl>(D) || | |||
1719 | isa<UnresolvedUsingValueDecl>(D); | |||
1720 | } | |||
1721 | ||||
1722 | /// Removes using shadow declarations from the lookup results. | |||
1723 | static void RemoveUsingDecls(LookupResult &R) { | |||
1724 | LookupResult::Filter F = R.makeFilter(); | |||
1725 | while (F.hasNext()) | |||
1726 | if (isUsingDecl(F.next())) | |||
1727 | F.erase(); | |||
1728 | ||||
1729 | F.done(); | |||
1730 | } | |||
1731 | ||||
1732 | /// Check for this common pattern: | |||
1733 | /// @code | |||
1734 | /// class S { | |||
1735 | /// S(const S&); // DO NOT IMPLEMENT | |||
1736 | /// void operator=(const S&); // DO NOT IMPLEMENT | |||
1737 | /// }; | |||
1738 | /// @endcode | |||
1739 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { | |||
1740 | // FIXME: Should check for private access too but access is set after we get | |||
1741 | // the decl here. | |||
1742 | if (D->doesThisDeclarationHaveABody()) | |||
1743 | return false; | |||
1744 | ||||
1745 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) | |||
1746 | return CD->isCopyConstructor(); | |||
1747 | return D->isCopyAssignmentOperator(); | |||
1748 | } | |||
1749 | ||||
1750 | // We need this to handle | |||
1751 | // | |||
1752 | // typedef struct { | |||
1753 | // void *foo() { return 0; } | |||
1754 | // } A; | |||
1755 | // | |||
1756 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' | |||
1757 | // for example. If 'A', foo will have external linkage. If we have '*A', | |||
1758 | // foo will have no linkage. Since we can't know until we get to the end | |||
1759 | // of the typedef, this function finds out if D might have non-external linkage. | |||
1760 | // Callers should verify at the end of the TU if it D has external linkage or | |||
1761 | // not. | |||
1762 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { | |||
1763 | const DeclContext *DC = D->getDeclContext(); | |||
1764 | while (!DC->isTranslationUnit()) { | |||
1765 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ | |||
1766 | if (!RD->hasNameForLinkage()) | |||
1767 | return true; | |||
1768 | } | |||
1769 | DC = DC->getParent(); | |||
1770 | } | |||
1771 | ||||
1772 | return !D->isExternallyVisible(); | |||
1773 | } | |||
1774 | ||||
1775 | // FIXME: This needs to be refactored; some other isInMainFile users want | |||
1776 | // these semantics. | |||
1777 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { | |||
1778 | if (S.TUKind != TU_Complete) | |||
1779 | return false; | |||
1780 | return S.SourceMgr.isInMainFile(Loc); | |||
1781 | } | |||
1782 | ||||
1783 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { | |||
1784 | assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D" , "clang/lib/Sema/SemaDecl.cpp", 1784, __extension__ __PRETTY_FUNCTION__ )); | |||
1785 | ||||
1786 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) | |||
1787 | return false; | |||
1788 | ||||
1789 | // Ignore all entities declared within templates, and out-of-line definitions | |||
1790 | // of members of class templates. | |||
1791 | if (D->getDeclContext()->isDependentContext() || | |||
1792 | D->getLexicalDeclContext()->isDependentContext()) | |||
1793 | return false; | |||
1794 | ||||
1795 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
1796 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | |||
1797 | return false; | |||
1798 | // A non-out-of-line declaration of a member specialization was implicitly | |||
1799 | // instantiated; it's the out-of-line declaration that we're interested in. | |||
1800 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | |||
1801 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) | |||
1802 | return false; | |||
1803 | ||||
1804 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
1805 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) | |||
1806 | return false; | |||
1807 | } else { | |||
1808 | // 'static inline' functions are defined in headers; don't warn. | |||
1809 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) | |||
1810 | return false; | |||
1811 | } | |||
1812 | ||||
1813 | if (FD->doesThisDeclarationHaveABody() && | |||
1814 | Context.DeclMustBeEmitted(FD)) | |||
1815 | return false; | |||
1816 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1817 | // Constants and utility variables are defined in headers with internal | |||
1818 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker | |||
1819 | // like "inline".) | |||
1820 | if (!isMainFileLoc(*this, VD->getLocation())) | |||
1821 | return false; | |||
1822 | ||||
1823 | if (Context.DeclMustBeEmitted(VD)) | |||
1824 | return false; | |||
1825 | ||||
1826 | if (VD->isStaticDataMember() && | |||
1827 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | |||
1828 | return false; | |||
1829 | if (VD->isStaticDataMember() && | |||
1830 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | |||
1831 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) | |||
1832 | return false; | |||
1833 | ||||
1834 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) | |||
1835 | return false; | |||
1836 | } else { | |||
1837 | return false; | |||
1838 | } | |||
1839 | ||||
1840 | // Only warn for unused decls internal to the translation unit. | |||
1841 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function | |||
1842 | // for inline functions defined in the main source file, for instance. | |||
1843 | return mightHaveNonExternalLinkage(D); | |||
1844 | } | |||
1845 | ||||
1846 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { | |||
1847 | if (!D) | |||
1848 | return; | |||
1849 | ||||
1850 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
1851 | const FunctionDecl *First = FD->getFirstDecl(); | |||
1852 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | |||
1853 | return; // First should already be in the vector. | |||
1854 | } | |||
1855 | ||||
1856 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1857 | const VarDecl *First = VD->getFirstDecl(); | |||
1858 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | |||
1859 | return; // First should already be in the vector. | |||
1860 | } | |||
1861 | ||||
1862 | if (ShouldWarnIfUnusedFileScopedDecl(D)) | |||
1863 | UnusedFileScopedDecls.push_back(D); | |||
1864 | } | |||
1865 | ||||
1866 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { | |||
1867 | if (D->isInvalidDecl()) | |||
1868 | return false; | |||
1869 | ||||
1870 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { | |||
1871 | // For a decomposition declaration, warn if none of the bindings are | |||
1872 | // referenced, instead of if the variable itself is referenced (which | |||
1873 | // it is, by the bindings' expressions). | |||
1874 | for (auto *BD : DD->bindings()) | |||
1875 | if (BD->isReferenced()) | |||
1876 | return false; | |||
1877 | } else if (!D->getDeclName()) { | |||
1878 | return false; | |||
1879 | } else if (D->isReferenced() || D->isUsed()) { | |||
1880 | return false; | |||
1881 | } | |||
1882 | ||||
1883 | if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) | |||
1884 | return false; | |||
1885 | ||||
1886 | if (isa<LabelDecl>(D)) | |||
1887 | return true; | |||
1888 | ||||
1889 | // Except for labels, we only care about unused decls that are local to | |||
1890 | // functions. | |||
1891 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); | |||
1892 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) | |||
1893 | // For dependent types, the diagnostic is deferred. | |||
1894 | WithinFunction = | |||
1895 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); | |||
1896 | if (!WithinFunction) | |||
1897 | return false; | |||
1898 | ||||
1899 | if (isa<TypedefNameDecl>(D)) | |||
1900 | return true; | |||
1901 | ||||
1902 | // White-list anything that isn't a local variable. | |||
1903 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) | |||
1904 | return false; | |||
1905 | ||||
1906 | // Types of valid local variables should be complete, so this should succeed. | |||
1907 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
1908 | ||||
1909 | const Expr *Init = VD->getInit(); | |||
1910 | if (const auto *Cleanups = dyn_cast_or_null<ExprWithCleanups>(Init)) | |||
1911 | Init = Cleanups->getSubExpr(); | |||
1912 | ||||
1913 | const auto *Ty = VD->getType().getTypePtr(); | |||
1914 | ||||
1915 | // Only look at the outermost level of typedef. | |||
1916 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { | |||
1917 | // Allow anything marked with __attribute__((unused)). | |||
1918 | if (TT->getDecl()->hasAttr<UnusedAttr>()) | |||
1919 | return false; | |||
1920 | } | |||
1921 | ||||
1922 | // Warn for reference variables whose initializtion performs lifetime | |||
1923 | // extension. | |||
1924 | if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(Init)) { | |||
1925 | if (MTE->getExtendingDecl()) { | |||
1926 | Ty = VD->getType().getNonReferenceType().getTypePtr(); | |||
1927 | Init = MTE->getSubExpr()->IgnoreImplicitAsWritten(); | |||
1928 | } | |||
1929 | } | |||
1930 | ||||
1931 | // If we failed to complete the type for some reason, or if the type is | |||
1932 | // dependent, don't diagnose the variable. | |||
1933 | if (Ty->isIncompleteType() || Ty->isDependentType()) | |||
1934 | return false; | |||
1935 | ||||
1936 | // Look at the element type to ensure that the warning behaviour is | |||
1937 | // consistent for both scalars and arrays. | |||
1938 | Ty = Ty->getBaseElementTypeUnsafe(); | |||
1939 | ||||
1940 | if (const TagType *TT = Ty->getAs<TagType>()) { | |||
1941 | const TagDecl *Tag = TT->getDecl(); | |||
1942 | if (Tag->hasAttr<UnusedAttr>()) | |||
1943 | return false; | |||
1944 | ||||
1945 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | |||
1946 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) | |||
1947 | return false; | |||
1948 | ||||
1949 | if (Init) { | |||
1950 | const CXXConstructExpr *Construct = | |||
1951 | dyn_cast<CXXConstructExpr>(Init); | |||
1952 | if (Construct && !Construct->isElidable()) { | |||
1953 | CXXConstructorDecl *CD = Construct->getConstructor(); | |||
1954 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && | |||
1955 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) | |||
1956 | return false; | |||
1957 | } | |||
1958 | ||||
1959 | // Suppress the warning if we don't know how this is constructed, and | |||
1960 | // it could possibly be non-trivial constructor. | |||
1961 | if (Init->isTypeDependent()) { | |||
1962 | for (const CXXConstructorDecl *Ctor : RD->ctors()) | |||
1963 | if (!Ctor->isTrivial()) | |||
1964 | return false; | |||
1965 | } | |||
1966 | ||||
1967 | // Suppress the warning if the constructor is unresolved because | |||
1968 | // its arguments are dependent. | |||
1969 | if (isa<CXXUnresolvedConstructExpr>(Init)) | |||
1970 | return false; | |||
1971 | } | |||
1972 | } | |||
1973 | } | |||
1974 | ||||
1975 | // TODO: __attribute__((unused)) templates? | |||
1976 | } | |||
1977 | ||||
1978 | return true; | |||
1979 | } | |||
1980 | ||||
1981 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, | |||
1982 | FixItHint &Hint) { | |||
1983 | if (isa<LabelDecl>(D)) { | |||
1984 | SourceLocation AfterColon = Lexer::findLocationAfterToken( | |||
1985 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), | |||
1986 | true); | |||
1987 | if (AfterColon.isInvalid()) | |||
1988 | return; | |||
1989 | Hint = FixItHint::CreateRemoval( | |||
1990 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); | |||
1991 | } | |||
1992 | } | |||
1993 | ||||
1994 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { | |||
1995 | if (D->getTypeForDecl()->isDependentType()) | |||
1996 | return; | |||
1997 | ||||
1998 | for (auto *TmpD : D->decls()) { | |||
1999 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) | |||
2000 | DiagnoseUnusedDecl(T); | |||
2001 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) | |||
2002 | DiagnoseUnusedNestedTypedefs(R); | |||
2003 | } | |||
2004 | } | |||
2005 | ||||
2006 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used | |||
2007 | /// unless they are marked attr(unused). | |||
2008 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { | |||
2009 | if (!ShouldDiagnoseUnusedDecl(D)) | |||
2010 | return; | |||
2011 | ||||
2012 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { | |||
2013 | // typedefs can be referenced later on, so the diagnostics are emitted | |||
2014 | // at end-of-translation-unit. | |||
2015 | UnusedLocalTypedefNameCandidates.insert(TD); | |||
2016 | return; | |||
2017 | } | |||
2018 | ||||
2019 | FixItHint Hint; | |||
2020 | GenerateFixForUnusedDecl(D, Context, Hint); | |||
2021 | ||||
2022 | unsigned DiagID; | |||
2023 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) | |||
2024 | DiagID = diag::warn_unused_exception_param; | |||
2025 | else if (isa<LabelDecl>(D)) | |||
2026 | DiagID = diag::warn_unused_label; | |||
2027 | else | |||
2028 | DiagID = diag::warn_unused_variable; | |||
2029 | ||||
2030 | Diag(D->getLocation(), DiagID) << D << Hint; | |||
2031 | } | |||
2032 | ||||
2033 | void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) { | |||
2034 | // If it's not referenced, it can't be set. If it has the Cleanup attribute, | |||
2035 | // it's not really unused. | |||
2036 | if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() || | |||
2037 | VD->hasAttr<CleanupAttr>()) | |||
2038 | return; | |||
2039 | ||||
2040 | const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe(); | |||
2041 | ||||
2042 | if (Ty->isReferenceType() || Ty->isDependentType()) | |||
2043 | return; | |||
2044 | ||||
2045 | if (const TagType *TT = Ty->getAs<TagType>()) { | |||
2046 | const TagDecl *Tag = TT->getDecl(); | |||
2047 | if (Tag->hasAttr<UnusedAttr>()) | |||
2048 | return; | |||
2049 | // In C++, don't warn for record types that don't have WarnUnusedAttr, to | |||
2050 | // mimic gcc's behavior. | |||
2051 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | |||
2052 | if (!RD->hasAttr<WarnUnusedAttr>()) | |||
2053 | return; | |||
2054 | } | |||
2055 | } | |||
2056 | ||||
2057 | // Don't warn about __block Objective-C pointer variables, as they might | |||
2058 | // be assigned in the block but not used elsewhere for the purpose of lifetime | |||
2059 | // extension. | |||
2060 | if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType()) | |||
2061 | return; | |||
2062 | ||||
2063 | // Don't warn about Objective-C pointer variables with precise lifetime | |||
2064 | // semantics; they can be used to ensure ARC releases the object at a known | |||
2065 | // time, which may mean assignment but no other references. | |||
2066 | if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType()) | |||
2067 | return; | |||
2068 | ||||
2069 | auto iter = RefsMinusAssignments.find(VD); | |||
2070 | if (iter == RefsMinusAssignments.end()) | |||
2071 | return; | |||
2072 | ||||
2073 | assert(iter->getSecond() >= 0 &&(static_cast <bool> (iter->getSecond() >= 0 && "Found a negative number of references to a VarDecl") ? void (0) : __assert_fail ("iter->getSecond() >= 0 && \"Found a negative number of references to a VarDecl\"" , "clang/lib/Sema/SemaDecl.cpp", 2074, __extension__ __PRETTY_FUNCTION__ )) | |||
2074 | "Found a negative number of references to a VarDecl")(static_cast <bool> (iter->getSecond() >= 0 && "Found a negative number of references to a VarDecl") ? void (0) : __assert_fail ("iter->getSecond() >= 0 && \"Found a negative number of references to a VarDecl\"" , "clang/lib/Sema/SemaDecl.cpp", 2074, __extension__ __PRETTY_FUNCTION__ )); | |||
2075 | if (iter->getSecond() != 0) | |||
2076 | return; | |||
2077 | unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter | |||
2078 | : diag::warn_unused_but_set_variable; | |||
2079 | Diag(VD->getLocation(), DiagID) << VD; | |||
2080 | } | |||
2081 | ||||
2082 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { | |||
2083 | // Verify that we have no forward references left. If so, there was a goto | |||
2084 | // or address of a label taken, but no definition of it. Label fwd | |||
2085 | // definitions are indicated with a null substmt which is also not a resolved | |||
2086 | // MS inline assembly label name. | |||
2087 | bool Diagnose = false; | |||
2088 | if (L->isMSAsmLabel()) | |||
2089 | Diagnose = !L->isResolvedMSAsmLabel(); | |||
2090 | else | |||
2091 | Diagnose = L->getStmt() == nullptr; | |||
2092 | if (Diagnose) | |||
2093 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; | |||
2094 | } | |||
2095 | ||||
2096 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { | |||
2097 | S->mergeNRVOIntoParent(); | |||
2098 | ||||
2099 | if (S->decl_empty()) return; | |||
2100 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(static_cast <bool> ((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && "Scope shouldn't contain decls!" ) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "clang/lib/Sema/SemaDecl.cpp", 2101, __extension__ __PRETTY_FUNCTION__ )) | |||
2101 | "Scope shouldn't contain decls!")(static_cast <bool> ((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && "Scope shouldn't contain decls!" ) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "clang/lib/Sema/SemaDecl.cpp", 2101, __extension__ __PRETTY_FUNCTION__ )); | |||
2102 | ||||
2103 | for (auto *TmpD : S->decls()) { | |||
2104 | assert(TmpD && "This decl didn't get pushed??")(static_cast <bool> (TmpD && "This decl didn't get pushed??" ) ? void (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\"" , "clang/lib/Sema/SemaDecl.cpp", 2104, __extension__ __PRETTY_FUNCTION__ )); | |||
2105 | ||||
2106 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")(static_cast <bool> (isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?") ? void (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\"" , "clang/lib/Sema/SemaDecl.cpp", 2106, __extension__ __PRETTY_FUNCTION__ )); | |||
2107 | NamedDecl *D = cast<NamedDecl>(TmpD); | |||
2108 | ||||
2109 | // Diagnose unused variables in this scope. | |||
2110 | if (!S->hasUnrecoverableErrorOccurred()) { | |||
2111 | DiagnoseUnusedDecl(D); | |||
2112 | if (const auto *RD = dyn_cast<RecordDecl>(D)) | |||
2113 | DiagnoseUnusedNestedTypedefs(RD); | |||
2114 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
2115 | DiagnoseUnusedButSetDecl(VD); | |||
2116 | RefsMinusAssignments.erase(VD); | |||
2117 | } | |||
2118 | } | |||
2119 | ||||
2120 | if (!D->getDeclName()) continue; | |||
2121 | ||||
2122 | // If this was a forward reference to a label, verify it was defined. | |||
2123 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) | |||
2124 | CheckPoppedLabel(LD, *this); | |||
2125 | ||||
2126 | // Remove this name from our lexical scope, and warn on it if we haven't | |||
2127 | // already. | |||
2128 | IdResolver.RemoveDecl(D); | |||
2129 | auto ShadowI = ShadowingDecls.find(D); | |||
2130 | if (ShadowI != ShadowingDecls.end()) { | |||
2131 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { | |||
2132 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) | |||
2133 | << D << FD << FD->getParent(); | |||
2134 | Diag(FD->getLocation(), diag::note_previous_declaration); | |||
2135 | } | |||
2136 | ShadowingDecls.erase(ShadowI); | |||
2137 | } | |||
2138 | } | |||
2139 | } | |||
2140 | ||||
2141 | /// Look for an Objective-C class in the translation unit. | |||
2142 | /// | |||
2143 | /// \param Id The name of the Objective-C class we're looking for. If | |||
2144 | /// typo-correction fixes this name, the Id will be updated | |||
2145 | /// to the fixed name. | |||
2146 | /// | |||
2147 | /// \param IdLoc The location of the name in the translation unit. | |||
2148 | /// | |||
2149 | /// \param DoTypoCorrection If true, this routine will attempt typo correction | |||
2150 | /// if there is no class with the given name. | |||
2151 | /// | |||
2152 | /// \returns The declaration of the named Objective-C class, or NULL if the | |||
2153 | /// class could not be found. | |||
2154 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, | |||
2155 | SourceLocation IdLoc, | |||
2156 | bool DoTypoCorrection) { | |||
2157 | // The third "scope" argument is 0 since we aren't enabling lazy built-in | |||
2158 | // creation from this context. | |||
2159 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); | |||
2160 | ||||
2161 | if (!IDecl && DoTypoCorrection) { | |||
2162 | // Perform typo correction at the given location, but only if we | |||
2163 | // find an Objective-C class name. | |||
2164 | DeclFilterCCC<ObjCInterfaceDecl> CCC{}; | |||
2165 | if (TypoCorrection C = | |||
2166 | CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, | |||
2167 | TUScope, nullptr, CCC, CTK_ErrorRecovery)) { | |||
2168 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); | |||
2169 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); | |||
2170 | Id = IDecl->getIdentifier(); | |||
2171 | } | |||
2172 | } | |||
2173 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); | |||
2174 | // This routine must always return a class definition, if any. | |||
2175 | if (Def && Def->getDefinition()) | |||
2176 | Def = Def->getDefinition(); | |||
2177 | return Def; | |||
2178 | } | |||
2179 | ||||
2180 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting | |||
2181 | /// from S, where a non-field would be declared. This routine copes | |||
2182 | /// with the difference between C and C++ scoping rules in structs and | |||
2183 | /// unions. For example, the following code is well-formed in C but | |||
2184 | /// ill-formed in C++: | |||
2185 | /// @code | |||
2186 | /// struct S6 { | |||
2187 | /// enum { BAR } e; | |||
2188 | /// }; | |||
2189 | /// | |||
2190 | /// void test_S6() { | |||
2191 | /// struct S6 a; | |||
2192 | /// a.e = BAR; | |||
2193 | /// } | |||
2194 | /// @endcode | |||
2195 | /// For the declaration of BAR, this routine will return a different | |||
2196 | /// scope. The scope S will be the scope of the unnamed enumeration | |||
2197 | /// within S6. In C++, this routine will return the scope associated | |||
2198 | /// with S6, because the enumeration's scope is a transparent | |||
2199 | /// context but structures can contain non-field names. In C, this | |||
2200 | /// routine will return the translation unit scope, since the | |||
2201 | /// enumeration's scope is a transparent context and structures cannot | |||
2202 | /// contain non-field names. | |||
2203 | Scope *Sema::getNonFieldDeclScope(Scope *S) { | |||
2204 | while (((S->getFlags() & Scope::DeclScope) == 0) || | |||
2205 | (S->getEntity() && S->getEntity()->isTransparentContext()) || | |||
2206 | (S->isClassScope() && !getLangOpts().CPlusPlus)) | |||
2207 | S = S->getParent(); | |||
2208 | return S; | |||
2209 | } | |||
2210 | ||||
2211 | static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, | |||
2212 | ASTContext::GetBuiltinTypeError Error) { | |||
2213 | switch (Error) { | |||
2214 | case ASTContext::GE_None: | |||
2215 | return ""; | |||
2216 | case ASTContext::GE_Missing_type: | |||
2217 | return BuiltinInfo.getHeaderName(ID); | |||
2218 | case ASTContext::GE_Missing_stdio: | |||
2219 | return "stdio.h"; | |||
2220 | case ASTContext::GE_Missing_setjmp: | |||
2221 | return "setjmp.h"; | |||
2222 | case ASTContext::GE_Missing_ucontext: | |||
2223 | return "ucontext.h"; | |||
2224 | } | |||
2225 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "clang/lib/Sema/SemaDecl.cpp" , 2225); | |||
2226 | } | |||
2227 | ||||
2228 | FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, | |||
2229 | unsigned ID, SourceLocation Loc) { | |||
2230 | DeclContext *Parent = Context.getTranslationUnitDecl(); | |||
2231 | ||||
2232 | if (getLangOpts().CPlusPlus) { | |||
2233 | LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( | |||
2234 | Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); | |||
2235 | CLinkageDecl->setImplicit(); | |||
2236 | Parent->addDecl(CLinkageDecl); | |||
2237 | Parent = CLinkageDecl; | |||
2238 | } | |||
2239 | ||||
2240 | FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, | |||
2241 | /*TInfo=*/nullptr, SC_Extern, | |||
2242 | getCurFPFeatures().isFPConstrained(), | |||
2243 | false, Type->isFunctionProtoType()); | |||
2244 | New->setImplicit(); | |||
2245 | New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); | |||
2246 | ||||
2247 | // Create Decl objects for each parameter, adding them to the | |||
2248 | // FunctionDecl. | |||
2249 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { | |||
2250 | SmallVector<ParmVarDecl *, 16> Params; | |||
2251 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | |||
2252 | ParmVarDecl *parm = ParmVarDecl::Create( | |||
2253 | Context, New, SourceLocation(), SourceLocation(), nullptr, | |||
2254 | FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); | |||
2255 | parm->setScopeInfo(0, i); | |||
2256 | Params.push_back(parm); | |||
2257 | } | |||
2258 | New->setParams(Params); | |||
2259 | } | |||
2260 | ||||
2261 | AddKnownFunctionAttributes(New); | |||
2262 | return New; | |||
2263 | } | |||
2264 | ||||
2265 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at | |||
2266 | /// file scope. lazily create a decl for it. ForRedeclaration is true | |||
2267 | /// if we're creating this built-in in anticipation of redeclaring the | |||
2268 | /// built-in. | |||
2269 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | |||
2270 | Scope *S, bool ForRedeclaration, | |||
2271 | SourceLocation Loc) { | |||
2272 | LookupNecessaryTypesForBuiltin(S, ID); | |||
2273 | ||||
2274 | ASTContext::GetBuiltinTypeError Error; | |||
2275 | QualType R = Context.GetBuiltinType(ID, Error); | |||
2276 | if (Error) { | |||
2277 | if (!ForRedeclaration) | |||
2278 | return nullptr; | |||
2279 | ||||
2280 | // If we have a builtin without an associated type we should not emit a | |||
2281 | // warning when we were not able to find a type for it. | |||
2282 | if (Error == ASTContext::GE_Missing_type || | |||
2283 | Context.BuiltinInfo.allowTypeMismatch(ID)) | |||
2284 | return nullptr; | |||
2285 | ||||
2286 | // If we could not find a type for setjmp it is because the jmp_buf type was | |||
2287 | // not defined prior to the setjmp declaration. | |||
2288 | if (Error == ASTContext::GE_Missing_setjmp) { | |||
2289 | Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) | |||
2290 | << Context.BuiltinInfo.getName(ID); | |||
2291 | return nullptr; | |||
2292 | } | |||
2293 | ||||
2294 | // Generally, we emit a warning that the declaration requires the | |||
2295 | // appropriate header. | |||
2296 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) | |||
2297 | << getHeaderName(Context.BuiltinInfo, ID, Error) | |||
2298 | << Context.BuiltinInfo.getName(ID); | |||
2299 | return nullptr; | |||
2300 | } | |||
2301 | ||||
2302 | if (!ForRedeclaration && | |||
2303 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || | |||
2304 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { | |||
2305 | Diag(Loc, diag::ext_implicit_lib_function_decl) | |||
2306 | << Context.BuiltinInfo.getName(ID) << R; | |||
2307 | if (const char *Header = Context.BuiltinInfo.getHeaderName(ID)) | |||
2308 | Diag(Loc, diag::note_include_header_or_declare) | |||
2309 | << Header << Context.BuiltinInfo.getName(ID); | |||
2310 | } | |||
2311 | ||||
2312 | if (R.isNull()) | |||
2313 | return nullptr; | |||
2314 | ||||
2315 | FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); | |||
2316 | RegisterLocallyScopedExternCDecl(New, S); | |||
2317 | ||||
2318 | // TUScope is the translation-unit scope to insert this function into. | |||
2319 | // FIXME: This is hideous. We need to teach PushOnScopeChains to | |||
2320 | // relate Scopes to DeclContexts, and probably eliminate CurContext | |||
2321 | // entirely, but we're not there yet. | |||
2322 | DeclContext *SavedContext = CurContext; | |||
2323 | CurContext = New->getDeclContext(); | |||
2324 | PushOnScopeChains(New, TUScope); | |||
2325 | CurContext = SavedContext; | |||
2326 | return New; | |||
2327 | } | |||
2328 | ||||
2329 | /// Typedef declarations don't have linkage, but they still denote the same | |||
2330 | /// entity if their types are the same. | |||
2331 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's | |||
2332 | /// isSameEntity. | |||
2333 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, | |||
2334 | TypedefNameDecl *Decl, | |||
2335 | LookupResult &Previous) { | |||
2336 | // This is only interesting when modules are enabled. | |||
2337 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) | |||
2338 | return; | |||
2339 | ||||
2340 | // Empty sets are uninteresting. | |||
2341 | if (Previous.empty()) | |||
2342 | return; | |||
2343 | ||||
2344 | LookupResult::Filter Filter = Previous.makeFilter(); | |||
2345 | while (Filter.hasNext()) { | |||
2346 | NamedDecl *Old = Filter.next(); | |||
2347 | ||||
2348 | // Non-hidden declarations are never ignored. | |||
2349 | if (S.isVisible(Old)) | |||
2350 | continue; | |||
2351 | ||||
2352 | // Declarations of the same entity are not ignored, even if they have | |||
2353 | // different linkages. | |||
2354 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | |||
2355 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), | |||
2356 | Decl->getUnderlyingType())) | |||
2357 | continue; | |||
2358 | ||||
2359 | // If both declarations give a tag declaration a typedef name for linkage | |||
2360 | // purposes, then they declare the same entity. | |||
2361 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && | |||
2362 | Decl->getAnonDeclWithTypedefName()) | |||
2363 | continue; | |||
2364 | } | |||
2365 | ||||
2366 | Filter.erase(); | |||
2367 | } | |||
2368 | ||||
2369 | Filter.done(); | |||
2370 | } | |||
2371 | ||||
2372 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { | |||
2373 | QualType OldType; | |||
2374 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) | |||
2375 | OldType = OldTypedef->getUnderlyingType(); | |||
2376 | else | |||
2377 | OldType = Context.getTypeDeclType(Old); | |||
2378 | QualType NewType = New->getUnderlyingType(); | |||
2379 | ||||
2380 | if (NewType->isVariablyModifiedType()) { | |||
2381 | // Must not redefine a typedef with a variably-modified type. | |||
2382 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | |||
2383 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) | |||
2384 | << Kind << NewType; | |||
2385 | if (Old->getLocation().isValid()) | |||
2386 | notePreviousDefinition(Old, New->getLocation()); | |||
2387 | New->setInvalidDecl(); | |||
2388 | return true; | |||
2389 | } | |||
2390 | ||||
2391 | if (OldType != NewType && | |||
2392 | !OldType->isDependentType() && | |||
2393 | !NewType->isDependentType() && | |||
2394 | !Context.hasSameType(OldType, NewType)) { | |||
2395 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | |||
2396 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) | |||
2397 | << Kind << NewType << OldType; | |||
2398 | if (Old->getLocation().isValid()) | |||
2399 | notePreviousDefinition(Old, New->getLocation()); | |||
2400 | New->setInvalidDecl(); | |||
2401 | return true; | |||
2402 | } | |||
2403 | return false; | |||
2404 | } | |||
2405 | ||||
2406 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the | |||
2407 | /// same name and scope as a previous declaration 'Old'. Figure out | |||
2408 | /// how to resolve this situation, merging decls or emitting | |||
2409 | /// diagnostics as appropriate. If there was an error, set New to be invalid. | |||
2410 | /// | |||
2411 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | |||
2412 | LookupResult &OldDecls) { | |||
2413 | // If the new decl is known invalid already, don't bother doing any | |||
2414 | // merging checks. | |||
2415 | if (New->isInvalidDecl()) return; | |||
2416 | ||||
2417 | // Allow multiple definitions for ObjC built-in typedefs. | |||
2418 | // FIXME: Verify the underlying types are equivalent! | |||
2419 | if (getLangOpts().ObjC) { | |||
2420 | const IdentifierInfo *TypeID = New->getIdentifier(); | |||
2421 | switch (TypeID->getLength()) { | |||
2422 | default: break; | |||
2423 | case 2: | |||
2424 | { | |||
2425 | if (!TypeID->isStr("id")) | |||
2426 | break; | |||
2427 | QualType T = New->getUnderlyingType(); | |||
2428 | if (!T->isPointerType()) | |||
2429 | break; | |||
2430 | if (!T->isVoidPointerType()) { | |||
2431 | QualType PT = T->castAs<PointerType>()->getPointeeType(); | |||
2432 | if (!PT->isStructureType()) | |||
2433 | break; | |||
2434 | } | |||
2435 | Context.setObjCIdRedefinitionType(T); | |||
2436 | // Install the built-in type for 'id', ignoring the current definition. | |||
2437 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); | |||
2438 | return; | |||
2439 | } | |||
2440 | case 5: | |||
2441 | if (!TypeID->isStr("Class")) | |||
2442 | break; | |||
2443 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); | |||
2444 | // Install the built-in type for 'Class', ignoring the current definition. | |||
2445 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); | |||
2446 | return; | |||
2447 | case 3: | |||
2448 | if (!TypeID->isStr("SEL")) | |||
2449 | break; | |||
2450 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); | |||
2451 | // Install the built-in type for 'SEL', ignoring the current definition. | |||
2452 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); | |||
2453 | return; | |||
2454 | } | |||
2455 | // Fall through - the typedef name was not a builtin type. | |||
2456 | } | |||
2457 | ||||
2458 | // Verify the old decl was also a type. | |||
2459 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); | |||
2460 | if (!Old) { | |||
2461 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
2462 | << New->getDeclName(); | |||
2463 | ||||
2464 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); | |||
2465 | if (OldD->getLocation().isValid()) | |||
2466 | notePreviousDefinition(OldD, New->getLocation()); | |||
2467 | ||||
2468 | return New->setInvalidDecl(); | |||
2469 | } | |||
2470 | ||||
2471 | // If the old declaration is invalid, just give up here. | |||
2472 | if (Old->isInvalidDecl()) | |||
2473 | return New->setInvalidDecl(); | |||
2474 | ||||
2475 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | |||
2476 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); | |||
2477 | auto *NewTag = New->getAnonDeclWithTypedefName(); | |||
2478 | NamedDecl *Hidden = nullptr; | |||
2479 | if (OldTag && NewTag && | |||
2480 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && | |||
2481 | !hasVisibleDefinition(OldTag, &Hidden)) { | |||
2482 | // There is a definition of this tag, but it is not visible. Use it | |||
2483 | // instead of our tag. | |||
2484 | New->setTypeForDecl(OldTD->getTypeForDecl()); | |||
2485 | if (OldTD->isModed()) | |||
2486 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), | |||
2487 | OldTD->getUnderlyingType()); | |||
2488 | else | |||
2489 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); | |||
2490 | ||||
2491 | // Make the old tag definition visible. | |||
2492 | makeMergedDefinitionVisible(Hidden); | |||
2493 | ||||
2494 | // If this was an unscoped enumeration, yank all of its enumerators | |||
2495 | // out of the scope. | |||
2496 | if (isa<EnumDecl>(NewTag)) { | |||
2497 | Scope *EnumScope = getNonFieldDeclScope(S); | |||
2498 | for (auto *D : NewTag->decls()) { | |||
2499 | auto *ED = cast<EnumConstantDecl>(D); | |||
2500 | assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void (0) : __assert_fail ("EnumScope->isDeclScope(ED)", "clang/lib/Sema/SemaDecl.cpp" , 2500, __extension__ __PRETTY_FUNCTION__)); | |||
2501 | EnumScope->RemoveDecl(ED); | |||
2502 | IdResolver.RemoveDecl(ED); | |||
2503 | ED->getLexicalDeclContext()->removeDecl(ED); | |||
2504 | } | |||
2505 | } | |||
2506 | } | |||
2507 | } | |||
2508 | ||||
2509 | // If the typedef types are not identical, reject them in all languages and | |||
2510 | // with any extensions enabled. | |||
2511 | if (isIncompatibleTypedef(Old, New)) | |||
2512 | return; | |||
2513 | ||||
2514 | // The types match. Link up the redeclaration chain and merge attributes if | |||
2515 | // the old declaration was a typedef. | |||
2516 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { | |||
2517 | New->setPreviousDecl(Typedef); | |||
2518 | mergeDeclAttributes(New, Old); | |||
2519 | } | |||
2520 | ||||
2521 | if (getLangOpts().MicrosoftExt) | |||
2522 | return; | |||
2523 | ||||
2524 | if (getLangOpts().CPlusPlus) { | |||
2525 | // C++ [dcl.typedef]p2: | |||
2526 | // In a given non-class scope, a typedef specifier can be used to | |||
2527 | // redefine the name of any type declared in that scope to refer | |||
2528 | // to the type to which it already refers. | |||
2529 | if (!isa<CXXRecordDecl>(CurContext)) | |||
2530 | return; | |||
2531 | ||||
2532 | // C++0x [dcl.typedef]p4: | |||
2533 | // In a given class scope, a typedef specifier can be used to redefine | |||
2534 | // any class-name declared in that scope that is not also a typedef-name | |||
2535 | // to refer to the type to which it already refers. | |||
2536 | // | |||
2537 | // This wording came in via DR424, which was a correction to the | |||
2538 | // wording in DR56, which accidentally banned code like: | |||
2539 | // | |||
2540 | // struct S { | |||
2541 | // typedef struct A { } A; | |||
2542 | // }; | |||
2543 | // | |||
2544 | // in the C++03 standard. We implement the C++0x semantics, which | |||
2545 | // allow the above but disallow | |||
2546 | // | |||
2547 | // struct S { | |||
2548 | // typedef int I; | |||
2549 | // typedef int I; | |||
2550 | // }; | |||
2551 | // | |||
2552 | // since that was the intent of DR56. | |||
2553 | if (!isa<TypedefNameDecl>(Old)) | |||
2554 | return; | |||
2555 | ||||
2556 | Diag(New->getLocation(), diag::err_redefinition) | |||
2557 | << New->getDeclName(); | |||
2558 | notePreviousDefinition(Old, New->getLocation()); | |||
2559 | return New->setInvalidDecl(); | |||
2560 | } | |||
2561 | ||||
2562 | // Modules always permit redefinition of typedefs, as does C11. | |||
2563 | if (getLangOpts().Modules || getLangOpts().C11) | |||
2564 | return; | |||
2565 | ||||
2566 | // If we have a redefinition of a typedef in C, emit a warning. This warning | |||
2567 | // is normally mapped to an error, but can be controlled with | |||
2568 | // -Wtypedef-redefinition. If either the original or the redefinition is | |||
2569 | // in a system header, don't emit this for compatibility with GCC. | |||
2570 | if (getDiagnostics().getSuppressSystemWarnings() && | |||
2571 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). | |||
2572 | (Old->isImplicit() || | |||
2573 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || | |||
2574 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) | |||
2575 | return; | |||
2576 | ||||
2577 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) | |||
2578 | << New->getDeclName(); | |||
2579 | notePreviousDefinition(Old, New->getLocation()); | |||
2580 | } | |||
2581 | ||||
2582 | /// DeclhasAttr - returns true if decl Declaration already has the target | |||
2583 | /// attribute. | |||
2584 | static bool DeclHasAttr(const Decl *D, const Attr *A) { | |||
2585 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); | |||
2586 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); | |||
2587 | for (const auto *i : D->attrs()) | |||
2588 | if (i->getKind() == A->getKind()) { | |||
2589 | if (Ann) { | |||
2590 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) | |||
2591 | return true; | |||
2592 | continue; | |||
2593 | } | |||
2594 | // FIXME: Don't hardcode this check | |||
2595 | if (OA && isa<OwnershipAttr>(i)) | |||
2596 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); | |||
2597 | return true; | |||
2598 | } | |||
2599 | ||||
2600 | return false; | |||
2601 | } | |||
2602 | ||||
2603 | static bool isAttributeTargetADefinition(Decl *D) { | |||
2604 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) | |||
2605 | return VD->isThisDeclarationADefinition(); | |||
2606 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) | |||
2607 | return TD->isCompleteDefinition() || TD->isBeingDefined(); | |||
2608 | return true; | |||
2609 | } | |||
2610 | ||||
2611 | /// Merge alignment attributes from \p Old to \p New, taking into account the | |||
2612 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. | |||
2613 | /// | |||
2614 | /// \return \c true if any attributes were added to \p New. | |||
2615 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { | |||
2616 | // Look for alignas attributes on Old, and pick out whichever attribute | |||
2617 | // specifies the strictest alignment requirement. | |||
2618 | AlignedAttr *OldAlignasAttr = nullptr; | |||
2619 | AlignedAttr *OldStrictestAlignAttr = nullptr; | |||
2620 | unsigned OldAlign = 0; | |||
2621 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { | |||
2622 | // FIXME: We have no way of representing inherited dependent alignments | |||
2623 | // in a case like: | |||
2624 | // template<int A, int B> struct alignas(A) X; | |||
2625 | // template<int A, int B> struct alignas(B) X {}; | |||
2626 | // For now, we just ignore any alignas attributes which are not on the | |||
2627 | // definition in such a case. | |||
2628 | if (I->isAlignmentDependent()) | |||
2629 | return false; | |||
2630 | ||||
2631 | if (I->isAlignas()) | |||
2632 | OldAlignasAttr = I; | |||
2633 | ||||
2634 | unsigned Align = I->getAlignment(S.Context); | |||
2635 | if (Align > OldAlign) { | |||
2636 | OldAlign = Align; | |||
2637 | OldStrictestAlignAttr = I; | |||
2638 | } | |||
2639 | } | |||
2640 | ||||
2641 | // Look for alignas attributes on New. | |||
2642 | AlignedAttr *NewAlignasAttr = nullptr; | |||
2643 | unsigned NewAlign = 0; | |||
2644 | for (auto *I : New->specific_attrs<AlignedAttr>()) { | |||
2645 | if (I->isAlignmentDependent()) | |||
2646 | return false; | |||
2647 | ||||
2648 | if (I->isAlignas()) | |||
2649 | NewAlignasAttr = I; | |||
2650 | ||||
2651 | unsigned Align = I->getAlignment(S.Context); | |||
2652 | if (Align > NewAlign) | |||
2653 | NewAlign = Align; | |||
2654 | } | |||
2655 | ||||
2656 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { | |||
2657 | // Both declarations have 'alignas' attributes. We require them to match. | |||
2658 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but | |||
2659 | // fall short. (If two declarations both have alignas, they must both match | |||
2660 | // every definition, and so must match each other if there is a definition.) | |||
2661 | ||||
2662 | // If either declaration only contains 'alignas(0)' specifiers, then it | |||
2663 | // specifies the natural alignment for the type. | |||
2664 | if (OldAlign == 0 || NewAlign == 0) { | |||
2665 | QualType Ty; | |||
2666 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) | |||
2667 | Ty = VD->getType(); | |||
2668 | else | |||
2669 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); | |||
2670 | ||||
2671 | if (OldAlign == 0) | |||
2672 | OldAlign = S.Context.getTypeAlign(Ty); | |||
2673 | if (NewAlign == 0) | |||
2674 | NewAlign = S.Context.getTypeAlign(Ty); | |||
2675 | } | |||
2676 | ||||
2677 | if (OldAlign != NewAlign) { | |||
2678 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) | |||
2679 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() | |||
2680 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); | |||
2681 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); | |||
2682 | } | |||
2683 | } | |||
2684 | ||||
2685 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { | |||
2686 | // C++11 [dcl.align]p6: | |||
2687 | // if any declaration of an entity has an alignment-specifier, | |||
2688 | // every defining declaration of that entity shall specify an | |||
2689 | // equivalent alignment. | |||
2690 | // C11 6.7.5/7: | |||
2691 | // If the definition of an object does not have an alignment | |||
2692 | // specifier, any other declaration of that object shall also | |||
2693 | // have no alignment specifier. | |||
2694 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) | |||
2695 | << OldAlignasAttr; | |||
2696 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) | |||
2697 | << OldAlignasAttr; | |||
2698 | } | |||
2699 | ||||
2700 | bool AnyAdded = false; | |||
2701 | ||||
2702 | // Ensure we have an attribute representing the strictest alignment. | |||
2703 | if (OldAlign > NewAlign) { | |||
2704 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); | |||
2705 | Clone->setInherited(true); | |||
2706 | New->addAttr(Clone); | |||
2707 | AnyAdded = true; | |||
2708 | } | |||
2709 | ||||
2710 | // Ensure we have an alignas attribute if the old declaration had one. | |||
2711 | if (OldAlignasAttr && !NewAlignasAttr && | |||
2712 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { | |||
2713 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); | |||
2714 | Clone->setInherited(true); | |||
2715 | New->addAttr(Clone); | |||
2716 | AnyAdded = true; | |||
2717 | } | |||
2718 | ||||
2719 | return AnyAdded; | |||
2720 | } | |||
2721 | ||||
2722 | #define WANT_DECL_MERGE_LOGIC | |||
2723 | #include "clang/Sema/AttrParsedAttrImpl.inc" | |||
2724 | #undef WANT_DECL_MERGE_LOGIC | |||
2725 | ||||
2726 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, | |||
2727 | const InheritableAttr *Attr, | |||
2728 | Sema::AvailabilityMergeKind AMK) { | |||
2729 | // Diagnose any mutual exclusions between the attribute that we want to add | |||
2730 | // and attributes that already exist on the declaration. | |||
2731 | if (!DiagnoseMutualExclusions(S, D, Attr)) | |||
2732 | return false; | |||
2733 | ||||
2734 | // This function copies an attribute Attr from a previous declaration to the | |||
2735 | // new declaration D if the new declaration doesn't itself have that attribute | |||
2736 | // yet or if that attribute allows duplicates. | |||
2737 | // If you're adding a new attribute that requires logic different from | |||
2738 | // "use explicit attribute on decl if present, else use attribute from | |||
2739 | // previous decl", for example if the attribute needs to be consistent | |||
2740 | // between redeclarations, you need to call a custom merge function here. | |||
2741 | InheritableAttr *NewAttr = nullptr; | |||
2742 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) | |||
2743 | NewAttr = S.mergeAvailabilityAttr( | |||
2744 | D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), | |||
2745 | AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), | |||
2746 | AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, | |||
2747 | AA->getPriority()); | |||
2748 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) | |||
2749 | NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); | |||
2750 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) | |||
2751 | NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); | |||
2752 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) | |||
2753 | NewAttr = S.mergeDLLImportAttr(D, *ImportA); | |||
2754 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) | |||
2755 | NewAttr = S.mergeDLLExportAttr(D, *ExportA); | |||
2756 | else if (const auto *EA = dyn_cast<ErrorAttr>(Attr)) | |||
2757 | NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic()); | |||
2758 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) | |||
2759 | NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), | |||
2760 | FA->getFirstArg()); | |||
2761 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) | |||
2762 | NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); | |||
2763 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) | |||
2764 | NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); | |||
2765 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) | |||
2766 | NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), | |||
2767 | IA->getInheritanceModel()); | |||
2768 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) | |||
2769 | NewAttr = S.mergeAlwaysInlineAttr(D, *AA, | |||
2770 | &S.Context.Idents.get(AA->getSpelling())); | |||
2771 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && | |||
2772 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || | |||
2773 | isa<CUDAGlobalAttr>(Attr))) { | |||
2774 | // CUDA target attributes are part of function signature for | |||
2775 | // overloading purposes and must not be merged. | |||
2776 | return false; | |||
2777 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) | |||
2778 | NewAttr = S.mergeMinSizeAttr(D, *MA); | |||
2779 | else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) | |||
2780 | NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); | |||
2781 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) | |||
2782 | NewAttr = S.mergeOptimizeNoneAttr(D, *OA); | |||
2783 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) | |||
2784 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); | |||
2785 | else if (isa<AlignedAttr>(Attr)) | |||
2786 | // AlignedAttrs are handled separately, because we need to handle all | |||
2787 | // such attributes on a declaration at the same time. | |||
2788 | NewAttr = nullptr; | |||
2789 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && | |||
2790 | (AMK == Sema::AMK_Override || | |||
2791 | AMK == Sema::AMK_ProtocolImplementation || | |||
2792 | AMK == Sema::AMK_OptionalProtocolImplementation)) | |||
2793 | NewAttr = nullptr; | |||
2794 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) | |||
2795 | NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); | |||
2796 | else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) | |||
2797 | NewAttr = S.mergeImportModuleAttr(D, *IMA); | |||
2798 | else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) | |||
2799 | NewAttr = S.mergeImportNameAttr(D, *INA); | |||
2800 | else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr)) | |||
2801 | NewAttr = S.mergeEnforceTCBAttr(D, *TCBA); | |||
2802 | else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr)) | |||
2803 | NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA); | |||
2804 | else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr)) | |||
2805 | NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA); | |||
2806 | else if (const auto *NT = dyn_cast<HLSLNumThreadsAttr>(Attr)) | |||
2807 | NewAttr = | |||
2808 | S.mergeHLSLNumThreadsAttr(D, *NT, NT->getX(), NT->getY(), NT->getZ()); | |||
2809 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) | |||
2810 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); | |||
2811 | ||||
2812 | if (NewAttr) { | |||
2813 | NewAttr->setInherited(true); | |||
2814 | D->addAttr(NewAttr); | |||
2815 | if (isa<MSInheritanceAttr>(NewAttr)) | |||
2816 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); | |||
2817 | return true; | |||
2818 | } | |||
2819 | ||||
2820 | return false; | |||
2821 | } | |||
2822 | ||||
2823 | static const NamedDecl *getDefinition(const Decl *D) { | |||
2824 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) | |||
2825 | return TD->getDefinition(); | |||
2826 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | |||
2827 | const VarDecl *Def = VD->getDefinition(); | |||
2828 | if (Def) | |||
2829 | return Def; | |||
2830 | return VD->getActingDefinition(); | |||
2831 | } | |||
2832 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | |||
2833 | const FunctionDecl *Def = nullptr; | |||
2834 | if (FD->isDefined(Def, true)) | |||
2835 | return Def; | |||
2836 | } | |||
2837 | return nullptr; | |||
2838 | } | |||
2839 | ||||
2840 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { | |||
2841 | for (const auto *Attribute : D->attrs()) | |||
2842 | if (Attribute->getKind() == Kind) | |||
2843 | return true; | |||
2844 | return false; | |||
2845 | } | |||
2846 | ||||
2847 | /// checkNewAttributesAfterDef - If we already have a definition, check that | |||
2848 | /// there are no new attributes in this declaration. | |||
2849 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { | |||
2850 | if (!New->hasAttrs()) | |||
2851 | return; | |||
2852 | ||||
2853 | const NamedDecl *Def = getDefinition(Old); | |||
2854 | if (!Def || Def == New) | |||
2855 | return; | |||
2856 | ||||
2857 | AttrVec &NewAttributes = New->getAttrs(); | |||
2858 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { | |||
2859 | const Attr *NewAttribute = NewAttributes[I]; | |||
2860 | ||||
2861 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { | |||
2862 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { | |||
2863 | Sema::SkipBodyInfo SkipBody; | |||
2864 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); | |||
2865 | ||||
2866 | // If we're skipping this definition, drop the "alias" attribute. | |||
2867 | if (SkipBody.ShouldSkip) { | |||
2868 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2869 | --E; | |||
2870 | continue; | |||
2871 | } | |||
2872 | } else { | |||
2873 | VarDecl *VD = cast<VarDecl>(New); | |||
2874 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == | |||
2875 | VarDecl::TentativeDefinition | |||
2876 | ? diag::err_alias_after_tentative | |||
2877 | : diag::err_redefinition; | |||
2878 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); | |||
2879 | if (Diag == diag::err_redefinition) | |||
2880 | S.notePreviousDefinition(Def, VD->getLocation()); | |||
2881 | else | |||
2882 | S.Diag(Def->getLocation(), diag::note_previous_definition); | |||
2883 | VD->setInvalidDecl(); | |||
2884 | } | |||
2885 | ++I; | |||
2886 | continue; | |||
2887 | } | |||
2888 | ||||
2889 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { | |||
2890 | // Tentative definitions are only interesting for the alias check above. | |||
2891 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { | |||
2892 | ++I; | |||
2893 | continue; | |||
2894 | } | |||
2895 | } | |||
2896 | ||||
2897 | if (hasAttribute(Def, NewAttribute->getKind())) { | |||
2898 | ++I; | |||
2899 | continue; // regular attr merging will take care of validating this. | |||
2900 | } | |||
2901 | ||||
2902 | if (isa<C11NoReturnAttr>(NewAttribute)) { | |||
2903 | // C's _Noreturn is allowed to be added to a function after it is defined. | |||
2904 | ++I; | |||
2905 | continue; | |||
2906 | } else if (isa<UuidAttr>(NewAttribute)) { | |||
2907 | // msvc will allow a subsequent definition to add an uuid to a class | |||
2908 | ++I; | |||
2909 | continue; | |||
2910 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { | |||
2911 | if (AA->isAlignas()) { | |||
2912 | // C++11 [dcl.align]p6: | |||
2913 | // if any declaration of an entity has an alignment-specifier, | |||
2914 | // every defining declaration of that entity shall specify an | |||
2915 | // equivalent alignment. | |||
2916 | // C11 6.7.5/7: | |||
2917 | // If the definition of an object does not have an alignment | |||
2918 | // specifier, any other declaration of that object shall also | |||
2919 | // have no alignment specifier. | |||
2920 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) | |||
2921 | << AA; | |||
2922 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) | |||
2923 | << AA; | |||
2924 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2925 | --E; | |||
2926 | continue; | |||
2927 | } | |||
2928 | } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { | |||
2929 | // If there is a C definition followed by a redeclaration with this | |||
2930 | // attribute then there are two different definitions. In C++, prefer the | |||
2931 | // standard diagnostics. | |||
2932 | if (!S.getLangOpts().CPlusPlus) { | |||
2933 | S.Diag(NewAttribute->getLocation(), | |||
2934 | diag::err_loader_uninitialized_redeclaration); | |||
2935 | S.Diag(Def->getLocation(), diag::note_previous_definition); | |||
2936 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2937 | --E; | |||
2938 | continue; | |||
2939 | } | |||
2940 | } else if (isa<SelectAnyAttr>(NewAttribute) && | |||
2941 | cast<VarDecl>(New)->isInline() && | |||
2942 | !cast<VarDecl>(New)->isInlineSpecified()) { | |||
2943 | // Don't warn about applying selectany to implicitly inline variables. | |||
2944 | // Older compilers and language modes would require the use of selectany | |||
2945 | // to make such variables inline, and it would have no effect if we | |||
2946 | // honored it. | |||
2947 | ++I; | |||
2948 | continue; | |||
2949 | } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { | |||
2950 | // We allow to add OMP[Begin]DeclareVariantAttr to be added to | |||
2951 | // declarations after defintions. | |||
2952 | ++I; | |||
2953 | continue; | |||
2954 | } | |||
2955 | ||||
2956 | S.Diag(NewAttribute->getLocation(), | |||
2957 | diag::warn_attribute_precede_definition); | |||
2958 | S.Diag(Def->getLocation(), diag::note_previous_definition); | |||
2959 | NewAttributes.erase(NewAttributes.begin() + I); | |||
2960 | --E; | |||
2961 | } | |||
2962 | } | |||
2963 | ||||
2964 | static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, | |||
2965 | const ConstInitAttr *CIAttr, | |||
2966 | bool AttrBeforeInit) { | |||
2967 | SourceLocation InsertLoc = InitDecl->getInnerLocStart(); | |||
2968 | ||||
2969 | // Figure out a good way to write this specifier on the old declaration. | |||
2970 | // FIXME: We should just use the spelling of CIAttr, but we don't preserve | |||
2971 | // enough of the attribute list spelling information to extract that without | |||
2972 | // heroics. | |||
2973 | std::string SuitableSpelling; | |||
2974 | if (S.getLangOpts().CPlusPlus20) | |||
2975 | SuitableSpelling = std::string( | |||
2976 | S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); | |||
2977 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | |||
2978 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( | |||
2979 | InsertLoc, {tok::l_square, tok::l_square, | |||
2980 | S.PP.getIdentifierInfo("clang"), tok::coloncolon, | |||
2981 | S.PP.getIdentifierInfo("require_constant_initialization"), | |||
2982 | tok::r_square, tok::r_square})); | |||
2983 | if (SuitableSpelling.empty()) | |||
2984 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( | |||
2985 | InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, | |||
2986 | S.PP.getIdentifierInfo("require_constant_initialization"), | |||
2987 | tok::r_paren, tok::r_paren})); | |||
2988 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) | |||
2989 | SuitableSpelling = "constinit"; | |||
2990 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | |||
2991 | SuitableSpelling = "[[clang::require_constant_initialization]]"; | |||
2992 | if (SuitableSpelling.empty()) | |||
2993 | SuitableSpelling = "__attribute__((require_constant_initialization))"; | |||
2994 | SuitableSpelling += " "; | |||
2995 | ||||
2996 | if (AttrBeforeInit) { | |||
2997 | // extern constinit int a; | |||
2998 | // int a = 0; // error (missing 'constinit'), accepted as extension | |||
2999 | assert(CIAttr->isConstinit() && "should not diagnose this for attribute")(static_cast <bool> (CIAttr->isConstinit() && "should not diagnose this for attribute") ? void (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\"" , "clang/lib/Sema/SemaDecl.cpp", 2999, __extension__ __PRETTY_FUNCTION__ )); | |||
3000 | S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) | |||
3001 | << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | |||
3002 | S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); | |||
3003 | } else { | |||
3004 | // int a = 0; | |||
3005 | // constinit extern int a; // error (missing 'constinit') | |||
3006 | S.Diag(CIAttr->getLocation(), | |||
3007 | CIAttr->isConstinit() ? diag::err_constinit_added_too_late | |||
3008 | : diag::warn_require_const_init_added_too_late) | |||
3009 | << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); | |||
3010 | S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) | |||
3011 | << CIAttr->isConstinit() | |||
3012 | << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | |||
3013 | } | |||
3014 | } | |||
3015 | ||||
3016 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. | |||
3017 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, | |||
3018 | AvailabilityMergeKind AMK) { | |||
3019 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { | |||
3020 | UsedAttr *NewAttr = OldAttr->clone(Context); | |||
3021 | NewAttr->setInherited(true); | |||
3022 | New->addAttr(NewAttr); | |||
3023 | } | |||
3024 | if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) { | |||
3025 | RetainAttr *NewAttr = OldAttr->clone(Context); | |||
3026 | NewAttr->setInherited(true); | |||
3027 | New->addAttr(NewAttr); | |||
3028 | } | |||
3029 | ||||
3030 | if (!Old->hasAttrs() && !New->hasAttrs()) | |||
3031 | return; | |||
3032 | ||||
3033 | // [dcl.constinit]p1: | |||
3034 | // If the [constinit] specifier is applied to any declaration of a | |||
3035 | // variable, it shall be applied to the initializing declaration. | |||
3036 | const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); | |||
3037 | const auto *NewConstInit = New->getAttr<ConstInitAttr>(); | |||
3038 | if (bool(OldConstInit) != bool(NewConstInit)) { | |||
3039 | const auto *OldVD = cast<VarDecl>(Old); | |||
3040 | auto *NewVD = cast<VarDecl>(New); | |||
3041 | ||||
3042 | // Find the initializing declaration. Note that we might not have linked | |||
3043 | // the new declaration into the redeclaration chain yet. | |||
3044 | const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); | |||
3045 | if (!InitDecl && | |||
3046 | (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) | |||
3047 | InitDecl = NewVD; | |||
3048 | ||||
3049 | if (InitDecl == NewVD) { | |||
3050 | // This is the initializing declaration. If it would inherit 'constinit', | |||
3051 | // that's ill-formed. (Note that we do not apply this to the attribute | |||
3052 | // form). | |||
3053 | if (OldConstInit && OldConstInit->isConstinit()) | |||
3054 | diagnoseMissingConstinit(*this, NewVD, OldConstInit, | |||
3055 | /*AttrBeforeInit=*/true); | |||
3056 | } else if (NewConstInit) { | |||
3057 | // This is the first time we've been told that this declaration should | |||
3058 | // have a constant initializer. If we already saw the initializing | |||
3059 | // declaration, this is too late. | |||
3060 | if (InitDecl && InitDecl != NewVD) { | |||
3061 | diagnoseMissingConstinit(*this, InitDecl, NewConstInit, | |||
3062 | /*AttrBeforeInit=*/false); | |||
3063 | NewVD->dropAttr<ConstInitAttr>(); | |||
3064 | } | |||
3065 | } | |||
3066 | } | |||
3067 | ||||
3068 | // Attributes declared post-definition are currently ignored. | |||
3069 | checkNewAttributesAfterDef(*this, New, Old); | |||
3070 | ||||
3071 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { | |||
3072 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { | |||
3073 | if (!OldA->isEquivalent(NewA)) { | |||
3074 | // This redeclaration changes __asm__ label. | |||
3075 | Diag(New->getLocation(), diag::err_different_asm_label); | |||
3076 | Diag(OldA->getLocation(), diag::note_previous_declaration); | |||
3077 | } | |||
3078 | } else if (Old->isUsed()) { | |||
3079 | // This redeclaration adds an __asm__ label to a declaration that has | |||
3080 | // already been ODR-used. | |||
3081 | Diag(New->getLocation(), diag::err_late_asm_label_name) | |||
3082 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); | |||
3083 | } | |||
3084 | } | |||
3085 | ||||
3086 | // Re-declaration cannot add abi_tag's. | |||
3087 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { | |||
3088 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { | |||
3089 | for (const auto &NewTag : NewAbiTagAttr->tags()) { | |||
3090 | if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) { | |||
3091 | Diag(NewAbiTagAttr->getLocation(), | |||
3092 | diag::err_new_abi_tag_on_redeclaration) | |||
3093 | << NewTag; | |||
3094 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); | |||
3095 | } | |||
3096 | } | |||
3097 | } else { | |||
3098 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); | |||
3099 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
3100 | } | |||
3101 | } | |||
3102 | ||||
3103 | // This redeclaration adds a section attribute. | |||
3104 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { | |||
3105 | if (auto *VD = dyn_cast<VarDecl>(New)) { | |||
3106 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { | |||
3107 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); | |||
3108 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
3109 | } | |||
3110 | } | |||
3111 | } | |||
3112 | ||||
3113 | // Redeclaration adds code-seg attribute. | |||
3114 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | |||
3115 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && | |||
3116 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { | |||
3117 | Diag(New->getLocation(), diag::warn_mismatched_section) | |||
3118 | << 0 /*codeseg*/; | |||
3119 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
3120 | } | |||
3121 | ||||
3122 | if (!Old->hasAttrs()) | |||
3123 | return; | |||
3124 | ||||
3125 | bool foundAny = New->hasAttrs(); | |||
3126 | ||||
3127 | // Ensure that any moving of objects within the allocated map is done before | |||
3128 | // we process them. | |||
3129 | if (!foundAny) New->setAttrs(AttrVec()); | |||
3130 | ||||
3131 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { | |||
3132 | // Ignore deprecated/unavailable/availability attributes if requested. | |||
3133 | AvailabilityMergeKind LocalAMK = AMK_None; | |||
3134 | if (isa<DeprecatedAttr>(I) || | |||
3135 | isa<UnavailableAttr>(I) || | |||
3136 | isa<AvailabilityAttr>(I)) { | |||
3137 | switch (AMK) { | |||
3138 | case AMK_None: | |||
3139 | continue; | |||
3140 | ||||
3141 | case AMK_Redeclaration: | |||
3142 | case AMK_Override: | |||
3143 | case AMK_ProtocolImplementation: | |||
3144 | case AMK_OptionalProtocolImplementation: | |||
3145 | LocalAMK = AMK; | |||
3146 | break; | |||
3147 | } | |||
3148 | } | |||
3149 | ||||
3150 | // Already handled. | |||
3151 | if (isa<UsedAttr>(I) || isa<RetainAttr>(I)) | |||
3152 | continue; | |||
3153 | ||||
3154 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) | |||
3155 | foundAny = true; | |||
3156 | } | |||
3157 | ||||
3158 | if (mergeAlignedAttrs(*this, New, Old)) | |||
3159 | foundAny = true; | |||
3160 | ||||
3161 | if (!foundAny) New->dropAttrs(); | |||
3162 | } | |||
3163 | ||||
3164 | /// mergeParamDeclAttributes - Copy attributes from the old parameter | |||
3165 | /// to the new one. | |||
3166 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, | |||
3167 | const ParmVarDecl *oldDecl, | |||
3168 | Sema &S) { | |||
3169 | // C++11 [dcl.attr.depend]p2: | |||
3170 | // The first declaration of a function shall specify the | |||
3171 | // carries_dependency attribute for its declarator-id if any declaration | |||
3172 | // of the function specifies the carries_dependency attribute. | |||
3173 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); | |||
3174 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { | |||
3175 | S.Diag(CDA->getLocation(), | |||
3176 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; | |||
3177 | // Find the first declaration of the parameter. | |||
3178 | // FIXME: Should we build redeclaration chains for function parameters? | |||
3179 | const FunctionDecl *FirstFD = | |||
3180 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); | |||
3181 | const ParmVarDecl *FirstVD = | |||
3182 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); | |||
3183 | S.Diag(FirstVD->getLocation(), | |||
3184 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; | |||
3185 | } | |||
3186 | ||||
3187 | if (!oldDecl->hasAttrs()) | |||
3188 | return; | |||
3189 | ||||
3190 | bool foundAny = newDecl->hasAttrs(); | |||
3191 | ||||
3192 | // Ensure that any moving of objects within the allocated map is | |||
3193 | // done before we process them. | |||
3194 | if (!foundAny) newDecl->setAttrs(AttrVec()); | |||
3195 | ||||
3196 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { | |||
3197 | if (!DeclHasAttr(newDecl, I)) { | |||
3198 | InheritableAttr *newAttr = | |||
3199 | cast<InheritableParamAttr>(I->clone(S.Context)); | |||
3200 | newAttr->setInherited(true); | |||
3201 | newDecl->addAttr(newAttr); | |||
3202 | foundAny = true; | |||
3203 | } | |||
3204 | } | |||
3205 | ||||
3206 | if (!foundAny) newDecl->dropAttrs(); | |||
3207 | } | |||
3208 | ||||
3209 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, | |||
3210 | const ParmVarDecl *OldParam, | |||
3211 | Sema &S) { | |||
3212 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { | |||
3213 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { | |||
3214 | if (*Oldnullability != *Newnullability) { | |||
3215 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) | |||
3216 | << DiagNullabilityKind( | |||
3217 | *Newnullability, | |||
3218 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | |||
3219 | != 0)) | |||
3220 | << DiagNullabilityKind( | |||
3221 | *Oldnullability, | |||
3222 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | |||
3223 | != 0)); | |||
3224 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); | |||
3225 | } | |||
3226 | } else { | |||
3227 | QualType NewT = NewParam->getType(); | |||
3228 | NewT = S.Context.getAttributedType( | |||
3229 | AttributedType::getNullabilityAttrKind(*Oldnullability), | |||
3230 | NewT, NewT); | |||
3231 | NewParam->setType(NewT); | |||
3232 | } | |||
3233 | } | |||
3234 | } | |||
3235 | ||||
3236 | namespace { | |||
3237 | ||||
3238 | /// Used in MergeFunctionDecl to keep track of function parameters in | |||
3239 | /// C. | |||
3240 | struct GNUCompatibleParamWarning { | |||
3241 | ParmVarDecl *OldParm; | |||
3242 | ParmVarDecl *NewParm; | |||
3243 | QualType PromotedType; | |||
3244 | }; | |||
3245 | ||||
3246 | } // end anonymous namespace | |||
3247 | ||||
3248 | // Determine whether the previous declaration was a definition, implicit | |||
3249 | // declaration, or a declaration. | |||
3250 | template <typename T> | |||
3251 | static std::pair<diag::kind, SourceLocation> | |||
3252 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { | |||
3253 | diag::kind PrevDiag; | |||
3254 | SourceLocation OldLocation = Old->getLocation(); | |||
3255 | if (Old->isThisDeclarationADefinition()) | |||
3256 | PrevDiag = diag::note_previous_definition; | |||
3257 | else if (Old->isImplicit()) { | |||
3258 | PrevDiag = diag::note_previous_implicit_declaration; | |||
3259 | if (const auto *FD = dyn_cast<FunctionDecl>(Old)) { | |||
3260 | if (FD->getBuiltinID()) | |||
3261 | PrevDiag = diag::note_previous_builtin_declaration; | |||
3262 | } | |||
3263 | if (OldLocation.isInvalid()) | |||
3264 | OldLocation = New->getLocation(); | |||
3265 | } else | |||
3266 | PrevDiag = diag::note_previous_declaration; | |||
3267 | return std::make_pair(PrevDiag, OldLocation); | |||
3268 | } | |||
3269 | ||||
3270 | /// canRedefineFunction - checks if a function can be redefined. Currently, | |||
3271 | /// only extern inline functions can be redefined, and even then only in | |||
3272 | /// GNU89 mode. | |||
3273 | static bool canRedefineFunction(const FunctionDecl *FD, | |||
3274 | const LangOptions& LangOpts) { | |||
3275 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && | |||
3276 | !LangOpts.CPlusPlus && | |||
3277 | FD->isInlineSpecified() && | |||
3278 | FD->getStorageClass() == SC_Extern); | |||
3279 | } | |||
3280 | ||||
3281 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { | |||
3282 | const AttributedType *AT = T->getAs<AttributedType>(); | |||
3283 | while (AT && !AT->isCallingConv()) | |||
3284 | AT = AT->getModifiedType()->getAs<AttributedType>(); | |||
3285 | return AT; | |||
3286 | } | |||
3287 | ||||
3288 | template <typename T> | |||
3289 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { | |||
3290 | const DeclContext *DC = Old->getDeclContext(); | |||
3291 | if (DC->isRecord()) | |||
3292 | return false; | |||
3293 | ||||
3294 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); | |||
3295 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) | |||
3296 | return true; | |||
3297 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) | |||
3298 | return true; | |||
3299 | return false; | |||
3300 | } | |||
3301 | ||||
3302 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } | |||
3303 | static bool isExternC(VarTemplateDecl *) { return false; } | |||
3304 | static bool isExternC(FunctionTemplateDecl *) { return false; } | |||
3305 | ||||
3306 | /// Check whether a redeclaration of an entity introduced by a | |||
3307 | /// using-declaration is valid, given that we know it's not an overload | |||
3308 | /// (nor a hidden tag declaration). | |||
3309 | template<typename ExpectedDecl> | |||
3310 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, | |||
3311 | ExpectedDecl *New) { | |||
3312 | // C++11 [basic.scope.declarative]p4: | |||
3313 | // Given a set of declarations in a single declarative region, each of | |||
3314 | // which specifies the same unqualified name, | |||
3315 | // -- they shall all refer to the same entity, or all refer to functions | |||
3316 | // and function templates; or | |||
3317 | // -- exactly one declaration shall declare a class name or enumeration | |||
3318 | // name that is not a typedef name and the other declarations shall all | |||
3319 | // refer to the same variable or enumerator, or all refer to functions | |||
3320 | // and function templates; in this case the class name or enumeration | |||
3321 | // name is hidden (3.3.10). | |||
3322 | ||||
3323 | // C++11 [namespace.udecl]p14: | |||
3324 | // If a function declaration in namespace scope or block scope has the | |||
3325 | // same name and the same parameter-type-list as a function introduced | |||
3326 | // by a using-declaration, and the declarations do not declare the same | |||
3327 | // function, the program is ill-formed. | |||
3328 | ||||
3329 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); | |||
3330 | if (Old && | |||
3331 | !Old->getDeclContext()->getRedeclContext()->Equals( | |||
3332 | New->getDeclContext()->getRedeclContext()) && | |||
3333 | !(isExternC(Old) && isExternC(New))) | |||
3334 | Old = nullptr; | |||
3335 | ||||
3336 | if (!Old) { | |||
3337 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); | |||
3338 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); | |||
3339 | S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0; | |||
3340 | return true; | |||
3341 | } | |||
3342 | return false; | |||
3343 | } | |||
3344 | ||||
3345 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, | |||
3346 | const FunctionDecl *B) { | |||
3347 | assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams ()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "clang/lib/Sema/SemaDecl.cpp", 3347, __extension__ __PRETTY_FUNCTION__ )); | |||
3348 | ||||
3349 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { | |||
3350 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); | |||
3351 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); | |||
3352 | if (AttrA == AttrB) | |||
3353 | return true; | |||
3354 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && | |||
3355 | AttrA->isDynamic() == AttrB->isDynamic(); | |||
3356 | }; | |||
3357 | ||||
3358 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); | |||
3359 | } | |||
3360 | ||||
3361 | /// If necessary, adjust the semantic declaration context for a qualified | |||
3362 | /// declaration to name the correct inline namespace within the qualifier. | |||
3363 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, | |||
3364 | DeclaratorDecl *OldD) { | |||
3365 | // The only case where we need to update the DeclContext is when | |||
3366 | // redeclaration lookup for a qualified name finds a declaration | |||
3367 | // in an inline namespace within the context named by the qualifier: | |||
3368 | // | |||
3369 | // inline namespace N { int f(); } | |||
3370 | // int ::f(); // Sema DC needs adjusting from :: to N::. | |||
3371 | // | |||
3372 | // For unqualified declarations, the semantic context *can* change | |||
3373 | // along the redeclaration chain (for local extern declarations, | |||
3374 | // extern "C" declarations, and friend declarations in particular). | |||
3375 | if (!NewD->getQualifier()) | |||
3376 | return; | |||
3377 | ||||
3378 | // NewD is probably already in the right context. | |||
3379 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); | |||
3380 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); | |||
3381 | if (NamedDC->Equals(SemaDC)) | |||
3382 | return; | |||
3383 | ||||
3384 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "clang/lib/Sema/SemaDecl.cpp", 3386, __extension__ __PRETTY_FUNCTION__ )) | |||
3385 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "clang/lib/Sema/SemaDecl.cpp", 3386, __extension__ __PRETTY_FUNCTION__ )) | |||
3386 | "unexpected context for redeclaration")(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf (SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl ()) && "unexpected context for redeclaration") ? void (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "clang/lib/Sema/SemaDecl.cpp", 3386, __extension__ __PRETTY_FUNCTION__ )); | |||
3387 | ||||
3388 | auto *LexDC = NewD->getLexicalDeclContext(); | |||
3389 | auto FixSemaDC = [=](NamedDecl *D) { | |||
3390 | if (!D) | |||
3391 | return; | |||
3392 | D->setDeclContext(SemaDC); | |||
3393 | D->setLexicalDeclContext(LexDC); | |||
3394 | }; | |||
3395 | ||||
3396 | FixSemaDC(NewD); | |||
3397 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) | |||
3398 | FixSemaDC(FD->getDescribedFunctionTemplate()); | |||
3399 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) | |||
3400 | FixSemaDC(VD->getDescribedVarTemplate()); | |||
3401 | } | |||
3402 | ||||
3403 | /// MergeFunctionDecl - We just parsed a function 'New' from | |||
3404 | /// declarator D which has the same name and scope as a previous | |||
3405 | /// declaration 'Old'. Figure out how to resolve this situation, | |||
3406 | /// merging decls or emitting diagnostics as appropriate. | |||
3407 | /// | |||
3408 | /// In C++, New and Old must be declarations that are not | |||
3409 | /// overloaded. Use IsOverload to determine whether New and Old are | |||
3410 | /// overloaded, and to select the Old declaration that New should be | |||
3411 | /// merged with. | |||
3412 | /// | |||
3413 | /// Returns true if there was an error, false otherwise. | |||
3414 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, Scope *S, | |||
3415 | bool MergeTypeWithOld, bool NewDeclIsDefn) { | |||
3416 | // Verify the old decl was also a function. | |||
3417 | FunctionDecl *Old = OldD->getAsFunction(); | |||
3418 | if (!Old) { | |||
3419 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { | |||
3420 | if (New->getFriendObjectKind()) { | |||
3421 | Diag(New->getLocation(), diag::err_using_decl_friend); | |||
3422 | Diag(Shadow->getTargetDecl()->getLocation(), | |||
3423 | diag::note_using_decl_target); | |||
3424 | Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) | |||
3425 | << 0; | |||
3426 | return true; | |||
3427 | } | |||
3428 | ||||
3429 | // Check whether the two declarations might declare the same function or | |||
3430 | // function template. | |||
3431 | if (FunctionTemplateDecl *NewTemplate = | |||
3432 | New->getDescribedFunctionTemplate()) { | |||
3433 | if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow, | |||
3434 | NewTemplate)) | |||
3435 | return true; | |||
3436 | OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl()) | |||
3437 | ->getAsFunction(); | |||
3438 | } else { | |||
3439 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) | |||
3440 | return true; | |||
3441 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); | |||
3442 | } | |||
3443 | } else { | |||
3444 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
3445 | << New->getDeclName(); | |||
3446 | notePreviousDefinition(OldD, New->getLocation()); | |||
3447 | return true; | |||
3448 | } | |||
3449 | } | |||
3450 | ||||
3451 | // If the old declaration was found in an inline namespace and the new | |||
3452 | // declaration was qualified, update the DeclContext to match. | |||
3453 | adjustDeclContextForDeclaratorDecl(New, Old); | |||
3454 | ||||
3455 | // If the old declaration is invalid, just give up here. | |||
3456 | if (Old->isInvalidDecl()) | |||
3457 | return true; | |||
3458 | ||||
3459 | // Disallow redeclaration of some builtins. | |||
3460 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { | |||
3461 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); | |||
3462 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) | |||
3463 | << Old << Old->getType(); | |||
3464 | return true; | |||
3465 | } | |||
3466 | ||||
3467 | diag::kind PrevDiag; | |||
3468 | SourceLocation OldLocation; | |||
3469 | std::tie(PrevDiag, OldLocation) = | |||
3470 | getNoteDiagForInvalidRedeclaration(Old, New); | |||
3471 | ||||
3472 | // Don't complain about this if we're in GNU89 mode and the old function | |||
3473 | // is an extern inline function. | |||
3474 | // Don't complain about specializations. They are not supposed to have | |||
3475 | // storage classes. | |||
3476 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && | |||
3477 | New->getStorageClass() == SC_Static && | |||
3478 | Old->hasExternalFormalLinkage() && | |||
3479 | !New->getTemplateSpecializationInfo() && | |||
3480 | !canRedefineFunction(Old, getLangOpts())) { | |||
3481 | if (getLangOpts().MicrosoftExt) { | |||
3482 | Diag(New->getLocation(), diag::ext_static_non_static) << New; | |||
3483 | Diag(OldLocation, PrevDiag); | |||
3484 | } else { | |||
3485 | Diag(New->getLocation(), diag::err_static_non_static) << New; | |||
3486 | Diag(OldLocation, PrevDiag); | |||
3487 | return true; | |||
3488 | } | |||
3489 | } | |||
3490 | ||||
3491 | if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) | |||
3492 | if (!Old->hasAttr<InternalLinkageAttr>()) { | |||
3493 | Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) | |||
3494 | << ILA; | |||
3495 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
3496 | New->dropAttr<InternalLinkageAttr>(); | |||
3497 | } | |||
3498 | ||||
3499 | if (auto *EA = New->getAttr<ErrorAttr>()) { | |||
3500 | if (!Old->hasAttr<ErrorAttr>()) { | |||
3501 | Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA; | |||
3502 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
3503 | New->dropAttr<ErrorAttr>(); | |||
3504 | } | |||
3505 | } | |||
3506 | ||||
3507 | if (CheckRedeclarationInModule(New, Old)) | |||
3508 | return true; | |||
3509 | ||||
3510 | if (!getLangOpts().CPlusPlus) { | |||
3511 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); | |||
3512 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { | |||
3513 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) | |||
3514 | << New << OldOvl; | |||
3515 | ||||
3516 | // Try our best to find a decl that actually has the overloadable | |||
3517 | // attribute for the note. In most cases (e.g. programs with only one | |||
3518 | // broken declaration/definition), this won't matter. | |||
3519 | // | |||
3520 | // FIXME: We could do this if we juggled some extra state in | |||
3521 | // OverloadableAttr, rather than just removing it. | |||
3522 | const Decl *DiagOld = Old; | |||
3523 | if (OldOvl) { | |||
3524 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { | |||
3525 | const auto *A = D->getAttr<OverloadableAttr>(); | |||
3526 | return A && !A->isImplicit(); | |||
3527 | }); | |||
3528 | // If we've implicitly added *all* of the overloadable attrs to this | |||
3529 | // chain, emitting a "previous redecl" note is pointless. | |||
3530 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; | |||
3531 | } | |||
3532 | ||||
3533 | if (DiagOld) | |||
3534 | Diag(DiagOld->getLocation(), | |||
3535 | diag::note_attribute_overloadable_prev_overload) | |||
3536 | << OldOvl; | |||
3537 | ||||
3538 | if (OldOvl) | |||
3539 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); | |||
3540 | else | |||
3541 | New->dropAttr<OverloadableAttr>(); | |||
3542 | } | |||
3543 | } | |||
3544 | ||||
3545 | // If a function is first declared with a calling convention, but is later | |||
3546 | // declared or defined without one, all following decls assume the calling | |||
3547 | // convention of the first. | |||
3548 | // | |||
3549 | // It's OK if a function is first declared without a calling convention, | |||
3550 | // but is later declared or defined with the default calling convention. | |||
3551 | // | |||
3552 | // To test if either decl has an explicit calling convention, we look for | |||
3553 | // AttributedType sugar nodes on the type as written. If they are missing or | |||
3554 | // were canonicalized away, we assume the calling convention was implicit. | |||
3555 | // | |||
3556 | // Note also that we DO NOT return at this point, because we still have | |||
3557 | // other tests to run. | |||
3558 | QualType OldQType = Context.getCanonicalType(Old->getType()); | |||
3559 | QualType NewQType = Context.getCanonicalType(New->getType()); | |||
3560 | const FunctionType *OldType = cast<FunctionType>(OldQType); | |||
3561 | const FunctionType *NewType = cast<FunctionType>(NewQType); | |||
3562 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | |||
3563 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | |||
3564 | bool RequiresAdjustment = false; | |||
3565 | ||||
3566 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { | |||
3567 | FunctionDecl *First = Old->getFirstDecl(); | |||
3568 | const FunctionType *FT = | |||
3569 | First->getType().getCanonicalType()->castAs<FunctionType>(); | |||
3570 | FunctionType::ExtInfo FI = FT->getExtInfo(); | |||
3571 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); | |||
3572 | if (!NewCCExplicit) { | |||
3573 | // Inherit the CC from the previous declaration if it was specified | |||
3574 | // there but not here. | |||
3575 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | |||
3576 | RequiresAdjustment = true; | |||
3577 | } else if (Old->getBuiltinID()) { | |||
3578 | // Builtin attribute isn't propagated to the new one yet at this point, | |||
3579 | // so we check if the old one is a builtin. | |||
3580 | ||||
3581 | // Calling Conventions on a Builtin aren't really useful and setting a | |||
3582 | // default calling convention and cdecl'ing some builtin redeclarations is | |||
3583 | // common, so warn and ignore the calling convention on the redeclaration. | |||
3584 | Diag(New->getLocation(), diag::warn_cconv_unsupported) | |||
3585 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | |||
3586 | << (int)CallingConventionIgnoredReason::BuiltinFunction; | |||
3587 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | |||
3588 | RequiresAdjustment = true; | |||
3589 | } else { | |||
3590 | // Calling conventions aren't compatible, so complain. | |||
3591 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); | |||
3592 | Diag(New->getLocation(), diag::err_cconv_change) | |||
3593 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | |||
3594 | << !FirstCCExplicit | |||
3595 | << (!FirstCCExplicit ? "" : | |||
3596 | FunctionType::getNameForCallConv(FI.getCC())); | |||
3597 | ||||
3598 | // Put the note on the first decl, since it is the one that matters. | |||
3599 | Diag(First->getLocation(), diag::note_previous_declaration); | |||
3600 | return true; | |||
3601 | } | |||
3602 | } | |||
3603 | ||||
3604 | // FIXME: diagnose the other way around? | |||
3605 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { | |||
3606 | NewTypeInfo = NewTypeInfo.withNoReturn(true); | |||
3607 | RequiresAdjustment = true; | |||
3608 | } | |||
3609 | ||||
3610 | // Merge regparm attribute. | |||
3611 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || | |||
3612 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { | |||
3613 | if (NewTypeInfo.getHasRegParm()) { | |||
3614 | Diag(New->getLocation(), diag::err_regparm_mismatch) | |||
3615 | << NewType->getRegParmType() | |||
3616 | << OldType->getRegParmType(); | |||
3617 | Diag(OldLocation, diag::note_previous_declaration); | |||
3618 | return true; | |||
3619 | } | |||
3620 | ||||
3621 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); | |||
3622 | RequiresAdjustment = true; | |||
3623 | } | |||
3624 | ||||
3625 | // Merge ns_returns_retained attribute. | |||
3626 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { | |||
3627 | if (NewTypeInfo.getProducesResult()) { | |||
3628 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) | |||
3629 | << "'ns_returns_retained'"; | |||
3630 | Diag(OldLocation, diag::note_previous_declaration); | |||
3631 | return true; | |||
3632 | } | |||
3633 | ||||
3634 | NewTypeInfo = NewTypeInfo.withProducesResult(true); | |||
3635 | RequiresAdjustment = true; | |||
3636 | } | |||
3637 | ||||
3638 | if (OldTypeInfo.getNoCallerSavedRegs() != | |||
3639 | NewTypeInfo.getNoCallerSavedRegs()) { | |||
3640 | if (NewTypeInfo.getNoCallerSavedRegs()) { | |||
3641 | AnyX86NoCallerSavedRegistersAttr *Attr = | |||
3642 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); | |||
3643 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; | |||
3644 | Diag(OldLocation, diag::note_previous_declaration); | |||
3645 | return true; | |||
3646 | } | |||
3647 | ||||
3648 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); | |||
3649 | RequiresAdjustment = true; | |||
3650 | } | |||
3651 | ||||
3652 | if (RequiresAdjustment) { | |||
3653 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); | |||
3654 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); | |||
3655 | New->setType(QualType(AdjustedType, 0)); | |||
3656 | NewQType = Context.getCanonicalType(New->getType()); | |||
3657 | } | |||
3658 | ||||
3659 | // If this redeclaration makes the function inline, we may need to add it to | |||
3660 | // UndefinedButUsed. | |||
3661 | if (!Old->isInlined() && New->isInlined() && | |||
3662 | !New->hasAttr<GNUInlineAttr>() && | |||
3663 | !getLangOpts().GNUInline && | |||
3664 | Old->isUsed(false) && | |||
3665 | !Old->isDefined() && !New->isThisDeclarationADefinition()) | |||
3666 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | |||
3667 | SourceLocation())); | |||
3668 | ||||
3669 | // If this redeclaration makes it newly gnu_inline, we don't want to warn | |||
3670 | // about it. | |||
3671 | if (New->hasAttr<GNUInlineAttr>() && | |||
3672 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { | |||
3673 | UndefinedButUsed.erase(Old->getCanonicalDecl()); | |||
3674 | } | |||
3675 | ||||
3676 | // If pass_object_size params don't match up perfectly, this isn't a valid | |||
3677 | // redeclaration. | |||
3678 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && | |||
3679 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { | |||
3680 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) | |||
3681 | << New->getDeclName(); | |||
3682 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3683 | return true; | |||
3684 | } | |||
3685 | ||||
3686 | if (getLangOpts().CPlusPlus) { | |||
3687 | // C++1z [over.load]p2 | |||
3688 | // Certain function declarations cannot be overloaded: | |||
3689 | // -- Function declarations that differ only in the return type, | |||
3690 | // the exception specification, or both cannot be overloaded. | |||
3691 | ||||
3692 | // Check the exception specifications match. This may recompute the type of | |||
3693 | // both Old and New if it resolved exception specifications, so grab the | |||
3694 | // types again after this. Because this updates the type, we do this before | |||
3695 | // any of the other checks below, which may update the "de facto" NewQType | |||
3696 | // but do not necessarily update the type of New. | |||
3697 | if (CheckEquivalentExceptionSpec(Old, New)) | |||
3698 | return true; | |||
3699 | OldQType = Context.getCanonicalType(Old->getType()); | |||
3700 | NewQType = Context.getCanonicalType(New->getType()); | |||
3701 | ||||
3702 | // Go back to the type source info to compare the declared return types, | |||
3703 | // per C++1y [dcl.type.auto]p13: | |||
3704 | // Redeclarations or specializations of a function or function template | |||
3705 | // with a declared return type that uses a placeholder type shall also | |||
3706 | // use that placeholder, not a deduced type. | |||
3707 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); | |||
3708 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); | |||
3709 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && | |||
3710 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, | |||
3711 | OldDeclaredReturnType)) { | |||
3712 | QualType ResQT; | |||
3713 | if (NewDeclaredReturnType->isObjCObjectPointerType() && | |||
3714 | OldDeclaredReturnType->isObjCObjectPointerType()) | |||
3715 | // FIXME: This does the wrong thing for a deduced return type. | |||
3716 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); | |||
3717 | if (ResQT.isNull()) { | |||
3718 | if (New->isCXXClassMember() && New->isOutOfLine()) | |||
3719 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) | |||
3720 | << New << New->getReturnTypeSourceRange(); | |||
3721 | else | |||
3722 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) | |||
3723 | << New->getReturnTypeSourceRange(); | |||
3724 | Diag(OldLocation, PrevDiag) << Old << Old->getType() | |||
3725 | << Old->getReturnTypeSourceRange(); | |||
3726 | return true; | |||
3727 | } | |||
3728 | else | |||
3729 | NewQType = ResQT; | |||
3730 | } | |||
3731 | ||||
3732 | QualType OldReturnType = OldType->getReturnType(); | |||
3733 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); | |||
3734 | if (OldReturnType != NewReturnType) { | |||
3735 | // If this function has a deduced return type and has already been | |||
3736 | // defined, copy the deduced value from the old declaration. | |||
3737 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); | |||
3738 | if (OldAT && OldAT->isDeduced()) { | |||
3739 | QualType DT = OldAT->getDeducedType(); | |||
3740 | if (DT.isNull()) { | |||
3741 | New->setType(SubstAutoTypeDependent(New->getType())); | |||
3742 | NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType)); | |||
3743 | } else { | |||
3744 | New->setType(SubstAutoType(New->getType(), DT)); | |||
3745 | NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT)); | |||
3746 | } | |||
3747 | } | |||
3748 | } | |||
3749 | ||||
3750 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | |||
3751 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | |||
3752 | if (OldMethod && NewMethod) { | |||
3753 | // Preserve triviality. | |||
3754 | NewMethod->setTrivial(OldMethod->isTrivial()); | |||
3755 | ||||
3756 | // MSVC allows explicit template specialization at class scope: | |||
3757 | // 2 CXXMethodDecls referring to the same function will be injected. | |||
3758 | // We don't want a redeclaration error. | |||
3759 | bool IsClassScopeExplicitSpecialization = | |||
3760 | OldMethod->isFunctionTemplateSpecialization() && | |||
3761 | NewMethod->isFunctionTemplateSpecialization(); | |||
3762 | bool isFriend = NewMethod->getFriendObjectKind(); | |||
3763 | ||||
3764 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && | |||
3765 | !IsClassScopeExplicitSpecialization) { | |||
3766 | // -- Member function declarations with the same name and the | |||
3767 | // same parameter types cannot be overloaded if any of them | |||
3768 | // is a static member function declaration. | |||
3769 | if (OldMethod->isStatic() != NewMethod->isStatic()) { | |||
3770 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); | |||
3771 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3772 | return true; | |||
3773 | } | |||
3774 | ||||
3775 | // C++ [class.mem]p1: | |||
3776 | // [...] A member shall not be declared twice in the | |||
3777 | // member-specification, except that a nested class or member | |||
3778 | // class template can be declared and then later defined. | |||
3779 | if (!inTemplateInstantiation()) { | |||
3780 | unsigned NewDiag; | |||
3781 | if (isa<CXXConstructorDecl>(OldMethod)) | |||
3782 | NewDiag = diag::err_constructor_redeclared; | |||
3783 | else if (isa<CXXDestructorDecl>(NewMethod)) | |||
3784 | NewDiag = diag::err_destructor_redeclared; | |||
3785 | else if (isa<CXXConversionDecl>(NewMethod)) | |||
3786 | NewDiag = diag::err_conv_function_redeclared; | |||
3787 | else | |||
3788 | NewDiag = diag::err_member_redeclared; | |||
3789 | ||||
3790 | Diag(New->getLocation(), NewDiag); | |||
3791 | } else { | |||
3792 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) | |||
3793 | << New << New->getType(); | |||
3794 | } | |||
3795 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
3796 | return true; | |||
3797 | ||||
3798 | // Complain if this is an explicit declaration of a special | |||
3799 | // member that was initially declared implicitly. | |||
3800 | // | |||
3801 | // As an exception, it's okay to befriend such methods in order | |||
3802 | // to permit the implicit constructor/destructor/operator calls. | |||
3803 | } else if (OldMethod->isImplicit()) { | |||
3804 | if (isFriend) { | |||
3805 | NewMethod->setImplicit(); | |||
3806 | } else { | |||
3807 | Diag(NewMethod->getLocation(), | |||
3808 | diag::err_definition_of_implicitly_declared_member) | |||
3809 | << New << getSpecialMember(OldMethod); | |||
3810 | return true; | |||
3811 | } | |||
3812 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { | |||
3813 | Diag(NewMethod->getLocation(), | |||
3814 | diag::err_definition_of_explicitly_defaulted_member) | |||
3815 | << getSpecialMember(OldMethod); | |||
3816 | return true; | |||
3817 | } | |||
3818 | } | |||
3819 | ||||
3820 | // C++11 [dcl.attr.noreturn]p1: | |||
3821 | // The first declaration of a function shall specify the noreturn | |||
3822 | // attribute if any declaration of that function specifies the noreturn | |||
3823 | // attribute. | |||
3824 | if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>()) | |||
3825 | if (!Old->hasAttr<CXX11NoReturnAttr>()) { | |||
3826 | Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl) | |||
3827 | << NRA; | |||
3828 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
3829 | } | |||
3830 | ||||
3831 | // C++11 [dcl.attr.depend]p2: | |||
3832 | // The first declaration of a function shall specify the | |||
3833 | // carries_dependency attribute for its declarator-id if any declaration | |||
3834 | // of the function specifies the carries_dependency attribute. | |||
3835 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); | |||
3836 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { | |||
3837 | Diag(CDA->getLocation(), | |||
3838 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; | |||
3839 | Diag(Old->getFirstDecl()->getLocation(), | |||
3840 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; | |||
3841 | } | |||
3842 | ||||
3843 | // (C++98 8.3.5p3): | |||
3844 | // All declarations for a function shall agree exactly in both the | |||
3845 | // return type and the parameter-type-list. | |||
3846 | // We also want to respect all the extended bits except noreturn. | |||
3847 | ||||
3848 | // noreturn should now match unless the old type info didn't have it. | |||
3849 | QualType OldQTypeForComparison = OldQType; | |||
3850 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { | |||
3851 | auto *OldType = OldQType->castAs<FunctionProtoType>(); | |||
3852 | const FunctionType *OldTypeForComparison | |||
3853 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); | |||
3854 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); | |||
3855 | assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical( )) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()" , "clang/lib/Sema/SemaDecl.cpp", 3855, __extension__ __PRETTY_FUNCTION__ )); | |||
3856 | } | |||
3857 | ||||
3858 | if (haveIncompatibleLanguageLinkages(Old, New)) { | |||
3859 | // As a special case, retain the language linkage from previous | |||
3860 | // declarations of a friend function as an extension. | |||
3861 | // | |||
3862 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC | |||
3863 | // and is useful because there's otherwise no way to specify language | |||
3864 | // linkage within class scope. | |||
3865 | // | |||
3866 | // Check cautiously as the friend object kind isn't yet complete. | |||
3867 | if (New->getFriendObjectKind() != Decl::FOK_None) { | |||
3868 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; | |||
3869 | Diag(OldLocation, PrevDiag); | |||
3870 | } else { | |||
3871 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | |||
3872 | Diag(OldLocation, PrevDiag); | |||
3873 | return true; | |||
3874 | } | |||
3875 | } | |||
3876 | ||||
3877 | // If the function types are compatible, merge the declarations. Ignore the | |||
3878 | // exception specifier because it was already checked above in | |||
3879 | // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics | |||
3880 | // about incompatible types under -fms-compatibility. | |||
3881 | if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, | |||
3882 | NewQType)) | |||
3883 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
3884 | ||||
3885 | // If the types are imprecise (due to dependent constructs in friends or | |||
3886 | // local extern declarations), it's OK if they differ. We'll check again | |||
3887 | // during instantiation. | |||
3888 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) | |||
3889 | return false; | |||
3890 | ||||
3891 | // Fall through for conflicting redeclarations and redefinitions. | |||
3892 | } | |||
3893 | ||||
3894 | // C: Function types need to be compatible, not identical. This handles | |||
3895 | // duplicate function decls like "void f(int); void f(enum X);" properly. | |||
3896 | if (!getLangOpts().CPlusPlus) { | |||
3897 | // C99 6.7.5.3p15: ...If one type has a parameter type list and the other | |||
3898 | // type is specified by a function definition that contains a (possibly | |||
3899 | // empty) identifier list, both shall agree in the number of parameters | |||
3900 | // and the type of each parameter shall be compatible with the type that | |||
3901 | // results from the application of default argument promotions to the | |||
3902 | // type of the corresponding identifier. ... | |||
3903 | // This cannot be handled by ASTContext::typesAreCompatible() because that | |||
3904 | // doesn't know whether the function type is for a definition or not when | |||
3905 | // eventually calling ASTContext::mergeFunctionTypes(). The only situation | |||
3906 | // we need to cover here is that the number of arguments agree as the | |||
3907 | // default argument promotion rules were already checked by | |||
3908 | // ASTContext::typesAreCompatible(). | |||
3909 | if (Old->hasPrototype() && !New->hasWrittenPrototype() && NewDeclIsDefn && | |||
3910 | Old->getNumParams() != New->getNumParams()) { | |||
3911 | Diag(New->getLocation(), diag::err_conflicting_types) << New; | |||
3912 | Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); | |||
3913 | return true; | |||
3914 | } | |||
3915 | ||||
3916 | // If we are merging two functions where only one of them has a prototype, | |||
3917 | // we may have enough information to decide to issue a diagnostic that the | |||
3918 | // function without a protoype will change behavior in C2x. This handles | |||
3919 | // cases like: | |||
3920 | // void i(); void i(int j); | |||
3921 | // void i(int j); void i(); | |||
3922 | // void i(); void i(int j) {} | |||
3923 | // See ActOnFinishFunctionBody() for other cases of the behavior change | |||
3924 | // diagnostic. See GetFullTypeForDeclarator() for handling of a function | |||
3925 | // type without a prototype. | |||
3926 | if (New->hasWrittenPrototype() != Old->hasWrittenPrototype() && | |||
3927 | !New->isImplicit() && !Old->isImplicit()) { | |||
3928 | const FunctionDecl *WithProto, *WithoutProto; | |||
3929 | if (New->hasWrittenPrototype()) { | |||
3930 | WithProto = New; | |||
3931 | WithoutProto = Old; | |||
3932 | } else { | |||
3933 | WithProto = Old; | |||
3934 | WithoutProto = New; | |||
3935 | } | |||
3936 | ||||
3937 | if (WithProto->getNumParams() != 0) { | |||
3938 | // The function definition has parameters, so this will change | |||
3939 | // behavior in C2x. | |||
3940 | // | |||
3941 | // If we already warned about about the function without a prototype | |||
3942 | // being deprecated, add a note that it also changes behavior. If we | |||
3943 | // didn't warn about it being deprecated (because the diagnostic is | |||
3944 | // not enabled), warn now that it is deprecated and changes behavior. | |||
3945 | bool AddNote = false; | |||
3946 | if (Diags.isIgnored(diag::warn_strict_prototypes, | |||
3947 | WithoutProto->getLocation())) { | |||
3948 | if (WithoutProto->getBuiltinID() == 0 && | |||
3949 | !WithoutProto->isImplicit() && | |||
3950 | SourceMgr.isBeforeInTranslationUnit(WithoutProto->getLocation(), | |||
3951 | WithProto->getLocation())) { | |||
3952 | PartialDiagnostic PD = | |||
3953 | PDiag(diag::warn_non_prototype_changes_behavior); | |||
3954 | if (TypeSourceInfo *TSI = WithoutProto->getTypeSourceInfo()) { | |||
3955 | if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>()) | |||
3956 | PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); | |||
3957 | } | |||
3958 | Diag(WithoutProto->getLocation(), PD); | |||
3959 | } | |||
3960 | } else { | |||
3961 | AddNote = true; | |||
3962 | } | |||
3963 | ||||
3964 | // Because the function with a prototype has parameters but a previous | |||
3965 | // declaration had none, the function with the prototype will also | |||
3966 | // change behavior in C2x. | |||
3967 | if (WithProto->getBuiltinID() == 0 && !WithProto->isImplicit()) { | |||
3968 | if (SourceMgr.isBeforeInTranslationUnit( | |||
3969 | WithProto->getLocation(), WithoutProto->getLocation())) { | |||
3970 | // If the function with the prototype comes before the function | |||
3971 | // without the prototype, we only want to diagnose the one without | |||
3972 | // the prototype. | |||
3973 | Diag(WithoutProto->getLocation(), | |||
3974 | diag::warn_non_prototype_changes_behavior); | |||
3975 | } else { | |||
3976 | // Otherwise, diagnose the one with the prototype, and potentially | |||
3977 | // attach a note to the one without a prototype if needed. | |||
3978 | Diag(WithProto->getLocation(), | |||
3979 | diag::warn_non_prototype_changes_behavior); | |||
3980 | if (AddNote && WithoutProto->getBuiltinID() == 0) | |||
3981 | Diag(WithoutProto->getLocation(), | |||
3982 | diag::note_func_decl_changes_behavior); | |||
3983 | } | |||
3984 | } else if (AddNote && WithoutProto->getBuiltinID() == 0 && | |||
3985 | !WithoutProto->isImplicit()) { | |||
3986 | // If we were supposed to add a note but the function with a | |||
3987 | // prototype is a builtin or was implicitly declared, which means we | |||
3988 | // have nothing to attach the note to, so we issue a warning instead. | |||
3989 | Diag(WithoutProto->getLocation(), | |||
3990 | diag::warn_non_prototype_changes_behavior); | |||
3991 | } | |||
3992 | } | |||
3993 | } | |||
3994 | ||||
3995 | if (Context.typesAreCompatible(OldQType, NewQType)) { | |||
3996 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); | |||
3997 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); | |||
3998 | const FunctionProtoType *OldProto = nullptr; | |||
3999 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && | |||
4000 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { | |||
4001 | // The old declaration provided a function prototype, but the | |||
4002 | // new declaration does not. Merge in the prototype. | |||
4003 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")(static_cast <bool> (!OldProto->hasExceptionSpec() && "Exception spec in C") ? void (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"" , "clang/lib/Sema/SemaDecl.cpp", 4003, __extension__ __PRETTY_FUNCTION__ )); | |||
4004 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); | |||
4005 | NewQType = | |||
4006 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, | |||
4007 | OldProto->getExtProtoInfo()); | |||
4008 | New->setType(NewQType); | |||
4009 | New->setHasInheritedPrototype(); | |||
4010 | ||||
4011 | // Synthesize parameters with the same types. | |||
4012 | SmallVector<ParmVarDecl *, 16> Params; | |||
4013 | for (const auto &ParamType : OldProto->param_types()) { | |||
4014 | ParmVarDecl *Param = ParmVarDecl::Create( | |||
4015 | Context, New, SourceLocation(), SourceLocation(), nullptr, | |||
4016 | ParamType, /*TInfo=*/nullptr, SC_None, nullptr); | |||
4017 | Param->setScopeInfo(0, Params.size()); | |||
4018 | Param->setImplicit(); | |||
4019 | Params.push_back(Param); | |||
4020 | } | |||
4021 | ||||
4022 | New->setParams(Params); | |||
4023 | } | |||
4024 | ||||
4025 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
4026 | } | |||
4027 | } | |||
4028 | ||||
4029 | // Check if the function types are compatible when pointer size address | |||
4030 | // spaces are ignored. | |||
4031 | if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) | |||
4032 | return false; | |||
4033 | ||||
4034 | // GNU C permits a K&R definition to follow a prototype declaration | |||
4035 | // if the declared types of the parameters in the K&R definition | |||
4036 | // match the types in the prototype declaration, even when the | |||
4037 | // promoted types of the parameters from the K&R definition differ | |||
4038 | // from the types in the prototype. GCC then keeps the types from | |||
4039 | // the prototype. | |||
4040 | // | |||
4041 | // If a variadic prototype is followed by a non-variadic K&R definition, | |||
4042 | // the K&R definition becomes variadic. This is sort of an edge case, but | |||
4043 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and | |||
4044 | // C99 6.9.1p8. | |||
4045 | if (!getLangOpts().CPlusPlus && | |||
4046 | Old->hasPrototype() && !New->hasPrototype() && | |||
4047 | New->getType()->getAs<FunctionProtoType>() && | |||
4048 | Old->getNumParams() == New->getNumParams()) { | |||
4049 | SmallVector<QualType, 16> ArgTypes; | |||
4050 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; | |||
4051 | const FunctionProtoType *OldProto | |||
4052 | = Old->getType()->getAs<FunctionProtoType>(); | |||
4053 | const FunctionProtoType *NewProto | |||
4054 | = New->getType()->getAs<FunctionProtoType>(); | |||
4055 | ||||
4056 | // Determine whether this is the GNU C extension. | |||
4057 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), | |||
4058 | NewProto->getReturnType()); | |||
4059 | bool LooseCompatible = !MergedReturn.isNull(); | |||
4060 | for (unsigned Idx = 0, End = Old->getNumParams(); | |||
4061 | LooseCompatible && Idx != End; ++Idx) { | |||
4062 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); | |||
4063 | ParmVarDecl *NewParm = New->getParamDecl(Idx); | |||
4064 | if (Context.typesAreCompatible(OldParm->getType(), | |||
4065 | NewProto->getParamType(Idx))) { | |||
4066 | ArgTypes.push_back(NewParm->getType()); | |||
4067 | } else if (Context.typesAreCompatible(OldParm->getType(), | |||
4068 | NewParm->getType(), | |||
4069 | /*CompareUnqualified=*/true)) { | |||
4070 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, | |||
4071 | NewProto->getParamType(Idx) }; | |||
4072 | Warnings.push_back(Warn); | |||
4073 | ArgTypes.push_back(NewParm->getType()); | |||
4074 | } else | |||
4075 | LooseCompatible = false; | |||
4076 | } | |||
4077 | ||||
4078 | if (LooseCompatible) { | |||
4079 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { | |||
4080 | Diag(Warnings[Warn].NewParm->getLocation(), | |||
4081 | diag::ext_param_promoted_not_compatible_with_prototype) | |||
4082 | << Warnings[Warn].PromotedType | |||
4083 | << Warnings[Warn].OldParm->getType(); | |||
4084 | if (Warnings[Warn].OldParm->getLocation().isValid()) | |||
4085 | Diag(Warnings[Warn].OldParm->getLocation(), | |||
4086 | diag::note_previous_declaration); | |||
4087 | } | |||
4088 | ||||
4089 | if (MergeTypeWithOld) | |||
4090 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, | |||
4091 | OldProto->getExtProtoInfo())); | |||
4092 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | |||
4093 | } | |||
4094 | ||||
4095 | // Fall through to diagnose conflicting types. | |||
4096 | } | |||
4097 | ||||
4098 | // A function that has already been declared has been redeclared or | |||
4099 | // defined with a different type; show an appropriate diagnostic. | |||
4100 | ||||
4101 | // If the previous declaration was an implicitly-generated builtin | |||
4102 | // declaration, then at the very least we should use a specialized note. | |||
4103 | unsigned BuiltinID; | |||
4104 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { | |||
4105 | // If it's actually a library-defined builtin function like 'malloc' | |||
4106 | // or 'printf', just warn about the incompatible redeclaration. | |||
4107 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { | |||
4108 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; | |||
4109 | Diag(OldLocation, diag::note_previous_builtin_declaration) | |||
4110 | << Old << Old->getType(); | |||
4111 | return false; | |||
4112 | } | |||
4113 | ||||
4114 | PrevDiag = diag::note_previous_builtin_declaration; | |||
4115 | } | |||
4116 | ||||
4117 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); | |||
4118 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | |||
4119 | return true; | |||
4120 | } | |||
4121 | ||||
4122 | /// Completes the merge of two function declarations that are | |||
4123 | /// known to be compatible. | |||
4124 | /// | |||
4125 | /// This routine handles the merging of attributes and other | |||
4126 | /// properties of function declarations from the old declaration to | |||
4127 | /// the new declaration, once we know that New is in fact a | |||
4128 | /// redeclaration of Old. | |||
4129 | /// | |||
4130 | /// \returns false | |||
4131 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | |||
4132 | Scope *S, bool MergeTypeWithOld) { | |||
4133 | // Merge the attributes | |||
4134 | mergeDeclAttributes(New, Old); | |||
4135 | ||||
4136 | // Merge "pure" flag. | |||
4137 | if (Old->isPure()) | |||
4138 | New->setPure(); | |||
4139 | ||||
4140 | // Merge "used" flag. | |||
4141 | if (Old->getMostRecentDecl()->isUsed(false)) | |||
4142 | New->setIsUsed(); | |||
4143 | ||||
4144 | // Merge attributes from the parameters. These can mismatch with K&R | |||
4145 | // declarations. | |||
4146 | if (New->getNumParams() == Old->getNumParams()) | |||
4147 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { | |||
4148 | ParmVarDecl *NewParam = New->getParamDecl(i); | |||
4149 | ParmVarDecl *OldParam = Old->getParamDecl(i); | |||
4150 | mergeParamDeclAttributes(NewParam, OldParam, *this); | |||
4151 | mergeParamDeclTypes(NewParam, OldParam, *this); | |||
4152 | } | |||
4153 | ||||
4154 | if (getLangOpts().CPlusPlus) | |||
4155 | return MergeCXXFunctionDecl(New, Old, S); | |||
4156 | ||||
4157 | // Merge the function types so the we get the composite types for the return | |||
4158 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl | |||
4159 | // was visible. | |||
4160 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); | |||
4161 | if (!Merged.isNull() && MergeTypeWithOld) | |||
4162 | New->setType(Merged); | |||
4163 | ||||
4164 | return false; | |||
4165 | } | |||
4166 | ||||
4167 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, | |||
4168 | ObjCMethodDecl *oldMethod) { | |||
4169 | // Merge the attributes, including deprecated/unavailable | |||
4170 | AvailabilityMergeKind MergeKind = | |||
4171 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) | |||
4172 | ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation | |||
4173 | : AMK_ProtocolImplementation) | |||
4174 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration | |||
4175 | : AMK_Override; | |||
4176 | ||||
4177 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); | |||
4178 | ||||
4179 | // Merge attributes from the parameters. | |||
4180 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), | |||
4181 | oe = oldMethod->param_end(); | |||
4182 | for (ObjCMethodDecl::param_iterator | |||
4183 | ni = newMethod->param_begin(), ne = newMethod->param_end(); | |||
4184 | ni != ne && oi != oe; ++ni, ++oi) | |||
4185 | mergeParamDeclAttributes(*ni, *oi, *this); | |||
4186 | ||||
4187 | CheckObjCMethodOverride(newMethod, oldMethod); | |||
4188 | } | |||
4189 | ||||
4190 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { | |||
4191 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))(static_cast <bool> (!S.Context.hasSameType(New->getType (), Old->getType())) ? void (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())" , "clang/lib/Sema/SemaDecl.cpp", 4191, __extension__ __PRETTY_FUNCTION__ )); | |||
4192 | ||||
4193 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() | |||
4194 | ? diag::err_redefinition_different_type | |||
4195 | : diag::err_redeclaration_different_type) | |||
4196 | << New->getDeclName() << New->getType() << Old->getType(); | |||
4197 | ||||
4198 | diag::kind PrevDiag; | |||
4199 | SourceLocation OldLocation; | |||
4200 | std::tie(PrevDiag, OldLocation) | |||
4201 | = getNoteDiagForInvalidRedeclaration(Old, New); | |||
4202 | S.Diag(OldLocation, PrevDiag); | |||
4203 | New->setInvalidDecl(); | |||
4204 | } | |||
4205 | ||||
4206 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and | |||
4207 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, | |||
4208 | /// emitting diagnostics as appropriate. | |||
4209 | /// | |||
4210 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back | |||
4211 | /// to here in AddInitializerToDecl. We can't check them before the initializer | |||
4212 | /// is attached. | |||
4213 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, | |||
4214 | bool MergeTypeWithOld) { | |||
4215 | if (New->isInvalidDecl() || Old->isInvalidDecl()) | |||
4216 | return; | |||
4217 | ||||
4218 | QualType MergedT; | |||
4219 | if (getLangOpts().CPlusPlus) { | |||
4220 | if (New->getType()->isUndeducedType()) { | |||
4221 | // We don't know what the new type is until the initializer is attached. | |||
4222 | return; | |||
4223 | } else if (Context.hasSameType(New->getType(), Old->getType())) { | |||
4224 | // These could still be something that needs exception specs checked. | |||
4225 | return MergeVarDeclExceptionSpecs(New, Old); | |||
4226 | } | |||
4227 | // C++ [basic.link]p10: | |||
4228 | // [...] the types specified by all declarations referring to a given | |||
4229 | // object or function shall be identical, except that declarations for an | |||
4230 | // array object can specify array types that differ by the presence or | |||
4231 | // absence of a major array bound (8.3.4). | |||
4232 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { | |||
4233 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); | |||
4234 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); | |||
4235 | ||||
4236 | // We are merging a variable declaration New into Old. If it has an array | |||
4237 | // bound, and that bound differs from Old's bound, we should diagnose the | |||
4238 | // mismatch. | |||
4239 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { | |||
4240 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; | |||
4241 | PrevVD = PrevVD->getPreviousDecl()) { | |||
4242 | QualType PrevVDTy = PrevVD->getType(); | |||
4243 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) | |||
4244 | continue; | |||
4245 | ||||
4246 | if (!Context.hasSameType(New->getType(), PrevVDTy)) | |||
4247 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); | |||
4248 | } | |||
4249 | } | |||
4250 | ||||
4251 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { | |||
4252 | if (Context.hasSameType(OldArray->getElementType(), | |||
4253 | NewArray->getElementType())) | |||
4254 | MergedT = New->getType(); | |||
4255 | } | |||
4256 | // FIXME: Check visibility. New is hidden but has a complete type. If New | |||
4257 | // has no array bound, it should not inherit one from Old, if Old is not | |||
4258 | // visible. | |||
4259 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { | |||
4260 | if (Context.hasSameType(OldArray->getElementType(), | |||
4261 | NewArray->getElementType())) | |||
4262 | MergedT = Old->getType(); | |||
4263 | } | |||
4264 | } | |||
4265 | else if (New->getType()->isObjCObjectPointerType() && | |||
4266 | Old->getType()->isObjCObjectPointerType()) { | |||
4267 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), | |||
4268 | Old->getType()); | |||
4269 | } | |||
4270 | } else { | |||
4271 | // C 6.2.7p2: | |||
4272 | // All declarations that refer to the same object or function shall have | |||
4273 | // compatible type. | |||
4274 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); | |||
4275 | } | |||
4276 | if (MergedT.isNull()) { | |||
4277 | // It's OK if we couldn't merge types if either type is dependent, for a | |||
4278 | // block-scope variable. In other cases (static data members of class | |||
4279 | // templates, variable templates, ...), we require the types to be | |||
4280 | // equivalent. | |||
4281 | // FIXME: The C++ standard doesn't say anything about this. | |||
4282 | if ((New->getType()->isDependentType() || | |||
4283 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { | |||
4284 | // If the old type was dependent, we can't merge with it, so the new type | |||
4285 | // becomes dependent for now. We'll reproduce the original type when we | |||
4286 | // instantiate the TypeSourceInfo for the variable. | |||
4287 | if (!New->getType()->isDependentType() && MergeTypeWithOld) | |||
4288 | New->setType(Context.DependentTy); | |||
4289 | return; | |||
4290 | } | |||
4291 | return diagnoseVarDeclTypeMismatch(*this, New, Old); | |||
4292 | } | |||
4293 | ||||
4294 | // Don't actually update the type on the new declaration if the old | |||
4295 | // declaration was an extern declaration in a different scope. | |||
4296 | if (MergeTypeWithOld) | |||
4297 | New->setType(MergedT); | |||
4298 | } | |||
4299 | ||||
4300 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, | |||
4301 | LookupResult &Previous) { | |||
4302 | // C11 6.2.7p4: | |||
4303 | // For an identifier with internal or external linkage declared | |||
4304 | // in a scope in which a prior declaration of that identifier is | |||
4305 | // visible, if the prior declaration specifies internal or | |||
4306 | // external linkage, the type of the identifier at the later | |||
4307 | // declaration becomes the composite type. | |||
4308 | // | |||
4309 | // If the variable isn't visible, we do not merge with its type. | |||
4310 | if (Previous.isShadowed()) | |||
4311 | return false; | |||
4312 | ||||
4313 | if (S.getLangOpts().CPlusPlus) { | |||
4314 | // C++11 [dcl.array]p3: | |||
4315 | // If there is a preceding declaration of the entity in the same | |||
4316 | // scope in which the bound was specified, an omitted array bound | |||
4317 | // is taken to be the same as in that earlier declaration. | |||
4318 | return NewVD->isPreviousDeclInSameBlockScope() || | |||
4319 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && | |||
4320 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); | |||
4321 | } else { | |||
4322 | // If the old declaration was function-local, don't merge with its | |||
4323 | // type unless we're in the same function. | |||
4324 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || | |||
4325 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); | |||
4326 | } | |||
4327 | } | |||
4328 | ||||
4329 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name | |||
4330 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this | |||
4331 | /// situation, merging decls or emitting diagnostics as appropriate. | |||
4332 | /// | |||
4333 | /// Tentative definition rules (C99 6.9.2p2) are checked by | |||
4334 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative | |||
4335 | /// definitions here, since the initializer hasn't been attached. | |||
4336 | /// | |||
4337 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { | |||
4338 | // If the new decl is already invalid, don't do any other checking. | |||
4339 | if (New->isInvalidDecl()) | |||
4340 | return; | |||
4341 | ||||
4342 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) | |||
4343 | return; | |||
4344 | ||||
4345 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); | |||
4346 | ||||
4347 | // Verify the old decl was also a variable or variable template. | |||
4348 | VarDecl *Old = nullptr; | |||
4349 | VarTemplateDecl *OldTemplate = nullptr; | |||
4350 | if (Previous.isSingleResult()) { | |||
4351 | if (NewTemplate) { | |||
4352 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); | |||
4353 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; | |||
4354 | ||||
4355 | if (auto *Shadow = | |||
4356 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | |||
4357 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) | |||
4358 | return New->setInvalidDecl(); | |||
4359 | } else { | |||
4360 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); | |||
4361 | ||||
4362 | if (auto *Shadow = | |||
4363 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | |||
4364 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) | |||
4365 | return New->setInvalidDecl(); | |||
4366 | } | |||
4367 | } | |||
4368 | if (!Old) { | |||
4369 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | |||
4370 | << New->getDeclName(); | |||
4371 | notePreviousDefinition(Previous.getRepresentativeDecl(), | |||
4372 | New->getLocation()); | |||
4373 | return New->setInvalidDecl(); | |||
4374 | } | |||
4375 | ||||
4376 | // If the old declaration was found in an inline namespace and the new | |||
4377 | // declaration was qualified, update the DeclContext to match. | |||
4378 | adjustDeclContextForDeclaratorDecl(New, Old); | |||
4379 | ||||
4380 | // Ensure the template parameters are compatible. | |||
4381 | if (NewTemplate && | |||
4382 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | |||
4383 | OldTemplate->getTemplateParameters(), | |||
4384 | /*Complain=*/true, TPL_TemplateMatch)) | |||
4385 | return New->setInvalidDecl(); | |||
4386 | ||||
4387 | // C++ [class.mem]p1: | |||
4388 | // A member shall not be declared twice in the member-specification [...] | |||
4389 | // | |||
4390 | // Here, we need only consider static data members. | |||
4391 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { | |||
4392 | Diag(New->getLocation(), diag::err_duplicate_member) | |||
4393 | << New->getIdentifier(); | |||
4394 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
4395 | New->setInvalidDecl(); | |||
4396 | } | |||
4397 | ||||
4398 | mergeDeclAttributes(New, Old); | |||
4399 | // Warn if an already-declared variable is made a weak_import in a subsequent | |||
4400 | // declaration | |||
4401 | if (New->hasAttr<WeakImportAttr>() && | |||
4402 | Old->getStorageClass() == SC_None && | |||
4403 | !Old->hasAttr<WeakImportAttr>()) { | |||
4404 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); | |||
4405 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
4406 | // Remove weak_import attribute on new declaration. | |||
4407 | New->dropAttr<WeakImportAttr>(); | |||
4408 | } | |||
4409 | ||||
4410 | if (const auto *ILA = New->getAttr<InternalLinkageAttr>()) | |||
4411 | if (!Old->hasAttr<InternalLinkageAttr>()) { | |||
4412 | Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl) | |||
4413 | << ILA; | |||
4414 | Diag(Old->getLocation(), diag::note_previous_declaration); | |||
4415 | New->dropAttr<InternalLinkageAttr>(); | |||
4416 | } | |||
4417 | ||||
4418 | // Merge the types. | |||
4419 | VarDecl *MostRecent = Old->getMostRecentDecl(); | |||
4420 | if (MostRecent != Old) { | |||
4421 | MergeVarDeclTypes(New, MostRecent, | |||
4422 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); | |||
4423 | if (New->isInvalidDecl()) | |||
4424 | return; | |||
4425 | } | |||
4426 | ||||
4427 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); | |||
4428 | if (New->isInvalidDecl()) | |||
4429 | return; | |||
4430 | ||||
4431 | diag::kind PrevDiag; | |||
4432 | SourceLocation OldLocation; | |||
4433 | std::tie(PrevDiag, OldLocation) = | |||
4434 | getNoteDiagForInvalidRedeclaration(Old, New); | |||
4435 | ||||
4436 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. | |||
4437 | if (New->getStorageClass() == SC_Static && | |||
4438 | !New->isStaticDataMember() && | |||
4439 | Old->hasExternalFormalLinkage()) { | |||
4440 | if (getLangOpts().MicrosoftExt) { | |||
4441 | Diag(New->getLocation(), diag::ext_static_non_static) | |||
4442 | << New->getDeclName(); | |||
4443 | Diag(OldLocation, PrevDiag); | |||
4444 | } else { | |||
4445 | Diag(New->getLocation(), diag::err_static_non_static) | |||
4446 | << New->getDeclName(); | |||
4447 | Diag(OldLocation, PrevDiag); | |||
4448 | return New->setInvalidDecl(); | |||
4449 | } | |||
4450 | } | |||
4451 | // C99 6.2.2p4: | |||
4452 | // For an identifier declared with the storage-class specifier | |||
4453 | // extern in a scope in which a prior declaration of that | |||
4454 | // identifier is visible,23) if the prior declaration specifies | |||
4455 | // internal or external linkage, the linkage of the identifier at | |||
4456 | // the later declaration is the same as the linkage specified at | |||
4457 | // the prior declaration. If no prior declaration is visible, or | |||
4458 | // if the prior declaration specifies no linkage, then the | |||
4459 | // identifier has external linkage. | |||
4460 | if (New->hasExternalStorage() && Old->hasLinkage()) | |||
4461 | /* Okay */; | |||
4462 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && | |||
4463 | !New->isStaticDataMember() && | |||
4464 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { | |||
4465 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); | |||
4466 | Diag(OldLocation, PrevDiag); | |||
4467 | return New->setInvalidDecl(); | |||
4468 | } | |||
4469 | ||||
4470 | // Check if extern is followed by non-extern and vice-versa. | |||
4471 | if (New->hasExternalStorage() && | |||
4472 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { | |||
4473 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); | |||
4474 | Diag(OldLocation, PrevDiag); | |||
4475 | return New->setInvalidDecl(); | |||
4476 | } | |||
4477 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && | |||
4478 | !New->hasExternalStorage()) { | |||
4479 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); | |||
4480 | Diag(OldLocation, PrevDiag); | |||
4481 | return New->setInvalidDecl(); | |||
4482 | } | |||
4483 | ||||
4484 | if (CheckRedeclarationInModule(New, Old)) | |||
4485 | return; | |||
4486 | ||||
4487 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. | |||
4488 | ||||
4489 | // FIXME: The test for external storage here seems wrong? We still | |||
4490 | // need to check for mismatches. | |||
4491 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && | |||
4492 | // Don't complain about out-of-line definitions of static members. | |||
4493 | !(Old->getLexicalDeclContext()->isRecord() && | |||
4494 | !New->getLexicalDeclContext()->isRecord())) { | |||
4495 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); | |||
4496 | Diag(OldLocation, PrevDiag); | |||
4497 | return New->setInvalidDecl(); | |||
4498 | } | |||
4499 | ||||
4500 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { | |||
4501 | if (VarDecl *Def = Old->getDefinition()) { | |||
4502 | // C++1z [dcl.fcn.spec]p4: | |||
4503 | // If the definition of a variable appears in a translation unit before | |||
4504 | // its first declaration as inline, the program is ill-formed. | |||
4505 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | |||
4506 | Diag(Def->getLocation(), diag::note_previous_definition); | |||
4507 | } | |||
4508 | } | |||
4509 | ||||
4510 | // If this redeclaration makes the variable inline, we may need to add it to | |||
4511 | // UndefinedButUsed. | |||
4512 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && | |||
4513 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) | |||
4514 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | |||
4515 | SourceLocation())); | |||
4516 | ||||
4517 | if (New->getTLSKind() != Old->getTLSKind()) { | |||
4518 | if (!Old->getTLSKind()) { | |||
4519 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); | |||
4520 | Diag(OldLocation, PrevDiag); | |||
4521 | } else if (!New->getTLSKind()) { | |||
4522 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); | |||
4523 | Diag(OldLocation, PrevDiag); | |||
4524 | } else { | |||
4525 | // Do not allow redeclaration to change the variable between requiring | |||
4526 | // static and dynamic initialization. | |||
4527 | // FIXME: GCC allows this, but uses the TLS keyword on the first | |||
4528 | // declaration to determine the kind. Do we need to be compatible here? | |||
4529 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) | |||
4530 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); | |||
4531 | Diag(OldLocation, PrevDiag); | |||
4532 | } | |||
4533 | } | |||
4534 | ||||
4535 | // C++ doesn't have tentative definitions, so go right ahead and check here. | |||
4536 | if (getLangOpts().CPlusPlus && | |||
4537 | New->isThisDeclarationADefinition() == VarDecl::Definition) { | |||
4538 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && | |||
4539 | Old->getCanonicalDecl()->isConstexpr()) { | |||
4540 | // This definition won't be a definition any more once it's been merged. | |||
4541 | Diag(New->getLocation(), | |||
4542 | diag::warn_deprecated_redundant_constexpr_static_def); | |||
4543 | } else if (VarDecl *Def = Old->getDefinition()) { | |||
4544 | if (checkVarDeclRedefinition(Def, New)) | |||
4545 | return; | |||
4546 | } | |||
4547 | } | |||
4548 | ||||
4549 | if (haveIncompatibleLanguageLinkages(Old, New)) { | |||
4550 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | |||
4551 | Diag(OldLocation, PrevDiag); | |||
4552 | New->setInvalidDecl(); | |||
4553 | return; | |||
4554 | } | |||
4555 | ||||
4556 | // Merge "used" flag. | |||
4557 | if (Old->getMostRecentDecl()->isUsed(false)) | |||
4558 | New->setIsUsed(); | |||
4559 | ||||
4560 | // Keep a chain of previous declarations. | |||
4561 | New->setPreviousDecl(Old); | |||
4562 | if (NewTemplate) | |||
4563 | NewTemplate->setPreviousDecl(OldTemplate); | |||
4564 | ||||
4565 | // Inherit access appropriately. | |||
4566 | New->setAccess(Old->getAccess()); | |||
4567 | if (NewTemplate) | |||
4568 | NewTemplate->setAccess(New->getAccess()); | |||
4569 | ||||
4570 | if (Old->isInline()) | |||
4571 | New->setImplicitlyInline(); | |||
4572 | } | |||
4573 | ||||
4574 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { | |||
4575 | SourceManager &SrcMgr = getSourceManager(); | |||
4576 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); | |||
4577 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); | |||
4578 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); | |||
4579 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); | |||
4580 | auto &HSI = PP.getHeaderSearchInfo(); | |||
4581 | StringRef HdrFilename = | |||
4582 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); | |||
4583 | ||||
4584 | auto noteFromModuleOrInclude = [&](Module *Mod, | |||
4585 | SourceLocation IncLoc) -> bool { | |||
4586 | // Redefinition errors with modules are common with non modular mapped | |||
4587 | // headers, example: a non-modular header H in module A that also gets | |||
4588 | // included directly in a TU. Pointing twice to the same header/definition | |||
4589 | // is confusing, try to get better diagnostics when modules is on. | |||
4590 | if (IncLoc.isValid()) { | |||
4591 | if (Mod) { | |||
4592 | Diag(IncLoc, diag::note_redefinition_modules_same_file) | |||
4593 | << HdrFilename.str() << Mod->getFullModuleName(); | |||
4594 | if (!Mod->DefinitionLoc.isInvalid()) | |||
4595 | Diag(Mod->DefinitionLoc, diag::note_defined_here) | |||
4596 | << Mod->getFullModuleName(); | |||
4597 | } else { | |||
4598 | Diag(IncLoc, diag::note_redefinition_include_same_file) | |||
4599 | << HdrFilename.str(); | |||
4600 | } | |||
4601 | return true; | |||
4602 | } | |||
4603 | ||||
4604 | return false; | |||
4605 | }; | |||
4606 | ||||
4607 | // Is it the same file and same offset? Provide more information on why | |||
4608 | // this leads to a redefinition error. | |||
4609 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { | |||
4610 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); | |||
4611 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); | |||
4612 | bool EmittedDiag = | |||
4613 | noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); | |||
4614 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); | |||
4615 | ||||
4616 | // If the header has no guards, emit a note suggesting one. | |||
4617 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) | |||
4618 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); | |||
4619 | ||||
4620 | if (EmittedDiag) | |||
4621 | return; | |||
4622 | } | |||
4623 | ||||
4624 | // Redefinition coming from different files or couldn't do better above. | |||
4625 | if (Old->getLocation().isValid()) | |||
4626 | Diag(Old->getLocation(), diag::note_previous_definition); | |||
4627 | } | |||
4628 | ||||
4629 | /// We've just determined that \p Old and \p New both appear to be definitions | |||
4630 | /// of the same variable. Either diagnose or fix the problem. | |||
4631 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { | |||
4632 | if (!hasVisibleDefinition(Old) && | |||
4633 | (New->getFormalLinkage() == InternalLinkage || | |||
4634 | New->isInline() || | |||
4635 | New->getDescribedVarTemplate() || | |||
4636 | New->getNumTemplateParameterLists() || | |||
4637 | New->getDeclContext()->isDependentContext())) { | |||
4638 | // The previous definition is hidden, and multiple definitions are | |||
4639 | // permitted (in separate TUs). Demote this to a declaration. | |||
4640 | New->demoteThisDefinitionToDeclaration(); | |||
4641 | ||||
4642 | // Make the canonical definition visible. | |||
4643 | if (auto *OldTD = Old->getDescribedVarTemplate()) | |||
4644 | makeMergedDefinitionVisible(OldTD); | |||
4645 | makeMergedDefinitionVisible(Old); | |||
4646 | return false; | |||
4647 | } else { | |||
4648 | Diag(New->getLocation(), diag::err_redefinition) << New; | |||
4649 | notePreviousDefinition(Old, New->getLocation()); | |||
4650 | New->setInvalidDecl(); | |||
4651 | return true; | |||
4652 | } | |||
4653 | } | |||
4654 | ||||
4655 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | |||
4656 | /// no declarator (e.g. "struct foo;") is parsed. | |||
4657 | Decl * | |||
4658 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | |||
4659 | RecordDecl *&AnonRecord) { | |||
4660 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, | |||
4661 | AnonRecord); | |||
4662 | } | |||
4663 | ||||
4664 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to | |||
4665 | // disambiguate entities defined in different scopes. | |||
4666 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks | |||
4667 | // compatibility. | |||
4668 | // We will pick our mangling number depending on which version of MSVC is being | |||
4669 | // targeted. | |||
4670 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { | |||
4671 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) | |||
4672 | ? S->getMSCurManglingNumber() | |||
4673 | : S->getMSLastManglingNumber(); | |||
4674 | } | |||
4675 | ||||
4676 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { | |||
4677 | if (!Context.getLangOpts().CPlusPlus) | |||
4678 | return; | |||
4679 | ||||
4680 | if (isa<CXXRecordDecl>(Tag->getParent())) { | |||
4681 | // If this tag is the direct child of a class, number it if | |||
4682 | // it is anonymous. | |||
4683 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) | |||
4684 | return; | |||
4685 | MangleNumberingContext &MCtx = | |||
4686 | Context.getManglingNumberContext(Tag->getParent()); | |||
4687 | Context.setManglingNumber( | |||
4688 | Tag, MCtx.getManglingNumber( | |||
4689 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | |||
4690 | return; | |||
4691 | } | |||
4692 | ||||
4693 | // If this tag isn't a direct child of a class, number it if it is local. | |||
4694 | MangleNumberingContext *MCtx; | |||
4695 | Decl *ManglingContextDecl; | |||
4696 | std::tie(MCtx, ManglingContextDecl) = | |||
4697 | getCurrentMangleNumberContext(Tag->getDeclContext()); | |||
4698 | if (MCtx) { | |||
4699 | Context.setManglingNumber( | |||
4700 | Tag, MCtx->getManglingNumber( | |||
4701 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | |||
4702 | } | |||
4703 | } | |||
4704 | ||||
4705 | namespace { | |||
4706 | struct NonCLikeKind { | |||
4707 | enum { | |||
4708 | None, | |||
4709 | BaseClass, | |||
4710 | DefaultMemberInit, | |||
4711 | Lambda, | |||
4712 | Friend, | |||
4713 | OtherMember, | |||
4714 | Invalid, | |||
4715 | } Kind = None; | |||
4716 | SourceRange Range; | |||
4717 | ||||
4718 | explicit operator bool() { return Kind != None; } | |||
4719 | }; | |||
4720 | } | |||
4721 | ||||
4722 | /// Determine whether a class is C-like, according to the rules of C++ | |||
4723 | /// [dcl.typedef] for anonymous classes with typedef names for linkage. | |||
4724 | static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { | |||
4725 | if (RD->isInvalidDecl()) | |||
4726 | return {NonCLikeKind::Invalid, {}}; | |||
4727 | ||||
4728 | // C++ [dcl.typedef]p9: [P1766R1] | |||
4729 | // An unnamed class with a typedef name for linkage purposes shall not | |||
4730 | // | |||
4731 | // -- have any base classes | |||
4732 | if (RD->getNumBases()) | |||
4733 | return {NonCLikeKind::BaseClass, | |||
4734 | SourceRange(RD->bases_begin()->getBeginLoc(), | |||
4735 | RD->bases_end()[-1].getEndLoc())}; | |||
4736 | bool Invalid = false; | |||
4737 | for (Decl *D : RD->decls()) { | |||
4738 | // Don't complain about things we already diagnosed. | |||
4739 | if (D->isInvalidDecl()) { | |||
4740 | Invalid = true; | |||
4741 | continue; | |||
4742 | } | |||
4743 | ||||
4744 | // -- have any [...] default member initializers | |||
4745 | if (auto *FD = dyn_cast<FieldDecl>(D)) { | |||
4746 | if (FD->hasInClassInitializer()) { | |||
4747 | auto *Init = FD->getInClassInitializer(); | |||
4748 | return {NonCLikeKind::DefaultMemberInit, | |||
4749 | Init ? Init->getSourceRange() : D->getSourceRange()}; | |||
4750 | } | |||
4751 | continue; | |||
4752 | } | |||
4753 | ||||
4754 | // FIXME: We don't allow friend declarations. This violates the wording of | |||
4755 | // P1766, but not the intent. | |||
4756 | if (isa<FriendDecl>(D)) | |||
4757 | return {NonCLikeKind::Friend, D->getSourceRange()}; | |||
4758 | ||||
4759 | // -- declare any members other than non-static data members, member | |||
4760 | // enumerations, or member classes, | |||
4761 | if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || | |||
4762 | isa<EnumDecl>(D)) | |||
4763 | continue; | |||
4764 | auto *MemberRD = dyn_cast<CXXRecordDecl>(D); | |||
4765 | if (!MemberRD) { | |||
4766 | if (D->isImplicit()) | |||
4767 | continue; | |||
4768 | return {NonCLikeKind::OtherMember, D->getSourceRange()}; | |||
4769 | } | |||
4770 | ||||
4771 | // -- contain a lambda-expression, | |||
4772 | if (MemberRD->isLambda()) | |||
4773 | return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; | |||
4774 | ||||
4775 | // and all member classes shall also satisfy these requirements | |||
4776 | // (recursively). | |||
4777 | if (MemberRD->isThisDeclarationADefinition()) { | |||
4778 | if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) | |||
4779 | return Kind; | |||
4780 | } | |||
4781 | } | |||
4782 | ||||
4783 | return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; | |||
4784 | } | |||
4785 | ||||
4786 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | |||
4787 | TypedefNameDecl *NewTD) { | |||
4788 | if (TagFromDeclSpec->isInvalidDecl()) | |||
4789 | return; | |||
4790 | ||||
4791 | // Do nothing if the tag already has a name for linkage purposes. | |||
4792 | if (TagFromDeclSpec->hasNameForLinkage()) | |||
4793 | return; | |||
4794 | ||||
4795 | // A well-formed anonymous tag must always be a TUK_Definition. | |||
4796 | assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition ()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "clang/lib/Sema/SemaDecl.cpp", 4796, __extension__ __PRETTY_FUNCTION__ )); | |||
4797 | ||||
4798 | // The type must match the tag exactly; no qualifiers allowed. | |||
4799 | if (!Context.hasSameType(NewTD->getUnderlyingType(), | |||
4800 | Context.getTagDeclType(TagFromDeclSpec))) { | |||
4801 | if (getLangOpts().CPlusPlus) | |||
4802 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); | |||
4803 | return; | |||
4804 | } | |||
4805 | ||||
4806 | // C++ [dcl.typedef]p9: [P1766R1, applied as DR] | |||
4807 | // An unnamed class with a typedef name for linkage purposes shall [be | |||
4808 | // C-like]. | |||
4809 | // | |||
4810 | // FIXME: Also diagnose if we've already computed the linkage. That ideally | |||
4811 | // shouldn't happen, but there are constructs that the language rule doesn't | |||
4812 | // disallow for which we can't reasonably avoid computing linkage early. | |||
4813 | const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); | |||
4814 | NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) | |||
4815 | : NonCLikeKind(); | |||
4816 | bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); | |||
4817 | if (NonCLike || ChangesLinkage) { | |||
4818 | if (NonCLike.Kind == NonCLikeKind::Invalid) | |||
4819 | return; | |||
4820 | ||||
4821 | unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; | |||
4822 | if (ChangesLinkage) { | |||
4823 | // If the linkage changes, we can't accept this as an extension. | |||
4824 | if (NonCLike.Kind == NonCLikeKind::None) | |||
4825 | DiagID = diag::err_typedef_changes_linkage; | |||
4826 | else | |||
4827 | DiagID = diag::err_non_c_like_anon_struct_in_typedef; | |||
4828 | } | |||
4829 | ||||
4830 | SourceLocation FixitLoc = | |||
4831 | getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); | |||
4832 | llvm::SmallString<40> TextToInsert; | |||
4833 | TextToInsert += ' '; | |||
4834 | TextToInsert += NewTD->getIdentifier()->getName(); | |||
4835 | ||||
4836 | Diag(FixitLoc, DiagID) | |||
4837 | << isa<TypeAliasDecl>(NewTD) | |||
4838 | << FixItHint::CreateInsertion(FixitLoc, TextToInsert); | |||
4839 | if (NonCLike.Kind != NonCLikeKind::None) { | |||
4840 | Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) | |||
4841 | << NonCLike.Kind - 1 << NonCLike.Range; | |||
4842 | } | |||
4843 | Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) | |||
4844 | << NewTD << isa<TypeAliasDecl>(NewTD); | |||
4845 | ||||
4846 | if (ChangesLinkage) | |||
4847 | return; | |||
4848 | } | |||
4849 | ||||
4850 | // Otherwise, set this as the anon-decl typedef for the tag. | |||
4851 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); | |||
4852 | } | |||
4853 | ||||
4854 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { | |||
4855 | switch (T) { | |||
4856 | case DeclSpec::TST_class: | |||
4857 | return 0; | |||
4858 | case DeclSpec::TST_struct: | |||
4859 | return 1; | |||
4860 | case DeclSpec::TST_interface: | |||
4861 | return 2; | |||
4862 | case DeclSpec::TST_union: | |||
4863 | return 3; | |||
4864 | case DeclSpec::TST_enum: | |||
4865 | return 4; | |||
4866 | default: | |||
4867 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "clang/lib/Sema/SemaDecl.cpp", 4867); | |||
4868 | } | |||
4869 | } | |||
4870 | ||||
4871 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | |||
4872 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template | |||
4873 | /// parameters to cope with template friend declarations. | |||
4874 | Decl * | |||
4875 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | |||
4876 | MultiTemplateParamsArg TemplateParams, | |||
4877 | bool IsExplicitInstantiation, | |||
4878 | RecordDecl *&AnonRecord) { | |||
4879 | Decl *TagD = nullptr; | |||
4880 | TagDecl *Tag = nullptr; | |||
4881 | if (DS.getTypeSpecType() == DeclSpec::TST_class || | |||
4882 | DS.getTypeSpecType() == DeclSpec::TST_struct || | |||
4883 | DS.getTypeSpecType() == DeclSpec::TST_interface || | |||
4884 | DS.getTypeSpecType() == DeclSpec::TST_union || | |||
4885 | DS.getTypeSpecType() == DeclSpec::TST_enum) { | |||
4886 | TagD = DS.getRepAsDecl(); | |||
4887 | ||||
4888 | if (!TagD) // We probably had an error | |||
4889 | return nullptr; | |||
4890 | ||||
4891 | // Note that the above type specs guarantee that the | |||
4892 | // type rep is a Decl, whereas in many of the others | |||
4893 | // it's a Type. | |||
4894 | if (isa<TagDecl>(TagD)) | |||
4895 | Tag = cast<TagDecl>(TagD); | |||
4896 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) | |||
4897 | Tag = CTD->getTemplatedDecl(); | |||
4898 | } | |||
4899 | ||||
4900 | if (Tag) { | |||
4901 | handleTagNumbering(Tag, S); | |||
4902 | Tag->setFreeStanding(); | |||
4903 | if (Tag->isInvalidDecl()) | |||
4904 | return Tag; | |||
4905 | } | |||
4906 | ||||
4907 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | |||
4908 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object | |||
4909 | // or incomplete types shall not be restrict-qualified." | |||
4910 | if (TypeQuals & DeclSpec::TQ_restrict) | |||
4911 | Diag(DS.getRestrictSpecLoc(), | |||
4912 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) | |||
4913 | << DS.getSourceRange(); | |||
4914 | } | |||
4915 | ||||
4916 | if (DS.isInlineSpecified()) | |||
4917 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | |||
4918 | << getLangOpts().CPlusPlus17; | |||
4919 | ||||
4920 | if (DS.hasConstexprSpecifier()) { | |||
4921 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations | |||
4922 | // and definitions of functions and variables. | |||
4923 | // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to | |||
4924 | // the declaration of a function or function template | |||
4925 | if (Tag) | |||
4926 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) | |||
4927 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) | |||
4928 | << static_cast<int>(DS.getConstexprSpecifier()); | |||
4929 | else | |||
4930 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) | |||
4931 | << static_cast<int>(DS.getConstexprSpecifier()); | |||
4932 | // Don't emit warnings after this error. | |||
4933 | return TagD; | |||
4934 | } | |||
4935 | ||||
4936 | DiagnoseFunctionSpecifiers(DS); | |||
4937 | ||||
4938 | if (DS.isFriendSpecified()) { | |||
4939 | // If we're dealing with a decl but not a TagDecl, assume that | |||
4940 | // whatever routines created it handled the friendship aspect. | |||
4941 | if (TagD && !Tag) | |||
4942 | return nullptr; | |||
4943 | return ActOnFriendTypeDecl(S, DS, TemplateParams); | |||
4944 | } | |||
4945 | ||||
4946 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); | |||
4947 | bool IsExplicitSpecialization = | |||
4948 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; | |||
4949 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && | |||
4950 | !IsExplicitInstantiation && !IsExplicitSpecialization && | |||
4951 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { | |||
4952 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a | |||
4953 | // nested-name-specifier unless it is an explicit instantiation | |||
4954 | // or an explicit specialization. | |||
4955 | // | |||
4956 | // FIXME: We allow class template partial specializations here too, per the | |||
4957 | // obvious intent of DR1819. | |||
4958 | // | |||
4959 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. | |||
4960 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) | |||
4961 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); | |||
4962 | return nullptr; | |||
4963 | } | |||
4964 | ||||
4965 | // Track whether this decl-specifier declares anything. | |||
4966 | bool DeclaresAnything = true; | |||
4967 | ||||
4968 | // Handle anonymous struct definitions. | |||
4969 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { | |||
4970 | if (!Record->getDeclName() && Record->isCompleteDefinition() && | |||
4971 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { | |||
4972 | if (getLangOpts().CPlusPlus || | |||
4973 | Record->getDeclContext()->isRecord()) { | |||
4974 | // If CurContext is a DeclContext that can contain statements, | |||
4975 | // RecursiveASTVisitor won't visit the decls that | |||
4976 | // BuildAnonymousStructOrUnion() will put into CurContext. | |||
4977 | // Also store them here so that they can be part of the | |||
4978 | // DeclStmt that gets created in this case. | |||
4979 | // FIXME: Also return the IndirectFieldDecls created by | |||
4980 | // BuildAnonymousStructOr union, for the same reason? | |||
4981 | if (CurContext->isFunctionOrMethod()) | |||
4982 | AnonRecord = Record; | |||
4983 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, | |||
4984 | Context.getPrintingPolicy()); | |||
4985 | } | |||
4986 | ||||
4987 | DeclaresAnything = false; | |||
4988 | } | |||
4989 | } | |||
4990 | ||||
4991 | // C11 6.7.2.1p2: | |||
4992 | // A struct-declaration that does not declare an anonymous structure or | |||
4993 | // anonymous union shall contain a struct-declarator-list. | |||
4994 | // | |||
4995 | // This rule also existed in C89 and C99; the grammar for struct-declaration | |||
4996 | // did not permit a struct-declaration without a struct-declarator-list. | |||
4997 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && | |||
4998 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { | |||
4999 | // Check for Microsoft C extension: anonymous struct/union member. | |||
5000 | // Handle 2 kinds of anonymous struct/union: | |||
5001 | // struct STRUCT; | |||
5002 | // union UNION; | |||
5003 | // and | |||
5004 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. | |||
5005 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. | |||
5006 | if ((Tag && Tag->getDeclName()) || | |||
5007 | DS.getTypeSpecType() == DeclSpec::TST_typename) { | |||
5008 | RecordDecl *Record = nullptr; | |||
5009 | if (Tag) | |||
5010 | Record = dyn_cast<RecordDecl>(Tag); | |||
5011 | else if (const RecordType *RT = | |||
5012 | DS.getRepAsType().get()->getAsStructureType()) | |||
5013 | Record = RT->getDecl(); | |||
5014 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) | |||
5015 | Record = UT->getDecl(); | |||
5016 | ||||
5017 | if (Record && getLangOpts().MicrosoftExt) { | |||
5018 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) | |||
5019 | << Record->isUnion() << DS.getSourceRange(); | |||
5020 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); | |||
5021 | } | |||
5022 | ||||
5023 | DeclaresAnything = false; | |||
5024 | } | |||
5025 | } | |||
5026 | ||||
5027 | // Skip all the checks below if we have a type error. | |||
5028 | if (DS.getTypeSpecType() == DeclSpec::TST_error || | |||
5029 | (TagD && TagD->isInvalidDecl())) | |||
5030 | return TagD; | |||
5031 | ||||
5032 | if (getLangOpts().CPlusPlus && | |||
5033 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) | |||
5034 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) | |||
5035 | if (Enum->enumerator_begin() == Enum->enumerator_end() && | |||
5036 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) | |||
5037 | DeclaresAnything = false; | |||
5038 | ||||
5039 | if (!DS.isMissingDeclaratorOk()) { | |||
5040 | // Customize diagnostic for a typedef missing a name. | |||
5041 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
5042 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) | |||
5043 | << DS.getSourceRange(); | |||
5044 | else | |||
5045 | DeclaresAnything = false; | |||
5046 | } | |||
5047 | ||||
5048 | if (DS.isModulePrivateSpecified() && | |||
5049 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) | |||
5050 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) | |||
5051 | << Tag->getTagKind() | |||
5052 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); | |||
5053 | ||||
5054 | ActOnDocumentableDecl(TagD); | |||
5055 | ||||
5056 | // C 6.7/2: | |||
5057 | // A declaration [...] shall declare at least a declarator [...], a tag, | |||
5058 | // or the members of an enumeration. | |||
5059 | // C++ [dcl.dcl]p3: | |||
5060 | // [If there are no declarators], and except for the declaration of an | |||
5061 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | |||
5062 | // names into the program, or shall redeclare a name introduced by a | |||
5063 | // previous declaration. | |||
5064 | if (!DeclaresAnything) { | |||
5065 | // In C, we allow this as a (popular) extension / bug. Don't bother | |||
5066 | // producing further diagnostics for redundant qualifiers after this. | |||
5067 | Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) | |||
5068 | ? diag::err_no_declarators | |||
5069 | : diag::ext_no_declarators) | |||
5070 | << DS.getSourceRange(); | |||
5071 | return TagD; | |||
5072 | } | |||
5073 | ||||
5074 | // C++ [dcl.stc]p1: | |||
5075 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the | |||
5076 | // init-declarator-list of the declaration shall not be empty. | |||
5077 | // C++ [dcl.fct.spec]p1: | |||
5078 | // If a cv-qualifier appears in a decl-specifier-seq, the | |||
5079 | // init-declarator-list of the declaration shall not be empty. | |||
5080 | // | |||
5081 | // Spurious qualifiers here appear to be valid in C. | |||
5082 | unsigned DiagID = diag::warn_standalone_specifier; | |||
5083 | if (getLangOpts().CPlusPlus) | |||
5084 | DiagID = diag::ext_standalone_specifier; | |||
5085 | ||||
5086 | // Note that a linkage-specification sets a storage class, but | |||
5087 | // 'extern "C" struct foo;' is actually valid and not theoretically | |||
5088 | // useless. | |||
5089 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { | |||
5090 | if (SCS == DeclSpec::SCS_mutable) | |||
5091 | // Since mutable is not a viable storage class specifier in C, there is | |||
5092 | // no reason to treat it as an extension. Instead, diagnose as an error. | |||
5093 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); | |||
5094 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) | |||
5095 | Diag(DS.getStorageClassSpecLoc(), DiagID) | |||
5096 | << DeclSpec::getSpecifierName(SCS); | |||
5097 | } | |||
5098 | ||||
5099 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | |||
5100 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) | |||
5101 | << DeclSpec::getSpecifierName(TSCS); | |||
5102 | if (DS.getTypeQualifiers()) { | |||
5103 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | |||
5104 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; | |||
5105 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | |||
5106 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; | |||
5107 | // Restrict is covered above. | |||
5108 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | |||
5109 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; | |||
5110 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | |||
5111 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; | |||
5112 | } | |||
5113 | ||||
5114 | // Warn about ignored type attributes, for example: | |||
5115 | // __attribute__((aligned)) struct A; | |||
5116 | // Attributes should be placed after tag to apply to type declaration. | |||
5117 | if (!DS.getAttributes().empty()) { | |||
5118 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); | |||
5119 | if (TypeSpecType == DeclSpec::TST_class || | |||
5120 | TypeSpecType == DeclSpec::TST_struct || | |||
5121 | TypeSpecType == DeclSpec::TST_interface || | |||
5122 | TypeSpecType == DeclSpec::TST_union || | |||
5123 | TypeSpecType == DeclSpec::TST_enum) { | |||
5124 | for (const ParsedAttr &AL : DS.getAttributes()) | |||
5125 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) | |||
5126 | << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); | |||
5127 | } | |||
5128 | } | |||
5129 | ||||
5130 | return TagD; | |||
5131 | } | |||
5132 | ||||
5133 | /// We are trying to inject an anonymous member into the given scope; | |||
5134 | /// check if there's an existing declaration that can't be overloaded. | |||
5135 | /// | |||
5136 | /// \return true if this is a forbidden redeclaration | |||
5137 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, | |||
5138 | Scope *S, | |||
5139 | DeclContext *Owner, | |||
5140 | DeclarationName Name, | |||
5141 | SourceLocation NameLoc, | |||
5142 | bool IsUnion) { | |||
5143 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, | |||
5144 | Sema::ForVisibleRedeclaration); | |||
5145 | if (!SemaRef.LookupName(R, S)) return false; | |||
5146 | ||||
5147 | // Pick a representative declaration. | |||
5148 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); | |||
5149 | assert(PrevDecl && "Expected a non-null Decl")(static_cast <bool> (PrevDecl && "Expected a non-null Decl" ) ? void (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\"" , "clang/lib/Sema/SemaDecl.cpp", 5149, __extension__ __PRETTY_FUNCTION__ )); | |||
5150 | ||||
5151 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) | |||
5152 | return false; | |||
5153 | ||||
5154 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) | |||
5155 | << IsUnion << Name; | |||
5156 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
5157 | ||||
5158 | return true; | |||
5159 | } | |||
5160 | ||||
5161 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the | |||
5162 | /// anonymous struct or union AnonRecord into the owning context Owner | |||
5163 | /// and scope S. This routine will be invoked just after we realize | |||
5164 | /// that an unnamed union or struct is actually an anonymous union or | |||
5165 | /// struct, e.g., | |||
5166 | /// | |||
5167 | /// @code | |||
5168 | /// union { | |||
5169 | /// int i; | |||
5170 | /// float f; | |||
5171 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and | |||
5172 | /// // f into the surrounding scope.x | |||
5173 | /// @endcode | |||
5174 | /// | |||
5175 | /// This routine is recursive, injecting the names of nested anonymous | |||
5176 | /// structs/unions into the owning context and scope as well. | |||
5177 | static bool | |||
5178 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, | |||
5179 | RecordDecl *AnonRecord, AccessSpecifier AS, | |||
5180 | SmallVectorImpl<NamedDecl *> &Chaining) { | |||
5181 | bool Invalid = false; | |||
5182 | ||||
5183 | // Look every FieldDecl and IndirectFieldDecl with a name. | |||
5184 | for (auto *D : AnonRecord->decls()) { | |||
5185 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && | |||
5186 | cast<NamedDecl>(D)->getDeclName()) { | |||
5187 | ValueDecl *VD = cast<ValueDecl>(D); | |||
5188 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), | |||
5189 | VD->getLocation(), | |||
5190 | AnonRecord->isUnion())) { | |||
5191 | // C++ [class.union]p2: | |||
5192 | // The names of the members of an anonymous union shall be | |||
5193 | // distinct from the names of any other entity in the | |||
5194 | // scope in which the anonymous union is declared. | |||
5195 | Invalid = true; | |||
5196 | } else { | |||
5197 | // C++ [class.union]p2: | |||
5198 | // For the purpose of name lookup, after the anonymous union | |||
5199 | // definition, the members of the anonymous union are | |||
5200 | // considered to have been defined in the scope in which the | |||
5201 | // anonymous union is declared. | |||
5202 | unsigned OldChainingSize = Chaining.size(); | |||
5203 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) | |||
5204 | Chaining.append(IF->chain_begin(), IF->chain_end()); | |||
5205 | else | |||
5206 | Chaining.push_back(VD); | |||
5207 | ||||
5208 | assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0 ) : __assert_fail ("Chaining.size() >= 2", "clang/lib/Sema/SemaDecl.cpp" , 5208, __extension__ __PRETTY_FUNCTION__)); | |||
5209 | NamedDecl **NamedChain = | |||
5210 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; | |||
5211 | for (unsigned i = 0; i < Chaining.size(); i++) | |||
5212 | NamedChain[i] = Chaining[i]; | |||
5213 | ||||
5214 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( | |||
5215 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), | |||
5216 | VD->getType(), {NamedChain, Chaining.size()}); | |||
5217 | ||||
5218 | for (const auto *Attr : VD->attrs()) | |||
5219 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); | |||
5220 | ||||
5221 | IndirectField->setAccess(AS); | |||
5222 | IndirectField->setImplicit(); | |||
5223 | SemaRef.PushOnScopeChains(IndirectField, S); | |||
5224 | ||||
5225 | // That includes picking up the appropriate access specifier. | |||
5226 | if (AS != AS_none) IndirectField->setAccess(AS); | |||
5227 | ||||
5228 | Chaining.resize(OldChainingSize); | |||
5229 | } | |||
5230 | } | |||
5231 | } | |||
5232 | ||||
5233 | return Invalid; | |||
5234 | } | |||
5235 | ||||
5236 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to | |||
5237 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: | |||
5238 | /// illegal input values are mapped to SC_None. | |||
5239 | static StorageClass | |||
5240 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { | |||
5241 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); | |||
5242 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "clang/lib/Sema/SemaDecl.cpp", 5243, __extension__ __PRETTY_FUNCTION__ )) | |||
5243 | "Parser allowed 'typedef' as storage class VarDecl.")(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "clang/lib/Sema/SemaDecl.cpp", 5243, __extension__ __PRETTY_FUNCTION__ )); | |||
5244 | switch (StorageClassSpec) { | |||
5245 | case DeclSpec::SCS_unspecified: return SC_None; | |||
5246 | case DeclSpec::SCS_extern: | |||
5247 | if (DS.isExternInLinkageSpec()) | |||
5248 | return SC_None; | |||
5249 | return SC_Extern; | |||
5250 | case DeclSpec::SCS_static: return SC_Static; | |||
5251 | case DeclSpec::SCS_auto: return SC_Auto; | |||
5252 | case DeclSpec::SCS_register: return SC_Register; | |||
5253 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | |||
5254 | // Illegal SCSs map to None: error reporting is up to the caller. | |||
5255 | case DeclSpec::SCS_mutable: // Fall through. | |||
5256 | case DeclSpec::SCS_typedef: return SC_None; | |||
5257 | } | |||
5258 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "clang/lib/Sema/SemaDecl.cpp", 5258); | |||
5259 | } | |||
5260 | ||||
5261 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { | |||
5262 | assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer() ) ? void (0) : __assert_fail ("Record->hasInClassInitializer()" , "clang/lib/Sema/SemaDecl.cpp", 5262, __extension__ __PRETTY_FUNCTION__ )); | |||
5263 | ||||
5264 | for (const auto *I : Record->decls()) { | |||
5265 | const auto *FD = dyn_cast<FieldDecl>(I); | |||
5266 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | |||
5267 | FD = IFD->getAnonField(); | |||
5268 | if (FD && FD->hasInClassInitializer()) | |||
5269 | return FD->getLocation(); | |||
5270 | } | |||
5271 | ||||
5272 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "clang/lib/Sema/SemaDecl.cpp", 5272); | |||
5273 | } | |||
5274 | ||||
5275 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | |||
5276 | SourceLocation DefaultInitLoc) { | |||
5277 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | |||
5278 | return; | |||
5279 | ||||
5280 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); | |||
5281 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; | |||
5282 | } | |||
5283 | ||||
5284 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | |||
5285 | CXXRecordDecl *AnonUnion) { | |||
5286 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | |||
5287 | return; | |||
5288 | ||||
5289 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); | |||
5290 | } | |||
5291 | ||||
5292 | /// BuildAnonymousStructOrUnion - Handle the declaration of an | |||
5293 | /// anonymous structure or union. Anonymous unions are a C++ feature | |||
5294 | /// (C++ [class.union]) and a C11 feature; anonymous structures | |||
5295 | /// are a C11 feature and GNU C++ extension. | |||
5296 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | |||
5297 | AccessSpecifier AS, | |||
5298 | RecordDecl *Record, | |||
5299 | const PrintingPolicy &Policy) { | |||
5300 | DeclContext *Owner = Record->getDeclContext(); | |||
5301 | ||||
5302 | // Diagnose whether this anonymous struct/union is an extension. | |||
5303 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) | |||
5304 | Diag(Record->getLocation(), diag::ext_anonymous_union); | |||
5305 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) | |||
5306 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); | |||
5307 | else if (!Record->isUnion() && !getLangOpts().C11) | |||
5308 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); | |||
5309 | ||||
5310 | // C and C++ require different kinds of checks for anonymous | |||
5311 | // structs/unions. | |||
5312 | bool Invalid = false; | |||
5313 | if (getLangOpts().CPlusPlus) { | |||
5314 | const char *PrevSpec = nullptr; | |||
5315 | if (Record->isUnion()) { | |||
5316 | // C++ [class.union]p6: | |||
5317 | // C++17 [class.union.anon]p2: | |||
5318 | // Anonymous unions declared in a named namespace or in the | |||
5319 | // global namespace shall be declared static. | |||
5320 | unsigned DiagID; | |||
5321 | DeclContext *OwnerScope = Owner->getRedeclContext(); | |||
5322 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && | |||
5323 | (OwnerScope->isTranslationUnit() || | |||
5324 | (OwnerScope->isNamespace() && | |||
5325 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { | |||
5326 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) | |||
5327 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); | |||
5328 | ||||
5329 | // Recover by adding 'static'. | |||
5330 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), | |||
5331 | PrevSpec, DiagID, Policy); | |||
5332 | } | |||
5333 | // C++ [class.union]p6: | |||
5334 | // A storage class is not allowed in a declaration of an | |||
5335 | // anonymous union in a class scope. | |||
5336 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && | |||
5337 | isa<RecordDecl>(Owner)) { | |||
5338 | Diag(DS.getStorageClassSpecLoc(), | |||
5339 | diag::err_anonymous_union_with_storage_spec) | |||
5340 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
5341 | ||||
5342 | // Recover by removing the storage specifier. | |||
5343 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, | |||
5344 | SourceLocation(), | |||
5345 | PrevSpec, DiagID, Context.getPrintingPolicy()); | |||
5346 | } | |||
5347 | } | |||
5348 | ||||
5349 | // Ignore const/volatile/restrict qualifiers. | |||
5350 | if (DS.getTypeQualifiers()) { | |||
5351 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | |||
5352 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) | |||
5353 | << Record->isUnion() << "const" | |||
5354 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); | |||
5355 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | |||
5356 | Diag(DS.getVolatileSpecLoc(), | |||
5357 | diag::ext_anonymous_struct_union_qualified) | |||
5358 | << Record->isUnion() << "volatile" | |||
5359 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); | |||
5360 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | |||
5361 | Diag(DS.getRestrictSpecLoc(), | |||
5362 | diag::ext_anonymous_struct_union_qualified) | |||
5363 | << Record->isUnion() << "restrict" | |||
5364 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); | |||
5365 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | |||
5366 | Diag(DS.getAtomicSpecLoc(), | |||
5367 | diag::ext_anonymous_struct_union_qualified) | |||
5368 | << Record->isUnion() << "_Atomic" | |||
5369 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); | |||
5370 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | |||
5371 | Diag(DS.getUnalignedSpecLoc(), | |||
5372 | diag::ext_anonymous_struct_union_qualified) | |||
5373 | << Record->isUnion() << "__unaligned" | |||
5374 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); | |||
5375 | ||||
5376 | DS.ClearTypeQualifiers(); | |||
5377 | } | |||
5378 | ||||
5379 | // C++ [class.union]p2: | |||
5380 | // The member-specification of an anonymous union shall only | |||
5381 | // define non-static data members. [Note: nested types and | |||
5382 | // functions cannot be declared within an anonymous union. ] | |||
5383 | for (auto *Mem : Record->decls()) { | |||
5384 | // Ignore invalid declarations; we already diagnosed them. | |||
5385 | if (Mem->isInvalidDecl()) | |||
5386 | continue; | |||
5387 | ||||
5388 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { | |||
5389 | // C++ [class.union]p3: | |||
5390 | // An anonymous union shall not have private or protected | |||
5391 | // members (clause 11). | |||
5392 | assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void (0) : __assert_fail ("FD->getAccess() != AS_none", "clang/lib/Sema/SemaDecl.cpp" , 5392, __extension__ __PRETTY_FUNCTION__)); | |||
5393 | if (FD->getAccess() != AS_public) { | |||
5394 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) | |||
5395 | << Record->isUnion() << (FD->getAccess() == AS_protected); | |||
5396 | Invalid = true; | |||
5397 | } | |||
5398 | ||||
5399 | // C++ [class.union]p1 | |||
5400 | // An object of a class with a non-trivial constructor, a non-trivial | |||
5401 | // copy constructor, a non-trivial destructor, or a non-trivial copy | |||
5402 | // assignment operator cannot be a member of a union, nor can an | |||
5403 | // array of such objects. | |||
5404 | if (CheckNontrivialField(FD)) | |||
5405 | Invalid = true; | |||
5406 | } else if (Mem->isImplicit()) { | |||
5407 | // Any implicit members are fine. | |||
5408 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { | |||
5409 | // This is a type that showed up in an | |||
5410 | // elaborated-type-specifier inside the anonymous struct or | |||
5411 | // union, but which actually declares a type outside of the | |||
5412 | // anonymous struct or union. It's okay. | |||
5413 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { | |||
5414 | if (!MemRecord->isAnonymousStructOrUnion() && | |||
5415 | MemRecord->getDeclName()) { | |||
5416 | // Visual C++ allows type definition in anonymous struct or union. | |||
5417 | if (getLangOpts().MicrosoftExt) | |||
5418 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) | |||
5419 | << Record->isUnion(); | |||
5420 | else { | |||
5421 | // This is a nested type declaration. | |||
5422 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) | |||
5423 | << Record->isUnion(); | |||
5424 | Invalid = true; | |||
5425 | } | |||
5426 | } else { | |||
5427 | // This is an anonymous type definition within another anonymous type. | |||
5428 | // This is a popular extension, provided by Plan9, MSVC and GCC, but | |||
5429 | // not part of standard C++. | |||
5430 | Diag(MemRecord->getLocation(), | |||
5431 | diag::ext_anonymous_record_with_anonymous_type) | |||
5432 | << Record->isUnion(); | |||
5433 | } | |||
5434 | } else if (isa<AccessSpecDecl>(Mem)) { | |||
5435 | // Any access specifier is fine. | |||
5436 | } else if (isa<StaticAssertDecl>(Mem)) { | |||
5437 | // In C++1z, static_assert declarations are also fine. | |||
5438 | } else { | |||
5439 | // We have something that isn't a non-static data | |||
5440 | // member. Complain about it. | |||
5441 | unsigned DK = diag::err_anonymous_record_bad_member; | |||
5442 | if (isa<TypeDecl>(Mem)) | |||
5443 | DK = diag::err_anonymous_record_with_type; | |||
5444 | else if (isa<FunctionDecl>(Mem)) | |||
5445 | DK = diag::err_anonymous_record_with_function; | |||
5446 | else if (isa<VarDecl>(Mem)) | |||
5447 | DK = diag::err_anonymous_record_with_static; | |||
5448 | ||||
5449 | // Visual C++ allows type definition in anonymous struct or union. | |||
5450 | if (getLangOpts().MicrosoftExt && | |||
5451 | DK == diag::err_anonymous_record_with_type) | |||
5452 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) | |||
5453 | << Record->isUnion(); | |||
5454 | else { | |||
5455 | Diag(Mem->getLocation(), DK) << Record->isUnion(); | |||
5456 | Invalid = true; | |||
5457 | } | |||
5458 | } | |||
5459 | } | |||
5460 | ||||
5461 | // C++11 [class.union]p8 (DR1460): | |||
5462 | // At most one variant member of a union may have a | |||
5463 | // brace-or-equal-initializer. | |||
5464 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && | |||
5465 | Owner->isRecord()) | |||
5466 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), | |||
5467 | cast<CXXRecordDecl>(Record)); | |||
5468 | } | |||
5469 | ||||
5470 | if (!Record->isUnion() && !Owner->isRecord()) { | |||
5471 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) | |||
5472 | << getLangOpts().CPlusPlus; | |||
5473 | Invalid = true; | |||
5474 | } | |||
5475 | ||||
5476 | // C++ [dcl.dcl]p3: | |||
5477 | // [If there are no declarators], and except for the declaration of an | |||
5478 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | |||
5479 | // names into the program | |||
5480 | // C++ [class.mem]p2: | |||
5481 | // each such member-declaration shall either declare at least one member | |||
5482 | // name of the class or declare at least one unnamed bit-field | |||
5483 | // | |||
5484 | // For C this is an error even for a named struct, and is diagnosed elsewhere. | |||
5485 | if (getLangOpts().CPlusPlus && Record->field_empty()) | |||
5486 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | |||
5487 | ||||
5488 | // Mock up a declarator. | |||
5489 | Declarator Dc(DS, DeclaratorContext::Member); | |||
5490 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | |||
5491 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct/union" ) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"" , "clang/lib/Sema/SemaDecl.cpp", 5491, __extension__ __PRETTY_FUNCTION__ )); | |||
5492 | ||||
5493 | // Create a declaration for this anonymous struct/union. | |||
5494 | NamedDecl *Anon = nullptr; | |||
5495 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { | |||
5496 | Anon = FieldDecl::Create( | |||
5497 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), | |||
5498 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, | |||
5499 | /*BitWidth=*/nullptr, /*Mutable=*/false, | |||
5500 | /*InitStyle=*/ICIS_NoInit); | |||
5501 | Anon->setAccess(AS); | |||
5502 | ProcessDeclAttributes(S, Anon, Dc); | |||
5503 | ||||
5504 | if (getLangOpts().CPlusPlus) | |||
5505 | FieldCollector->Add(cast<FieldDecl>(Anon)); | |||
5506 | } else { | |||
5507 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); | |||
5508 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); | |||
5509 | if (SCSpec == DeclSpec::SCS_mutable) { | |||
5510 | // mutable can only appear on non-static class members, so it's always | |||
5511 | // an error here | |||
5512 | Diag(Record->getLocation(), diag::err_mutable_nonmember); | |||
5513 | Invalid = true; | |||
5514 | SC = SC_None; | |||
5515 | } | |||
5516 | ||||
5517 | assert(DS.getAttributes().empty() && "No attribute expected")(static_cast <bool> (DS.getAttributes().empty() && "No attribute expected") ? void (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\"" , "clang/lib/Sema/SemaDecl.cpp", 5517, __extension__ __PRETTY_FUNCTION__ )); | |||
5518 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), | |||
5519 | Record->getLocation(), /*IdentifierInfo=*/nullptr, | |||
5520 | Context.getTypeDeclType(Record), TInfo, SC); | |||
5521 | ||||
5522 | // Default-initialize the implicit variable. This initialization will be | |||
5523 | // trivial in almost all cases, except if a union member has an in-class | |||
5524 | // initializer: | |||
5525 | // union { int n = 0; }; | |||
5526 | ActOnUninitializedDecl(Anon); | |||
5527 | } | |||
5528 | Anon->setImplicit(); | |||
5529 | ||||
5530 | // Mark this as an anonymous struct/union type. | |||
5531 | Record->setAnonymousStructOrUnion(true); | |||
5532 | ||||
5533 | // Add the anonymous struct/union object to the current | |||
5534 | // context. We'll be referencing this object when we refer to one of | |||
5535 | // its members. | |||
5536 | Owner->addDecl(Anon); | |||
5537 | ||||
5538 | // Inject the members of the anonymous struct/union into the owning | |||
5539 | // context and into the identifier resolver chain for name lookup | |||
5540 | // purposes. | |||
5541 | SmallVector<NamedDecl*, 2> Chain; | |||
5542 | Chain.push_back(Anon); | |||
5543 | ||||
5544 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) | |||
5545 | Invalid = true; | |||
5546 | ||||
5547 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { | |||
5548 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | |||
5549 | MangleNumberingContext *MCtx; | |||
5550 | Decl *ManglingContextDecl; | |||
5551 | std::tie(MCtx, ManglingContextDecl) = | |||
5552 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | |||
5553 | if (MCtx) { | |||
5554 | Context.setManglingNumber( | |||
5555 | NewVD, MCtx->getManglingNumber( | |||
5556 | NewVD, getMSManglingNumber(getLangOpts(), S))); | |||
5557 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | |||
5558 | } | |||
5559 | } | |||
5560 | } | |||
5561 | ||||
5562 | if (Invalid) | |||
5563 | Anon->setInvalidDecl(); | |||
5564 | ||||
5565 | return Anon; | |||
5566 | } | |||
5567 | ||||
5568 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an | |||
5569 | /// Microsoft C anonymous structure. | |||
5570 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx | |||
5571 | /// Example: | |||
5572 | /// | |||
5573 | /// struct A { int a; }; | |||
5574 | /// struct B { struct A; int b; }; | |||
5575 | /// | |||
5576 | /// void foo() { | |||
5577 | /// B var; | |||
5578 | /// var.a = 3; | |||
5579 | /// } | |||
5580 | /// | |||
5581 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | |||
5582 | RecordDecl *Record) { | |||
5583 | assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!" ) ? void (0) : __assert_fail ("Record && \"expected a record!\"" , "clang/lib/Sema/SemaDecl.cpp", 5583, __extension__ __PRETTY_FUNCTION__ )); | |||
5584 | ||||
5585 | // Mock up a declarator. | |||
5586 | Declarator Dc(DS, DeclaratorContext::TypeName); | |||
5587 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | |||
5588 | assert(TInfo && "couldn't build declarator info for anonymous struct")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct" ) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"" , "clang/lib/Sema/SemaDecl.cpp", 5588, __extension__ __PRETTY_FUNCTION__ )); | |||
5589 | ||||
5590 | auto *ParentDecl = cast<RecordDecl>(CurContext); | |||
5591 | QualType RecTy = Context.getTypeDeclType(Record); | |||
5592 | ||||
5593 | // Create a declaration for this anonymous struct. | |||
5594 | NamedDecl *Anon = | |||
5595 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), | |||
5596 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, | |||
5597 | /*BitWidth=*/nullptr, /*Mutable=*/false, | |||
5598 | /*InitStyle=*/ICIS_NoInit); | |||
5599 | Anon->setImplicit(); | |||
5600 | ||||
5601 | // Add the anonymous struct object to the current context. | |||
5602 | CurContext->addDecl(Anon); | |||
5603 | ||||
5604 | // Inject the members of the anonymous struct into the current | |||
5605 | // context and into the identifier resolver chain for name lookup | |||
5606 | // purposes. | |||
5607 | SmallVector<NamedDecl*, 2> Chain; | |||
5608 | Chain.push_back(Anon); | |||
5609 | ||||
5610 | RecordDecl *RecordDef = Record->getDefinition(); | |||
5611 | if (RequireCompleteSizedType(Anon->getLocation(), RecTy, | |||
5612 | diag::err_field_incomplete_or_sizeless) || | |||
5613 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, | |||
5614 | AS_none, Chain)) { | |||
5615 | Anon->setInvalidDecl(); | |||
5616 | ParentDecl->setInvalidDecl(); | |||
5617 | } | |||
5618 | ||||
5619 | return Anon; | |||
5620 | } | |||
5621 | ||||
5622 | /// GetNameForDeclarator - Determine the full declaration name for the | |||
5623 | /// given Declarator. | |||
5624 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { | |||
5625 | return GetNameFromUnqualifiedId(D.getName()); | |||
5626 | } | |||
5627 | ||||
5628 | /// Retrieves the declaration name from a parsed unqualified-id. | |||
5629 | DeclarationNameInfo | |||
5630 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { | |||
5631 | DeclarationNameInfo NameInfo; | |||
5632 | NameInfo.setLoc(Name.StartLocation); | |||
5633 | ||||
5634 | switch (Name.getKind()) { | |||
5635 | ||||
5636 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
5637 | case UnqualifiedIdKind::IK_Identifier: | |||
5638 | NameInfo.setName(Name.Identifier); | |||
5639 | return NameInfo; | |||
5640 | ||||
5641 | case UnqualifiedIdKind::IK_DeductionGuideName: { | |||
5642 | // C++ [temp.deduct.guide]p3: | |||
5643 | // The simple-template-id shall name a class template specialization. | |||
5644 | // The template-name shall be the same identifier as the template-name | |||
5645 | // of the simple-template-id. | |||
5646 | // These together intend to imply that the template-name shall name a | |||
5647 | // class template. | |||
5648 | // FIXME: template<typename T> struct X {}; | |||
5649 | // template<typename T> using Y = X<T>; | |||
5650 | // Y(int) -> Y<int>; | |||
5651 | // satisfies these rules but does not name a class template. | |||
5652 | TemplateName TN = Name.TemplateName.get().get(); | |||
5653 | auto *Template = TN.getAsTemplateDecl(); | |||
5654 | if (!Template || !isa<ClassTemplateDecl>(Template)) { | |||
5655 | Diag(Name.StartLocation, | |||
5656 | diag::err_deduction_guide_name_not_class_template) | |||
5657 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; | |||
5658 | if (Template) | |||
5659 | Diag(Template->getLocation(), diag::note_template_decl_here); | |||
5660 | return DeclarationNameInfo(); | |||
5661 | } | |||
5662 | ||||
5663 | NameInfo.setName( | |||
5664 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); | |||
5665 | return NameInfo; | |||
5666 | } | |||
5667 | ||||
5668 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
5669 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( | |||
5670 | Name.OperatorFunctionId.Operator)); | |||
5671 | NameInfo.setCXXOperatorNameRange(SourceRange( | |||
5672 | Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation)); | |||
5673 | return NameInfo; | |||
5674 | ||||
5675 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
5676 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( | |||
5677 | Name.Identifier)); | |||
5678 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); | |||
5679 | return NameInfo; | |||
5680 | ||||
5681 | case UnqualifiedIdKind::IK_ConversionFunctionId: { | |||
5682 | TypeSourceInfo *TInfo; | |||
5683 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); | |||
5684 | if (Ty.isNull()) | |||
5685 | return DeclarationNameInfo(); | |||
5686 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( | |||
5687 | Context.getCanonicalType(Ty))); | |||
5688 | NameInfo.setNamedTypeInfo(TInfo); | |||
5689 | return NameInfo; | |||
5690 | } | |||
5691 | ||||
5692 | case UnqualifiedIdKind::IK_ConstructorName: { | |||
5693 | TypeSourceInfo *TInfo; | |||
5694 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); | |||
5695 | if (Ty.isNull()) | |||
5696 | return DeclarationNameInfo(); | |||
5697 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | |||
5698 | Context.getCanonicalType(Ty))); | |||
5699 | NameInfo.setNamedTypeInfo(TInfo); | |||
5700 | return NameInfo; | |||
5701 | } | |||
5702 | ||||
5703 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { | |||
5704 | // In well-formed code, we can only have a constructor | |||
5705 | // template-id that refers to the current context, so go there | |||
5706 | // to find the actual type being constructed. | |||
5707 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); | |||
5708 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) | |||
5709 | return DeclarationNameInfo(); | |||
5710 | ||||
5711 | // Determine the type of the class being constructed. | |||
5712 | QualType CurClassType = Context.getTypeDeclType(CurClass); | |||
5713 | ||||
5714 | // FIXME: Check two things: that the template-id names the same type as | |||
5715 | // CurClassType, and that the template-id does not occur when the name | |||
5716 | // was qualified. | |||
5717 | ||||
5718 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | |||
5719 | Context.getCanonicalType(CurClassType))); | |||
5720 | // FIXME: should we retrieve TypeSourceInfo? | |||
5721 | NameInfo.setNamedTypeInfo(nullptr); | |||
5722 | return NameInfo; | |||
5723 | } | |||
5724 | ||||
5725 | case UnqualifiedIdKind::IK_DestructorName: { | |||
5726 | TypeSourceInfo *TInfo; | |||
5727 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); | |||
5728 | if (Ty.isNull()) | |||
5729 | return DeclarationNameInfo(); | |||
5730 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( | |||
5731 | Context.getCanonicalType(Ty))); | |||
5732 | NameInfo.setNamedTypeInfo(TInfo); | |||
5733 | return NameInfo; | |||
5734 | } | |||
5735 | ||||
5736 | case UnqualifiedIdKind::IK_TemplateId: { | |||
5737 | TemplateName TName = Name.TemplateId->Template.get(); | |||
5738 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; | |||
5739 | return Context.getNameForTemplate(TName, TNameLoc); | |||
5740 | } | |||
5741 | ||||
5742 | } // switch (Name.getKind()) | |||
5743 | ||||
5744 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "clang/lib/Sema/SemaDecl.cpp" , 5744); | |||
5745 | } | |||
5746 | ||||
5747 | static QualType getCoreType(QualType Ty) { | |||
5748 | do { | |||
5749 | if (Ty->isPointerType() || Ty->isReferenceType()) | |||
5750 | Ty = Ty->getPointeeType(); | |||
5751 | else if (Ty->isArrayType()) | |||
5752 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); | |||
5753 | else | |||
5754 | return Ty.withoutLocalFastQualifiers(); | |||
5755 | } while (true); | |||
5756 | } | |||
5757 | ||||
5758 | /// hasSimilarParameters - Determine whether the C++ functions Declaration | |||
5759 | /// and Definition have "nearly" matching parameters. This heuristic is | |||
5760 | /// used to improve diagnostics in the case where an out-of-line function | |||
5761 | /// definition doesn't match any declaration within the class or namespace. | |||
5762 | /// Also sets Params to the list of indices to the parameters that differ | |||
5763 | /// between the declaration and the definition. If hasSimilarParameters | |||
5764 | /// returns true and Params is empty, then all of the parameters match. | |||
5765 | static bool hasSimilarParameters(ASTContext &Context, | |||
5766 | FunctionDecl *Declaration, | |||
5767 | FunctionDecl *Definition, | |||
5768 | SmallVectorImpl<unsigned> &Params) { | |||
5769 | Params.clear(); | |||
5770 | if (Declaration->param_size() != Definition->param_size()) | |||
5771 | return false; | |||
5772 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { | |||
5773 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); | |||
5774 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); | |||
5775 | ||||
5776 | // The parameter types are identical | |||
5777 | if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) | |||
5778 | continue; | |||
5779 | ||||
5780 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); | |||
5781 | QualType DefParamBaseTy = getCoreType(DefParamTy); | |||
5782 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); | |||
5783 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); | |||
5784 | ||||
5785 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || | |||
5786 | (DeclTyName && DeclTyName == DefTyName)) | |||
5787 | Params.push_back(Idx); | |||
5788 | else // The two parameters aren't even close | |||
5789 | return false; | |||
5790 | } | |||
5791 | ||||
5792 | return true; | |||
5793 | } | |||
5794 | ||||
5795 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given | |||
5796 | /// declarator needs to be rebuilt in the current instantiation. | |||
5797 | /// Any bits of declarator which appear before the name are valid for | |||
5798 | /// consideration here. That's specifically the type in the decl spec | |||
5799 | /// and the base type in any member-pointer chunks. | |||
5800 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, | |||
5801 | DeclarationName Name) { | |||
5802 | // The types we specifically need to rebuild are: | |||
5803 | // - typenames, typeofs, and decltypes | |||
5804 | // - types which will become injected class names | |||
5805 | // Of course, we also need to rebuild any type referencing such a | |||
5806 | // type. It's safest to just say "dependent", but we call out a | |||
5807 | // few cases here. | |||
5808 | ||||
5809 | DeclSpec &DS = D.getMutableDeclSpec(); | |||
5810 | switch (DS.getTypeSpecType()) { | |||
5811 | case DeclSpec::TST_typename: | |||
5812 | case DeclSpec::TST_typeofType: | |||
5813 | case DeclSpec::TST_underlyingType: | |||
5814 | case DeclSpec::TST_atomic: { | |||
5815 | // Grab the type from the parser. | |||
5816 | TypeSourceInfo *TSI = nullptr; | |||
5817 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); | |||
5818 | if (T.isNull() || !T->isInstantiationDependentType()) break; | |||
5819 | ||||
5820 | // Make sure there's a type source info. This isn't really much | |||
5821 | // of a waste; most dependent types should have type source info | |||
5822 | // attached already. | |||
5823 | if (!TSI) | |||
5824 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); | |||
5825 | ||||
5826 | // Rebuild the type in the current instantiation. | |||
5827 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); | |||
5828 | if (!TSI) return true; | |||
5829 | ||||
5830 | // Store the new type back in the decl spec. | |||
5831 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); | |||
5832 | DS.UpdateTypeRep(LocType); | |||
5833 | break; | |||
5834 | } | |||
5835 | ||||
5836 | case DeclSpec::TST_decltype: | |||
5837 | case DeclSpec::TST_typeofExpr: { | |||
5838 | Expr *E = DS.getRepAsExpr(); | |||
5839 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); | |||
5840 | if (Result.isInvalid()) return true; | |||
5841 | DS.UpdateExprRep(Result.get()); | |||
5842 | break; | |||
5843 | } | |||
5844 | ||||
5845 | default: | |||
5846 | // Nothing to do for these decl specs. | |||
5847 | break; | |||
5848 | } | |||
5849 | ||||
5850 | // It doesn't matter what order we do this in. | |||
5851 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | |||
5852 | DeclaratorChunk &Chunk = D.getTypeObject(I); | |||
5853 | ||||
5854 | // The only type information in the declarator which can come | |||
5855 | // before the declaration name is the base type of a member | |||
5856 | // pointer. | |||
5857 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) | |||
5858 | continue; | |||
5859 | ||||
5860 | // Rebuild the scope specifier in-place. | |||
5861 | CXXScopeSpec &SS = Chunk.Mem.Scope(); | |||
5862 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) | |||
5863 | return true; | |||
5864 | } | |||
5865 | ||||
5866 | return false; | |||
5867 | } | |||
5868 | ||||
5869 | /// Returns true if the declaration is declared in a system header or from a | |||
5870 | /// system macro. | |||
5871 | static bool isFromSystemHeader(SourceManager &SM, const Decl *D) { | |||
5872 | return SM.isInSystemHeader(D->getLocation()) || | |||
5873 | SM.isInSystemMacro(D->getLocation()); | |||
5874 | } | |||
5875 | ||||
5876 | void Sema::warnOnReservedIdentifier(const NamedDecl *D) { | |||
5877 | // Avoid warning twice on the same identifier, and don't warn on redeclaration | |||
5878 | // of system decl. | |||
5879 | if (D->getPreviousDecl() || D->isImplicit()) | |||
5880 | return; | |||
5881 | ReservedIdentifierStatus Status = D->isReserved(getLangOpts()); | |||
5882 | if (Status != ReservedIdentifierStatus::NotReserved && | |||
5883 | !isFromSystemHeader(Context.getSourceManager(), D)) { | |||
5884 | Diag(D->getLocation(), diag::warn_reserved_extern_symbol) | |||
5885 | << D << static_cast<int>(Status); | |||
5886 | } | |||
5887 | } | |||
5888 | ||||
5889 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { | |||
5890 | D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); | |||
5891 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); | |||
5892 | ||||
5893 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && | |||
5894 | Dcl && Dcl->getDeclContext()->isFileContext()) | |||
5895 | Dcl->setTopLevelDeclInObjCContainer(); | |||
5896 | ||||
5897 | return Dcl; | |||
5898 | } | |||
5899 | ||||
5900 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: | |||
5901 | /// If T is the name of a class, then each of the following shall have a | |||
5902 | /// name different from T: | |||
5903 | /// - every static data member of class T; | |||
5904 | /// - every member function of class T | |||
5905 | /// - every member of class T that is itself a type; | |||
5906 | /// \returns true if the declaration name violates these rules. | |||
5907 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, | |||
5908 | DeclarationNameInfo NameInfo) { | |||
5909 | DeclarationName Name = NameInfo.getName(); | |||
5910 | ||||
5911 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); | |||
5912 | while (Record && Record->isAnonymousStructOrUnion()) | |||
5913 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); | |||
5914 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { | |||
5915 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; | |||
5916 | return true; | |||
5917 | } | |||
5918 | ||||
5919 | return false; | |||
5920 | } | |||
5921 | ||||
5922 | /// Diagnose a declaration whose declarator-id has the given | |||
5923 | /// nested-name-specifier. | |||
5924 | /// | |||
5925 | /// \param SS The nested-name-specifier of the declarator-id. | |||
5926 | /// | |||
5927 | /// \param DC The declaration context to which the nested-name-specifier | |||
5928 | /// resolves. | |||
5929 | /// | |||
5930 | /// \param Name The name of the entity being declared. | |||
5931 | /// | |||
5932 | /// \param Loc The location of the name of the entity being declared. | |||
5933 | /// | |||
5934 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus | |||
5935 | /// we're declaring an explicit / partial specialization / instantiation. | |||
5936 | /// | |||
5937 | /// \returns true if we cannot safely recover from this error, false otherwise. | |||
5938 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | |||
5939 | DeclarationName Name, | |||
5940 | SourceLocation Loc, bool IsTemplateId) { | |||
5941 | DeclContext *Cur = CurContext; | |||
5942 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) | |||
5943 | Cur = Cur->getParent(); | |||
5944 | ||||
5945 | // If the user provided a superfluous scope specifier that refers back to the | |||
5946 | // class in which the entity is already declared, diagnose and ignore it. | |||
5947 | // | |||
5948 | // class X { | |||
5949 | // void X::f(); | |||
5950 | // }; | |||
5951 | // | |||
5952 | // Note, it was once ill-formed to give redundant qualification in all | |||
5953 | // contexts, but that rule was removed by DR482. | |||
5954 | if (Cur->Equals(DC)) { | |||
5955 | if (Cur->isRecord()) { | |||
5956 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification | |||
5957 | : diag::err_member_extra_qualification) | |||
5958 | << Name << FixItHint::CreateRemoval(SS.getRange()); | |||
5959 | SS.clear(); | |||
5960 | } else { | |||
5961 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; | |||
5962 | } | |||
5963 | return false; | |||
5964 | } | |||
5965 | ||||
5966 | // Check whether the qualifying scope encloses the scope of the original | |||
5967 | // declaration. For a template-id, we perform the checks in | |||
5968 | // CheckTemplateSpecializationScope. | |||
5969 | if (!Cur->Encloses(DC) && !IsTemplateId) { | |||
5970 | if (Cur->isRecord()) | |||
5971 | Diag(Loc, diag::err_member_qualification) | |||
5972 | << Name << SS.getRange(); | |||
5973 | else if (isa<TranslationUnitDecl>(DC)) | |||
5974 | Diag(Loc, diag::err_invalid_declarator_global_scope) | |||
5975 | << Name << SS.getRange(); | |||
5976 | else if (isa<FunctionDecl>(Cur)) | |||
5977 | Diag(Loc, diag::err_invalid_declarator_in_function) | |||
5978 | << Name << SS.getRange(); | |||
5979 | else if (isa<BlockDecl>(Cur)) | |||
5980 | Diag(Loc, diag::err_invalid_declarator_in_block) | |||
5981 | << Name << SS.getRange(); | |||
5982 | else if (isa<ExportDecl>(Cur)) { | |||
5983 | if (!isa<NamespaceDecl>(DC)) | |||
5984 | Diag(Loc, diag::err_export_non_namespace_scope_name) | |||
5985 | << Name << SS.getRange(); | |||
5986 | else | |||
5987 | // The cases that DC is not NamespaceDecl should be handled in | |||
5988 | // CheckRedeclarationExported. | |||
5989 | return false; | |||
5990 | } else | |||
5991 | Diag(Loc, diag::err_invalid_declarator_scope) | |||
5992 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); | |||
5993 | ||||
5994 | return true; | |||
5995 | } | |||
5996 | ||||
5997 | if (Cur->isRecord()) { | |||
5998 | // Cannot qualify members within a class. | |||
5999 | Diag(Loc, diag::err_member_qualification) | |||
6000 | << Name << SS.getRange(); | |||
6001 | SS.clear(); | |||
6002 | ||||
6003 | // C++ constructors and destructors with incorrect scopes can break | |||
6004 | // our AST invariants by having the wrong underlying types. If | |||
6005 | // that's the case, then drop this declaration entirely. | |||
6006 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || | |||
6007 | Name.getNameKind() == DeclarationName::CXXDestructorName) && | |||
6008 | !Context.hasSameType(Name.getCXXNameType(), | |||
6009 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) | |||
6010 | return true; | |||
6011 | ||||
6012 | return false; | |||
6013 | } | |||
6014 | ||||
6015 | // C++11 [dcl.meaning]p1: | |||
6016 | // [...] "The nested-name-specifier of the qualified declarator-id shall | |||
6017 | // not begin with a decltype-specifer" | |||
6018 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); | |||
6019 | while (SpecLoc.getPrefix()) | |||
6020 | SpecLoc = SpecLoc.getPrefix(); | |||
6021 | if (isa_and_nonnull<DecltypeType>( | |||
6022 | SpecLoc.getNestedNameSpecifier()->getAsType())) | |||
6023 | Diag(Loc, diag::err_decltype_in_declarator) | |||
6024 | << SpecLoc.getTypeLoc().getSourceRange(); | |||
6025 | ||||
6026 | return false; | |||
6027 | } | |||
6028 | ||||
6029 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, | |||
6030 | MultiTemplateParamsArg TemplateParamLists) { | |||
6031 | // TODO: consider using NameInfo for diagnostic. | |||
6032 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
6033 | DeclarationName Name = NameInfo.getName(); | |||
6034 | ||||
6035 | // All of these full declarators require an identifier. If it doesn't have | |||
6036 | // one, the ParsedFreeStandingDeclSpec action should be used. | |||
6037 | if (D.isDecompositionDeclarator()) { | |||
6038 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); | |||
6039 | } else if (!Name) { | |||
6040 | if (!D.isInvalidType()) // Reject this if we think it is valid. | |||
6041 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) | |||
6042 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); | |||
6043 | return nullptr; | |||
6044 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) | |||
6045 | return nullptr; | |||
6046 | ||||
6047 | // The scope passed in may not be a decl scope. Zip up the scope tree until | |||
6048 | // we find one that is. | |||
6049 | while ((S->getFlags() & Scope::DeclScope) == 0 || | |||
6050 | (S->getFlags() & Scope::TemplateParamScope) != 0) | |||
6051 | S = S->getParent(); | |||
6052 | ||||
6053 | DeclContext *DC = CurContext; | |||
6054 | if (D.getCXXScopeSpec().isInvalid()) | |||
6055 | D.setInvalidType(); | |||
6056 | else if (D.getCXXScopeSpec().isSet()) { | |||
6057 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), | |||
6058 | UPPC_DeclarationQualifier)) | |||
6059 | return nullptr; | |||
6060 | ||||
6061 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); | |||
6062 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); | |||
6063 | if (!DC || isa<EnumDecl>(DC)) { | |||
6064 | // If we could not compute the declaration context, it's because the | |||
6065 | // declaration context is dependent but does not refer to a class, | |||
6066 | // class template, or class template partial specialization. Complain | |||
6067 | // and return early, to avoid the coming semantic disaster. | |||
6068 | Diag(D.getIdentifierLoc(), | |||
6069 | diag::err_template_qualified_declarator_no_match) | |||
6070 | << D.getCXXScopeSpec().getScopeRep() | |||
6071 | << D.getCXXScopeSpec().getRange(); | |||
6072 | return nullptr; | |||
6073 | } | |||
6074 | bool IsDependentContext = DC->isDependentContext(); | |||
6075 | ||||
6076 | if (!IsDependentContext && | |||
6077 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) | |||
6078 | return nullptr; | |||
6079 | ||||
6080 | // If a class is incomplete, do not parse entities inside it. | |||
6081 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { | |||
6082 | Diag(D.getIdentifierLoc(), | |||
6083 | diag::err_member_def_undefined_record) | |||
6084 | << Name << DC << D.getCXXScopeSpec().getRange(); | |||
6085 | return nullptr; | |||
6086 | } | |||
6087 | if (!D.getDeclSpec().isFriendSpecified()) { | |||
6088 | if (diagnoseQualifiedDeclaration( | |||
6089 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), | |||
6090 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { | |||
6091 | if (DC->isRecord()) | |||
6092 | return nullptr; | |||
6093 | ||||
6094 | D.setInvalidType(); | |||
6095 | } | |||
6096 | } | |||
6097 | ||||
6098 | // Check whether we need to rebuild the type of the given | |||
6099 | // declaration in the current instantiation. | |||
6100 | if (EnteringContext && IsDependentContext && | |||
6101 | TemplateParamLists.size() != 0) { | |||
6102 | ContextRAII SavedContext(*this, DC); | |||
6103 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) | |||
6104 | D.setInvalidType(); | |||
6105 | } | |||
6106 | } | |||
6107 | ||||
6108 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
6109 | QualType R = TInfo->getType(); | |||
6110 | ||||
6111 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
6112 | UPPC_DeclarationType)) | |||
6113 | D.setInvalidType(); | |||
6114 | ||||
6115 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | |||
6116 | forRedeclarationInCurContext()); | |||
6117 | ||||
6118 | // See if this is a redefinition of a variable in the same scope. | |||
6119 | if (!D.getCXXScopeSpec().isSet()) { | |||
6120 | bool IsLinkageLookup = false; | |||
6121 | bool CreateBuiltins = false; | |||
6122 | ||||
6123 | // If the declaration we're planning to build will be a function | |||
6124 | // or object with linkage, then look for another declaration with | |||
6125 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). | |||
6126 | // | |||
6127 | // If the declaration we're planning to build will be declared with | |||
6128 | // external linkage in the translation unit, create any builtin with | |||
6129 | // the same name. | |||
6130 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | |||
6131 | /* Do nothing*/; | |||
6132 | else if (CurContext->isFunctionOrMethod() && | |||
6133 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || | |||
6134 | R->isFunctionType())) { | |||
6135 | IsLinkageLookup = true; | |||
6136 | CreateBuiltins = | |||
6137 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); | |||
6138 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && | |||
6139 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) | |||
6140 | CreateBuiltins = true; | |||
6141 | ||||
6142 | if (IsLinkageLookup) { | |||
6143 | Previous.clear(LookupRedeclarationWithLinkage); | |||
6144 | Previous.setRedeclarationKind(ForExternalRedeclaration); | |||
6145 | } | |||
6146 | ||||
6147 | LookupName(Previous, S, CreateBuiltins); | |||
6148 | } else { // Something like "int foo::x;" | |||
6149 | LookupQualifiedName(Previous, DC); | |||
6150 | ||||
6151 | // C++ [dcl.meaning]p1: | |||
6152 | // When the declarator-id is qualified, the declaration shall refer to a | |||
6153 | // previously declared member of the class or namespace to which the | |||
6154 | // qualifier refers (or, in the case of a namespace, of an element of the | |||
6155 | // inline namespace set of that namespace (7.3.1)) or to a specialization | |||
6156 | // thereof; [...] | |||
6157 | // | |||
6158 | // Note that we already checked the context above, and that we do not have | |||
6159 | // enough information to make sure that Previous contains the declaration | |||
6160 | // we want to match. For example, given: | |||
6161 | // | |||
6162 | // class X { | |||
6163 | // void f(); | |||
6164 | // void f(float); | |||
6165 | // }; | |||
6166 | // | |||
6167 | // void X::f(int) { } // ill-formed | |||
6168 | // | |||
6169 | // In this case, Previous will point to the overload set | |||
6170 | // containing the two f's declared in X, but neither of them | |||
6171 | // matches. | |||
6172 | ||||
6173 | // C++ [dcl.meaning]p1: | |||
6174 | // [...] the member shall not merely have been introduced by a | |||
6175 | // using-declaration in the scope of the class or namespace nominated by | |||
6176 | // the nested-name-specifier of the declarator-id. | |||
6177 | RemoveUsingDecls(Previous); | |||
6178 | } | |||
6179 | ||||
6180 | if (Previous.isSingleResult() && | |||
6181 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
6182 | // Maybe we will complain about the shadowed template parameter. | |||
6183 | if (!D.isInvalidType()) | |||
6184 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | |||
6185 | Previous.getFoundDecl()); | |||
6186 | ||||
6187 | // Just pretend that we didn't see the previous declaration. | |||
6188 | Previous.clear(); | |||
6189 | } | |||
6190 | ||||
6191 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) | |||
6192 | // Forget that the previous declaration is the injected-class-name. | |||
6193 | Previous.clear(); | |||
6194 | ||||
6195 | // In C++, the previous declaration we find might be a tag type | |||
6196 | // (class or enum). In this case, the new declaration will hide the | |||
6197 | // tag type. Note that this applies to functions, function templates, and | |||
6198 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. | |||
6199 | if (Previous.isSingleTagDecl() && | |||
6200 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | |||
6201 | (TemplateParamLists.size() == 0 || R->isFunctionType())) | |||
6202 | Previous.clear(); | |||
6203 | ||||
6204 | // Check that there are no default arguments other than in the parameters | |||
6205 | // of a function declaration (C++ only). | |||
6206 | if (getLangOpts().CPlusPlus) | |||
6207 | CheckExtraCXXDefaultArguments(D); | |||
6208 | ||||
6209 | NamedDecl *New; | |||
6210 | ||||
6211 | bool AddToScope = true; | |||
6212 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { | |||
6213 | if (TemplateParamLists.size()) { | |||
6214 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); | |||
6215 | return nullptr; | |||
6216 | } | |||
6217 | ||||
6218 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); | |||
6219 | } else if (R->isFunctionType()) { | |||
6220 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, | |||
6221 | TemplateParamLists, | |||
6222 | AddToScope); | |||
6223 | } else { | |||
6224 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, | |||
6225 | AddToScope); | |||
6226 | } | |||
6227 | ||||
6228 | if (!New) | |||
6229 | return nullptr; | |||
6230 | ||||
6231 | // If this has an identifier and is not a function template specialization, | |||
6232 | // add it to the scope stack. | |||
6233 | if (New->getDeclName() && AddToScope) | |||
6234 | PushOnScopeChains(New, S); | |||
6235 | ||||
6236 | if (isInOpenMPDeclareTargetContext()) | |||
6237 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | |||
6238 | ||||
6239 | return New; | |||
6240 | } | |||
6241 | ||||
6242 | /// Helper method to turn variable array types into constant array | |||
6243 | /// types in certain situations which would otherwise be errors (for | |||
6244 | /// GCC compatibility). | |||
6245 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, | |||
6246 | ASTContext &Context, | |||
6247 | bool &SizeIsNegative, | |||
6248 | llvm::APSInt &Oversized) { | |||
6249 | // This method tries to turn a variable array into a constant | |||
6250 | // array even when the size isn't an ICE. This is necessary | |||
6251 | // for compatibility with code that depends on gcc's buggy | |||
6252 | // constant expression folding, like struct {char x[(int)(char*)2];} | |||
6253 | SizeIsNegative = false; | |||
6254 | Oversized = 0; | |||
6255 | ||||
6256 | if (T->isDependentType()) | |||
6257 | return QualType(); | |||
6258 | ||||
6259 | QualifierCollector Qs; | |||
6260 | const Type *Ty = Qs.strip(T); | |||
6261 | ||||
6262 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { | |||
6263 | QualType Pointee = PTy->getPointeeType(); | |||
6264 | QualType FixedType = | |||
6265 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, | |||
6266 | Oversized); | |||
6267 | if (FixedType.isNull()) return FixedType; | |||
6268 | FixedType = Context.getPointerType(FixedType); | |||
6269 | return Qs.apply(Context, FixedType); | |||
6270 | } | |||
6271 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { | |||
6272 | QualType Inner = PTy->getInnerType(); | |||
6273 | QualType FixedType = | |||
6274 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, | |||
6275 | Oversized); | |||
6276 | if (FixedType.isNull()) return FixedType; | |||
6277 | FixedType = Context.getParenType(FixedType); | |||
6278 | return Qs.apply(Context, FixedType); | |||
6279 | } | |||
6280 | ||||
6281 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); | |||
6282 | if (!VLATy) | |||
6283 | return QualType(); | |||
6284 | ||||
6285 | QualType ElemTy = VLATy->getElementType(); | |||
6286 | if (ElemTy->isVariablyModifiedType()) { | |||
6287 | ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context, | |||
6288 | SizeIsNegative, Oversized); | |||
6289 | if (ElemTy.isNull()) | |||
6290 | return QualType(); | |||
6291 | } | |||
6292 | ||||
6293 | Expr::EvalResult Result; | |||
6294 | if (!VLATy->getSizeExpr() || | |||
6295 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) | |||
6296 | return QualType(); | |||
6297 | ||||
6298 | llvm::APSInt Res = Result.Val.getInt(); | |||
6299 | ||||
6300 | // Check whether the array size is negative. | |||
6301 | if (Res.isSigned() && Res.isNegative()) { | |||
6302 | SizeIsNegative = true; | |||
6303 | return QualType(); | |||
6304 | } | |||
6305 | ||||
6306 | // Check whether the array is too large to be addressed. | |||
6307 | unsigned ActiveSizeBits = | |||
6308 | (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() && | |||
6309 | !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType()) | |||
6310 | ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res) | |||
6311 | : Res.getActiveBits(); | |||
6312 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | |||
6313 | Oversized = Res; | |||
6314 | return QualType(); | |||
6315 | } | |||
6316 | ||||
6317 | QualType FoldedArrayType = Context.getConstantArrayType( | |||
6318 | ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); | |||
6319 | return Qs.apply(Context, FoldedArrayType); | |||
6320 | } | |||
6321 | ||||
6322 | static void | |||
6323 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { | |||
6324 | SrcTL = SrcTL.getUnqualifiedLoc(); | |||
6325 | DstTL = DstTL.getUnqualifiedLoc(); | |||
6326 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { | |||
6327 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); | |||
6328 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), | |||
6329 | DstPTL.getPointeeLoc()); | |||
6330 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); | |||
6331 | return; | |||
6332 | } | |||
6333 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { | |||
6334 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); | |||
6335 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), | |||
6336 | DstPTL.getInnerLoc()); | |||
6337 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); | |||
6338 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); | |||
6339 | return; | |||
6340 | } | |||
6341 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); | |||
6342 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); | |||
6343 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); | |||
6344 | TypeLoc DstElemTL = DstATL.getElementLoc(); | |||
6345 | if (VariableArrayTypeLoc SrcElemATL = | |||
6346 | SrcElemTL.getAs<VariableArrayTypeLoc>()) { | |||
6347 | ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>(); | |||
6348 | FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL); | |||
6349 | } else { | |||
6350 | DstElemTL.initializeFullCopy(SrcElemTL); | |||
6351 | } | |||
6352 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); | |||
6353 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); | |||
6354 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); | |||
6355 | } | |||
6356 | ||||
6357 | /// Helper method to turn variable array types into constant array | |||
6358 | /// types in certain situations which would otherwise be errors (for | |||
6359 | /// GCC compatibility). | |||
6360 | static TypeSourceInfo* | |||
6361 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, | |||
6362 | ASTContext &Context, | |||
6363 | bool &SizeIsNegative, | |||
6364 | llvm::APSInt &Oversized) { | |||
6365 | QualType FixedTy | |||
6366 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, | |||
6367 | SizeIsNegative, Oversized); | |||
6368 | if (FixedTy.isNull()) | |||
6369 | return nullptr; | |||
6370 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); | |||
6371 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), | |||
6372 | FixedTInfo->getTypeLoc()); | |||
6373 | return FixedTInfo; | |||
6374 | } | |||
6375 | ||||
6376 | /// Attempt to fold a variable-sized type to a constant-sized type, returning | |||
6377 | /// true if we were successful. | |||
6378 | bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, | |||
6379 | QualType &T, SourceLocation Loc, | |||
6380 | unsigned FailedFoldDiagID) { | |||
6381 | bool SizeIsNegative; | |||
6382 | llvm::APSInt Oversized; | |||
6383 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | |||
6384 | TInfo, Context, SizeIsNegative, Oversized); | |||
6385 | if (FixedTInfo) { | |||
6386 | Diag(Loc, diag::ext_vla_folded_to_constant); | |||
6387 | TInfo = FixedTInfo; | |||
6388 | T = FixedTInfo->getType(); | |||
6389 | return true; | |||
6390 | } | |||
6391 | ||||
6392 | if (SizeIsNegative) | |||
6393 | Diag(Loc, diag::err_typecheck_negative_array_size); | |||
6394 | else if (Oversized.getBoolValue()) | |||
6395 | Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10); | |||
6396 | else if (FailedFoldDiagID) | |||
6397 | Diag(Loc, FailedFoldDiagID); | |||
6398 | return false; | |||
6399 | } | |||
6400 | ||||
6401 | /// Register the given locally-scoped extern "C" declaration so | |||
6402 | /// that it can be found later for redeclarations. We include any extern "C" | |||
6403 | /// declaration that is not visible in the translation unit here, not just | |||
6404 | /// function-scope declarations. | |||
6405 | void | |||
6406 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { | |||
6407 | if (!getLangOpts().CPlusPlus && | |||
6408 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) | |||
6409 | // Don't need to track declarations in the TU in C. | |||
6410 | return; | |||
6411 | ||||
6412 | // Note that we have a locally-scoped external with this name. | |||
6413 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); | |||
6414 | } | |||
6415 | ||||
6416 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { | |||
6417 | // FIXME: We can have multiple results via __attribute__((overloadable)). | |||
6418 | auto Result = Context.getExternCContextDecl()->lookup(Name); | |||
6419 | return Result.empty() ? nullptr : *Result.begin(); | |||
6420 | } | |||
6421 | ||||
6422 | /// Diagnose function specifiers on a declaration of an identifier that | |||
6423 | /// does not identify a function. | |||
6424 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { | |||
6425 | // FIXME: We should probably indicate the identifier in question to avoid | |||
6426 | // confusion for constructs like "virtual int a(), b;" | |||
6427 | if (DS.isVirtualSpecified()) | |||
6428 | Diag(DS.getVirtualSpecLoc(), | |||
6429 | diag::err_virtual_non_function); | |||
6430 | ||||
6431 | if (DS.hasExplicitSpecifier()) | |||
6432 | Diag(DS.getExplicitSpecLoc(), | |||
6433 | diag::err_explicit_non_function); | |||
6434 | ||||
6435 | if (DS.isNoreturnSpecified()) | |||
6436 | Diag(DS.getNoreturnSpecLoc(), | |||
6437 | diag::err_noreturn_non_function); | |||
6438 | } | |||
6439 | ||||
6440 | NamedDecl* | |||
6441 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | |||
6442 | TypeSourceInfo *TInfo, LookupResult &Previous) { | |||
6443 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). | |||
6444 | if (D.getCXXScopeSpec().isSet()) { | |||
6445 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) | |||
6446 | << D.getCXXScopeSpec().getRange(); | |||
6447 | D.setInvalidType(); | |||
6448 | // Pretend we didn't see the scope specifier. | |||
6449 | DC = CurContext; | |||
6450 | Previous.clear(); | |||
6451 | } | |||
6452 | ||||
6453 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
6454 | ||||
6455 | if (D.getDeclSpec().isInlineSpecified()) | |||
6456 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
6457 | << getLangOpts().CPlusPlus17; | |||
6458 | if (D.getDeclSpec().hasConstexprSpecifier()) | |||
6459 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) | |||
6460 | << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); | |||
6461 | ||||
6462 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { | |||
6463 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) | |||
6464 | Diag(D.getName().StartLocation, | |||
6465 | diag::err_deduction_guide_invalid_specifier) | |||
6466 | << "typedef"; | |||
6467 | else | |||
6468 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) | |||
6469 | << D.getName().getSourceRange(); | |||
6470 | return nullptr; | |||
6471 | } | |||
6472 | ||||
6473 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); | |||
6474 | if (!NewTD) return nullptr; | |||
6475 | ||||
6476 | // Handle attributes prior to checking for duplicates in MergeVarDecl | |||
6477 | ProcessDeclAttributes(S, NewTD, D); | |||
6478 | ||||
6479 | CheckTypedefForVariablyModifiedType(S, NewTD); | |||
6480 | ||||
6481 | bool Redeclaration = D.isRedeclaration(); | |||
6482 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); | |||
6483 | D.setRedeclaration(Redeclaration); | |||
6484 | return ND; | |||
6485 | } | |||
6486 | ||||
6487 | void | |||
6488 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { | |||
6489 | // C99 6.7.7p2: If a typedef name specifies a variably modified type | |||
6490 | // then it shall have block scope. | |||
6491 | // Note that variably modified types must be fixed before merging the decl so | |||
6492 | // that redeclarations will match. | |||
6493 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); | |||
6494 | QualType T = TInfo->getType(); | |||
6495 | if (T->isVariablyModifiedType()) { | |||
6496 | setFunctionHasBranchProtectedScope(); | |||
6497 | ||||
6498 | if (S->getFnParent() == nullptr) { | |||
6499 | bool SizeIsNegative; | |||
6500 | llvm::APSInt Oversized; | |||
6501 | TypeSourceInfo *FixedTInfo = | |||
6502 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | |||
6503 | SizeIsNegative, | |||
6504 | Oversized); | |||
6505 | if (FixedTInfo) { | |||
6506 | Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant); | |||
6507 | NewTD->setTypeSourceInfo(FixedTInfo); | |||
6508 | } else { | |||
6509 | if (SizeIsNegative) | |||
6510 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); | |||
6511 | else if (T->isVariableArrayType()) | |||
6512 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); | |||
6513 | else if (Oversized.getBoolValue()) | |||
6514 | Diag(NewTD->getLocation(), diag::err_array_too_large) | |||
6515 | << toString(Oversized, 10); | |||
6516 | else | |||
6517 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); | |||
6518 | NewTD->setInvalidDecl(); | |||
6519 | } | |||
6520 | } | |||
6521 | } | |||
6522 | } | |||
6523 | ||||
6524 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which | |||
6525 | /// declares a typedef-name, either using the 'typedef' type specifier or via | |||
6526 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. | |||
6527 | NamedDecl* | |||
6528 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, | |||
6529 | LookupResult &Previous, bool &Redeclaration) { | |||
6530 | ||||
6531 | // Find the shadowed declaration before filtering for scope. | |||
6532 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); | |||
6533 | ||||
6534 | // Merge the decl with the existing one if appropriate. If the decl is | |||
6535 | // in an outer scope, it isn't the same thing. | |||
6536 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, | |||
6537 | /*AllowInlineNamespace*/false); | |||
6538 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); | |||
6539 | if (!Previous.empty()) { | |||
6540 | Redeclaration = true; | |||
6541 | MergeTypedefNameDecl(S, NewTD, Previous); | |||
6542 | } else { | |||
6543 | inferGslPointerAttribute(NewTD); | |||
6544 | } | |||
6545 | ||||
6546 | if (ShadowedDecl && !Redeclaration) | |||
6547 | CheckShadow(NewTD, ShadowedDecl, Previous); | |||
6548 | ||||
6549 | // If this is the C FILE type, notify the AST context. | |||
6550 | if (IdentifierInfo *II = NewTD->getIdentifier()) | |||
6551 | if (!NewTD->isInvalidDecl() && | |||
6552 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
6553 | if (II->isStr("FILE")) | |||
6554 | Context.setFILEDecl(NewTD); | |||
6555 | else if (II->isStr("jmp_buf")) | |||
6556 | Context.setjmp_bufDecl(NewTD); | |||
6557 | else if (II->isStr("sigjmp_buf")) | |||
6558 | Context.setsigjmp_bufDecl(NewTD); | |||
6559 | else if (II->isStr("ucontext_t")) | |||
6560 | Context.setucontext_tDecl(NewTD); | |||
6561 | } | |||
6562 | ||||
6563 | return NewTD; | |||
6564 | } | |||
6565 | ||||
6566 | /// Determines whether the given declaration is an out-of-scope | |||
6567 | /// previous declaration. | |||
6568 | /// | |||
6569 | /// This routine should be invoked when name lookup has found a | |||
6570 | /// previous declaration (PrevDecl) that is not in the scope where a | |||
6571 | /// new declaration by the same name is being introduced. If the new | |||
6572 | /// declaration occurs in a local scope, previous declarations with | |||
6573 | /// linkage may still be considered previous declarations (C99 | |||
6574 | /// 6.2.2p4-5, C++ [basic.link]p6). | |||
6575 | /// | |||
6576 | /// \param PrevDecl the previous declaration found by name | |||
6577 | /// lookup | |||
6578 | /// | |||
6579 | /// \param DC the context in which the new declaration is being | |||
6580 | /// declared. | |||
6581 | /// | |||
6582 | /// \returns true if PrevDecl is an out-of-scope previous declaration | |||
6583 | /// for a new delcaration with the same name. | |||
6584 | static bool | |||
6585 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, | |||
6586 | ASTContext &Context) { | |||
6587 | if (!PrevDecl) | |||
6588 | return false; | |||
6589 | ||||
6590 | if (!PrevDecl->hasLinkage()) | |||
6591 | return false; | |||
6592 | ||||
6593 | if (Context.getLangOpts().CPlusPlus) { | |||
6594 | // C++ [basic.link]p6: | |||
6595 | // If there is a visible declaration of an entity with linkage | |||
6596 | // having the same name and type, ignoring entities declared | |||
6597 | // outside the innermost enclosing namespace scope, the block | |||
6598 | // scope declaration declares that same entity and receives the | |||
6599 | // linkage of the previous declaration. | |||
6600 | DeclContext *OuterContext = DC->getRedeclContext(); | |||
6601 | if (!OuterContext->isFunctionOrMethod()) | |||
6602 | // This rule only applies to block-scope declarations. | |||
6603 | return false; | |||
6604 | ||||
6605 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); | |||
6606 | if (PrevOuterContext->isRecord()) | |||
6607 | // We found a member function: ignore it. | |||
6608 | return false; | |||
6609 | ||||
6610 | // Find the innermost enclosing namespace for the new and | |||
6611 | // previous declarations. | |||
6612 | OuterContext = OuterContext->getEnclosingNamespaceContext(); | |||
6613 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); | |||
6614 | ||||
6615 | // The previous declaration is in a different namespace, so it | |||
6616 | // isn't the same function. | |||
6617 | if (!OuterContext->Equals(PrevOuterContext)) | |||
6618 | return false; | |||
6619 | } | |||
6620 | ||||
6621 | return true; | |||
6622 | } | |||
6623 | ||||
6624 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { | |||
6625 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | |||
6626 | if (!SS.isSet()) return; | |||
6627 | DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); | |||
6628 | } | |||
6629 | ||||
6630 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { | |||
6631 | QualType type = decl->getType(); | |||
6632 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); | |||
6633 | if (lifetime == Qualifiers::OCL_Autoreleasing) { | |||
6634 | // Various kinds of declaration aren't allowed to be __autoreleasing. | |||
6635 | unsigned kind = -1U; | |||
6636 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | |||
6637 | if (var->hasAttr<BlocksAttr>()) | |||
6638 | kind = 0; // __block | |||
6639 | else if (!var->hasLocalStorage()) | |||
6640 | kind = 1; // global | |||
6641 | } else if (isa<ObjCIvarDecl>(decl)) { | |||
6642 | kind = 3; // ivar | |||
6643 | } else if (isa<FieldDecl>(decl)) { | |||
6644 | kind = 2; // field | |||
6645 | } | |||
6646 | ||||
6647 | if (kind != -1U) { | |||
6648 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) | |||
6649 | << kind; | |||
6650 | } | |||
6651 | } else if (lifetime == Qualifiers::OCL_None) { | |||
6652 | // Try to infer lifetime. | |||
6653 | if (!type->isObjCLifetimeType()) | |||
6654 | return false; | |||
6655 | ||||
6656 | lifetime = type->getObjCARCImplicitLifetime(); | |||
6657 | type = Context.getLifetimeQualifiedType(type, lifetime); | |||
6658 | decl->setType(type); | |||
6659 | } | |||
6660 | ||||
6661 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | |||
6662 | // Thread-local variables cannot have lifetime. | |||
6663 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && | |||
6664 | var->getTLSKind()) { | |||
6665 | Diag(var->getLocation(), diag::err_arc_thread_ownership) | |||
6666 | << var->getType(); | |||
6667 | return true; | |||
6668 | } | |||
6669 | } | |||
6670 | ||||
6671 | return false; | |||
6672 | } | |||
6673 | ||||
6674 | void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { | |||
6675 | if (Decl->getType().hasAddressSpace()) | |||
6676 | return; | |||
6677 | if (Decl->getType()->isDependentType()) | |||
6678 | return; | |||
6679 | if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { | |||
6680 | QualType Type = Var->getType(); | |||
6681 | if (Type->isSamplerT() || Type->isVoidType()) | |||
6682 | return; | |||
6683 | LangAS ImplAS = LangAS::opencl_private; | |||
6684 | // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the | |||
6685 | // __opencl_c_program_scope_global_variables feature, the address space | |||
6686 | // for a variable at program scope or a static or extern variable inside | |||
6687 | // a function are inferred to be __global. | |||
6688 | if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) && | |||
6689 | Var->hasGlobalStorage()) | |||
6690 | ImplAS = LangAS::opencl_global; | |||
6691 | // If the original type from a decayed type is an array type and that array | |||
6692 | // type has no address space yet, deduce it now. | |||
6693 | if (auto DT = dyn_cast<DecayedType>(Type)) { | |||
6694 | auto OrigTy = DT->getOriginalType(); | |||
6695 | if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { | |||
6696 | // Add the address space to the original array type and then propagate | |||
6697 | // that to the element type through `getAsArrayType`. | |||
6698 | OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); | |||
6699 | OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); | |||
6700 | // Re-generate the decayed type. | |||
6701 | Type = Context.getDecayedType(OrigTy); | |||
6702 | } | |||
6703 | } | |||
6704 | Type = Context.getAddrSpaceQualType(Type, ImplAS); | |||
6705 | // Apply any qualifiers (including address space) from the array type to | |||
6706 | // the element type. This implements C99 6.7.3p8: "If the specification of | |||
6707 | // an array type includes any type qualifiers, the element type is so | |||
6708 | // qualified, not the array type." | |||
6709 | if (Type->isArrayType()) | |||
6710 | Type = QualType(Context.getAsArrayType(Type), 0); | |||
6711 | Decl->setType(Type); | |||
6712 | } | |||
6713 | } | |||
6714 | ||||
6715 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { | |||
6716 | // Ensure that an auto decl is deduced otherwise the checks below might cache | |||
6717 | // the wrong linkage. | |||
6718 | assert(S.ParsingInitForAutoVars.count(&ND) == 0)(static_cast <bool> (S.ParsingInitForAutoVars.count(& ND) == 0) ? void (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0" , "clang/lib/Sema/SemaDecl.cpp", 6718, __extension__ __PRETTY_FUNCTION__ )); | |||
6719 | ||||
6720 | // 'weak' only applies to declarations with external linkage. | |||
6721 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { | |||
6722 | if (!ND.isExternallyVisible()) { | |||
6723 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); | |||
6724 | ND.dropAttr<WeakAttr>(); | |||
6725 | } | |||
6726 | } | |||
6727 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { | |||
6728 | if (ND.isExternallyVisible()) { | |||
6729 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); | |||
6730 | ND.dropAttr<WeakRefAttr>(); | |||
6731 | ND.dropAttr<AliasAttr>(); | |||
6732 | } | |||
6733 | } | |||
6734 | ||||
6735 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { | |||
6736 | if (VD->hasInit()) { | |||
6737 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { | |||
6738 | assert(VD->isThisDeclarationADefinition() &&(static_cast <bool> (VD->isThisDeclarationADefinition () && !VD->isExternallyVisible() && "Broken AliasAttr handled late!" ) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "clang/lib/Sema/SemaDecl.cpp", 6739, __extension__ __PRETTY_FUNCTION__ )) | |||
6739 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!")(static_cast <bool> (VD->isThisDeclarationADefinition () && !VD->isExternallyVisible() && "Broken AliasAttr handled late!" ) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "clang/lib/Sema/SemaDecl.cpp", 6739, __extension__ __PRETTY_FUNCTION__ )); | |||
6740 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; | |||
6741 | VD->dropAttr<AliasAttr>(); | |||
6742 | } | |||
6743 | } | |||
6744 | } | |||
6745 | ||||
6746 | // 'selectany' only applies to externally visible variable declarations. | |||
6747 | // It does not apply to functions. | |||
6748 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { | |||
6749 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { | |||
6750 | S.Diag(Attr->getLocation(), | |||
6751 | diag::err_attribute_selectany_non_extern_data); | |||
6752 | ND.dropAttr<SelectAnyAttr>(); | |||
6753 | } | |||
6754 | } | |||
6755 | ||||
6756 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { | |||
6757 | auto *VD = dyn_cast<VarDecl>(&ND); | |||
6758 | bool IsAnonymousNS = false; | |||
6759 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | |||
6760 | if (VD) { | |||
6761 | const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); | |||
6762 | while (NS && !IsAnonymousNS) { | |||
6763 | IsAnonymousNS = NS->isAnonymousNamespace(); | |||
6764 | NS = dyn_cast<NamespaceDecl>(NS->getParent()); | |||
6765 | } | |||
6766 | } | |||
6767 | // dll attributes require external linkage. Static locals may have external | |||
6768 | // linkage but still cannot be explicitly imported or exported. | |||
6769 | // In Microsoft mode, a variable defined in anonymous namespace must have | |||
6770 | // external linkage in order to be exported. | |||
6771 | bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; | |||
6772 | if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || | |||
6773 | (!AnonNSInMicrosoftMode && | |||
6774 | (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { | |||
6775 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) | |||
6776 | << &ND << Attr; | |||
6777 | ND.setInvalidDecl(); | |||
6778 | } | |||
6779 | } | |||
6780 | ||||
6781 | // Check the attributes on the function type, if any. | |||
6782 | if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { | |||
6783 | // Don't declare this variable in the second operand of the for-statement; | |||
6784 | // GCC miscompiles that by ending its lifetime before evaluating the | |||
6785 | // third operand. See gcc.gnu.org/PR86769. | |||
6786 | AttributedTypeLoc ATL; | |||
6787 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); | |||
6788 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | |||
6789 | TL = ATL.getModifiedLoc()) { | |||
6790 | // The [[lifetimebound]] attribute can be applied to the implicit object | |||
6791 | // parameter of a non-static member function (other than a ctor or dtor) | |||
6792 | // by applying it to the function type. | |||
6793 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { | |||
6794 | const auto *MD = dyn_cast<CXXMethodDecl>(FD); | |||
6795 | if (!MD || MD->isStatic()) { | |||
6796 | S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) | |||
6797 | << !MD << A->getRange(); | |||
6798 | } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { | |||
6799 | S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) | |||
6800 | << isa<CXXDestructorDecl>(MD) << A->getRange(); | |||
6801 | } | |||
6802 | } | |||
6803 | } | |||
6804 | } | |||
6805 | } | |||
6806 | ||||
6807 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, | |||
6808 | NamedDecl *NewDecl, | |||
6809 | bool IsSpecialization, | |||
6810 | bool IsDefinition) { | |||
6811 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) | |||
6812 | return; | |||
6813 | ||||
6814 | bool IsTemplate = false; | |||
6815 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { | |||
6816 | OldDecl = OldTD->getTemplatedDecl(); | |||
6817 | IsTemplate = true; | |||
6818 | if (!IsSpecialization) | |||
6819 | IsDefinition = false; | |||
6820 | } | |||
6821 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { | |||
6822 | NewDecl = NewTD->getTemplatedDecl(); | |||
6823 | IsTemplate = true; | |||
6824 | } | |||
6825 | ||||
6826 | if (!OldDecl || !NewDecl) | |||
6827 | return; | |||
6828 | ||||
6829 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); | |||
6830 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); | |||
6831 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); | |||
6832 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); | |||
6833 | ||||
6834 | // dllimport and dllexport are inheritable attributes so we have to exclude | |||
6835 | // inherited attribute instances. | |||
6836 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || | |||
6837 | (NewExportAttr && !NewExportAttr->isInherited()); | |||
6838 | ||||
6839 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, | |||
6840 | // the only exception being explicit specializations. | |||
6841 | // Implicitly generated declarations are also excluded for now because there | |||
6842 | // is no other way to switch these to use dllimport or dllexport. | |||
6843 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; | |||
6844 | ||||
6845 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { | |||
6846 | // Allow with a warning for free functions and global variables. | |||
6847 | bool JustWarn = false; | |||
6848 | if (!OldDecl->isCXXClassMember()) { | |||
6849 | auto *VD = dyn_cast<VarDecl>(OldDecl); | |||
6850 | if (VD && !VD->getDescribedVarTemplate()) | |||
6851 | JustWarn = true; | |||
6852 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); | |||
6853 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) | |||
6854 | JustWarn = true; | |||
6855 | } | |||
6856 | ||||
6857 | // We cannot change a declaration that's been used because IR has already | |||
6858 | // been emitted. Dllimported functions will still work though (modulo | |||
6859 | // address equality) as they can use the thunk. | |||
6860 | if (OldDecl->isUsed()) | |||
6861 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) | |||
6862 | JustWarn = false; | |||
6863 | ||||
6864 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration | |||
6865 | : diag::err_attribute_dll_redeclaration; | |||
6866 | S.Diag(NewDecl->getLocation(), DiagID) | |||
6867 | << NewDecl | |||
6868 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); | |||
6869 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6870 | if (!JustWarn) { | |||
6871 | NewDecl->setInvalidDecl(); | |||
6872 | return; | |||
6873 | } | |||
6874 | } | |||
6875 | ||||
6876 | // A redeclaration is not allowed to drop a dllimport attribute, the only | |||
6877 | // exceptions being inline function definitions (except for function | |||
6878 | // templates), local extern declarations, qualified friend declarations or | |||
6879 | // special MSVC extension: in the last case, the declaration is treated as if | |||
6880 | // it were marked dllexport. | |||
6881 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; | |||
6882 | bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols(); | |||
6883 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { | |||
6884 | // Ignore static data because out-of-line definitions are diagnosed | |||
6885 | // separately. | |||
6886 | IsStaticDataMember = VD->isStaticDataMember(); | |||
6887 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != | |||
6888 | VarDecl::DeclarationOnly; | |||
6889 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { | |||
6890 | IsInline = FD->isInlined(); | |||
6891 | IsQualifiedFriend = FD->getQualifier() && | |||
6892 | FD->getFriendObjectKind() == Decl::FOK_Declared; | |||
6893 | } | |||
6894 | ||||
6895 | if (OldImportAttr && !HasNewAttr && | |||
6896 | (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember && | |||
6897 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { | |||
6898 | if (IsMicrosoftABI && IsDefinition) { | |||
6899 | S.Diag(NewDecl->getLocation(), | |||
6900 | diag::warn_redeclaration_without_import_attribute) | |||
6901 | << NewDecl; | |||
6902 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6903 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6904 | NewDecl->addAttr( | |||
6905 | DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); | |||
6906 | } else { | |||
6907 | S.Diag(NewDecl->getLocation(), | |||
6908 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) | |||
6909 | << NewDecl << OldImportAttr; | |||
6910 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | |||
6911 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); | |||
6912 | OldDecl->dropAttr<DLLImportAttr>(); | |||
6913 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6914 | } | |||
6915 | } else if (IsInline && OldImportAttr && !IsMicrosoftABI) { | |||
6916 | // In MinGW, seeing a function declared inline drops the dllimport | |||
6917 | // attribute. | |||
6918 | OldDecl->dropAttr<DLLImportAttr>(); | |||
6919 | NewDecl->dropAttr<DLLImportAttr>(); | |||
6920 | S.Diag(NewDecl->getLocation(), | |||
6921 | diag::warn_dllimport_dropped_from_inline_function) | |||
6922 | << NewDecl << OldImportAttr; | |||
6923 | } | |||
6924 | ||||
6925 | // A specialization of a class template member function is processed here | |||
6926 | // since it's a redeclaration. If the parent class is dllexport, the | |||
6927 | // specialization inherits that attribute. This doesn't happen automatically | |||
6928 | // since the parent class isn't instantiated until later. | |||
6929 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { | |||
6930 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && | |||
6931 | !NewImportAttr && !NewExportAttr) { | |||
6932 | if (const DLLExportAttr *ParentExportAttr = | |||
6933 | MD->getParent()->getAttr<DLLExportAttr>()) { | |||
6934 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); | |||
6935 | NewAttr->setInherited(true); | |||
6936 | NewDecl->addAttr(NewAttr); | |||
6937 | } | |||
6938 | } | |||
6939 | } | |||
6940 | } | |||
6941 | ||||
6942 | /// Given that we are within the definition of the given function, | |||
6943 | /// will that definition behave like C99's 'inline', where the | |||
6944 | /// definition is discarded except for optimization purposes? | |||
6945 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { | |||
6946 | // Try to avoid calling GetGVALinkageForFunction. | |||
6947 | ||||
6948 | // All cases of this require the 'inline' keyword. | |||
6949 | if (!FD->isInlined()) return false; | |||
6950 | ||||
6951 | // This is only possible in C++ with the gnu_inline attribute. | |||
6952 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) | |||
6953 | return false; | |||
6954 | ||||
6955 | // Okay, go ahead and call the relatively-more-expensive function. | |||
6956 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; | |||
6957 | } | |||
6958 | ||||
6959 | /// Determine whether a variable is extern "C" prior to attaching | |||
6960 | /// an initializer. We can't just call isExternC() here, because that | |||
6961 | /// will also compute and cache whether the declaration is externally | |||
6962 | /// visible, which might change when we attach the initializer. | |||
6963 | /// | |||
6964 | /// This can only be used if the declaration is known to not be a | |||
6965 | /// redeclaration of an internal linkage declaration. | |||
6966 | /// | |||
6967 | /// For instance: | |||
6968 | /// | |||
6969 | /// auto x = []{}; | |||
6970 | /// | |||
6971 | /// Attaching the initializer here makes this declaration not externally | |||
6972 | /// visible, because its type has internal linkage. | |||
6973 | /// | |||
6974 | /// FIXME: This is a hack. | |||
6975 | template<typename T> | |||
6976 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { | |||
6977 | if (S.getLangOpts().CPlusPlus) { | |||
6978 | // In C++, the overloadable attribute negates the effects of extern "C". | |||
6979 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) | |||
6980 | return false; | |||
6981 | ||||
6982 | // So do CUDA's host/device attributes. | |||
6983 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || | |||
6984 | D->template hasAttr<CUDAHostAttr>())) | |||
6985 | return false; | |||
6986 | } | |||
6987 | return D->isExternC(); | |||
6988 | } | |||
6989 | ||||
6990 | static bool shouldConsiderLinkage(const VarDecl *VD) { | |||
6991 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); | |||
6992 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || | |||
6993 | isa<OMPDeclareMapperDecl>(DC)) | |||
6994 | return VD->hasExternalStorage(); | |||
6995 | if (DC->isFileContext()) | |||
6996 | return true; | |||
6997 | if (DC->isRecord()) | |||
6998 | return false; | |||
6999 | if (isa<RequiresExprBodyDecl>(DC)) | |||
7000 | return false; | |||
7001 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "clang/lib/Sema/SemaDecl.cpp" , 7001); | |||
7002 | } | |||
7003 | ||||
7004 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { | |||
7005 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); | |||
7006 | if (DC->isFileContext() || DC->isFunctionOrMethod() || | |||
7007 | isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) | |||
7008 | return true; | |||
7009 | if (DC->isRecord()) | |||
7010 | return false; | |||
7011 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "clang/lib/Sema/SemaDecl.cpp" , 7011); | |||
7012 | } | |||
7013 | ||||
7014 | static bool hasParsedAttr(Scope *S, const Declarator &PD, | |||
7015 | ParsedAttr::Kind Kind) { | |||
7016 | // Check decl attributes on the DeclSpec. | |||
7017 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) | |||
7018 | return true; | |||
7019 | ||||
7020 | // Walk the declarator structure, checking decl attributes that were in a type | |||
7021 | // position to the decl itself. | |||
7022 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { | |||
7023 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) | |||
7024 | return true; | |||
7025 | } | |||
7026 | ||||
7027 | // Finally, check attributes on the decl itself. | |||
7028 | return PD.getAttributes().hasAttribute(Kind); | |||
7029 | } | |||
7030 | ||||
7031 | /// Adjust the \c DeclContext for a function or variable that might be a | |||
7032 | /// function-local external declaration. | |||
7033 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { | |||
7034 | if (!DC->isFunctionOrMethod()) | |||
7035 | return false; | |||
7036 | ||||
7037 | // If this is a local extern function or variable declared within a function | |||
7038 | // template, don't add it into the enclosing namespace scope until it is | |||
7039 | // instantiated; it might have a dependent type right now. | |||
7040 | if (DC->isDependentContext()) | |||
7041 | return true; | |||
7042 | ||||
7043 | // C++11 [basic.link]p7: | |||
7044 | // When a block scope declaration of an entity with linkage is not found to | |||
7045 | // refer to some other declaration, then that entity is a member of the | |||
7046 | // innermost enclosing namespace. | |||
7047 | // | |||
7048 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a | |||
7049 | // semantically-enclosing namespace, not a lexically-enclosing one. | |||
7050 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) | |||
7051 | DC = DC->getParent(); | |||
7052 | return true; | |||
7053 | } | |||
7054 | ||||
7055 | /// Returns true if given declaration has external C language linkage. | |||
7056 | static bool isDeclExternC(const Decl *D) { | |||
7057 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) | |||
7058 | return FD->isExternC(); | |||
7059 | if (const auto *VD = dyn_cast<VarDecl>(D)) | |||
7060 | return VD->isExternC(); | |||
7061 | ||||
7062 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "clang/lib/Sema/SemaDecl.cpp" , 7062); | |||
7063 | } | |||
7064 | ||||
7065 | /// Returns true if there hasn't been any invalid type diagnosed. | |||
7066 | static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) { | |||
7067 | DeclContext *DC = NewVD->getDeclContext(); | |||
7068 | QualType R = NewVD->getType(); | |||
7069 | ||||
7070 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. | |||
7071 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function | |||
7072 | // argument. | |||
7073 | if (R->isImageType() || R->isPipeType()) { | |||
7074 | Se.Diag(NewVD->getLocation(), | |||
7075 | diag::err_opencl_type_can_only_be_used_as_function_parameter) | |||
7076 | << R; | |||
7077 | NewVD->setInvalidDecl(); | |||
7078 | return false; | |||
7079 | } | |||
7080 | ||||
7081 | // OpenCL v1.2 s6.9.r: | |||
7082 | // The event type cannot be used to declare a program scope variable. | |||
7083 | // OpenCL v2.0 s6.9.q: | |||
7084 | // The clk_event_t and reserve_id_t types cannot be declared in program | |||
7085 | // scope. | |||
7086 | if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) { | |||
7087 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { | |||
7088 | Se.Diag(NewVD->getLocation(), | |||
7089 | diag::err_invalid_type_for_program_scope_var) | |||
7090 | << R; | |||
7091 | NewVD->setInvalidDecl(); | |||
7092 | return false; | |||
7093 | } | |||
7094 | } | |||
7095 | ||||
7096 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. | |||
7097 | if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers", | |||
7098 | Se.getLangOpts())) { | |||
7099 | QualType NR = R.getCanonicalType(); | |||
7100 | while (NR->isPointerType() || NR->isMemberFunctionPointerType() || | |||
7101 | NR->isReferenceType()) { | |||
7102 | if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() || | |||
7103 | NR->isFunctionReferenceType()) { | |||
7104 | Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer) | |||
7105 | << NR->isReferenceType(); | |||
7106 | NewVD->setInvalidDecl(); | |||
7107 | return false; | |||
7108 | } | |||
7109 | NR = NR->getPointeeType(); | |||
7110 | } | |||
7111 | } | |||
7112 | ||||
7113 | if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16", | |||
7114 | Se.getLangOpts())) { | |||
7115 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and | |||
7116 | // half array type (unless the cl_khr_fp16 extension is enabled). | |||
7117 | if (Se.Context.getBaseElementType(R)->isHalfType()) { | |||
7118 | Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R; | |||
7119 | NewVD->setInvalidDecl(); | |||
7120 | return false; | |||
7121 | } | |||
7122 | } | |||
7123 | ||||
7124 | // OpenCL v1.2 s6.9.r: | |||
7125 | // The event type cannot be used with the __local, __constant and __global | |||
7126 | // address space qualifiers. | |||
7127 | if (R->isEventT()) { | |||
7128 | if (R.getAddressSpace() != LangAS::opencl_private) { | |||
7129 | Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual); | |||
7130 | NewVD->setInvalidDecl(); | |||
7131 | return false; | |||
7132 | } | |||
7133 | } | |||
7134 | ||||
7135 | if (R->isSamplerT()) { | |||
7136 | // OpenCL v1.2 s6.9.b p4: | |||
7137 | // The sampler type cannot be used with the __local and __global address | |||
7138 | // space qualifiers. | |||
7139 | if (R.getAddressSpace() == LangAS::opencl_local || | |||
7140 | R.getAddressSpace() == LangAS::opencl_global) { | |||
7141 | Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace); | |||
7142 | NewVD->setInvalidDecl(); | |||
7143 | } | |||
7144 | ||||
7145 | // OpenCL v1.2 s6.12.14.1: | |||
7146 | // A global sampler must be declared with either the constant address | |||
7147 | // space qualifier or with the const qualifier. | |||
7148 | if (DC->isTranslationUnit() && | |||
7149 | !(R.getAddressSpace() == LangAS::opencl_constant || | |||
7150 | R.isConstQualified())) { | |||
7151 | Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler); | |||
7152 | NewVD->setInvalidDecl(); | |||
7153 | } | |||
7154 | if (NewVD->isInvalidDecl()) | |||
7155 | return false; | |||
7156 | } | |||
7157 | ||||
7158 | return true; | |||
7159 | } | |||
7160 | ||||
7161 | template <typename AttrTy> | |||
7162 | static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) { | |||
7163 | const TypedefNameDecl *TND = TT->getDecl(); | |||
7164 | if (const auto *Attribute = TND->getAttr<AttrTy>()) { | |||
7165 | AttrTy *Clone = Attribute->clone(S.Context); | |||
7166 | Clone->setInherited(true); | |||
7167 | D->addAttr(Clone); | |||
7168 | } | |||
7169 | } | |||
7170 | ||||
7171 | NamedDecl *Sema::ActOnVariableDeclarator( | |||
7172 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, | |||
7173 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, | |||
7174 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { | |||
7175 | QualType R = TInfo->getType(); | |||
7176 | DeclarationName Name = GetNameForDeclarator(D).getName(); | |||
7177 | ||||
7178 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
7179 | ||||
7180 | if (D.isDecompositionDeclarator()) { | |||
7181 | // Take the name of the first declarator as our name for diagnostic | |||
7182 | // purposes. | |||
7183 | auto &Decomp = D.getDecompositionDeclarator(); | |||
7184 | if (!Decomp.bindings().empty()) { | |||
7185 | II = Decomp.bindings()[0].Name; | |||
7186 | Name = II; | |||
7187 | } | |||
7188 | } else if (!II) { | |||
7189 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; | |||
7190 | return nullptr; | |||
7191 | } | |||
7192 | ||||
7193 | ||||
7194 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); | |||
7195 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); | |||
7196 | ||||
7197 | // dllimport globals without explicit storage class are treated as extern. We | |||
7198 | // have to change the storage class this early to get the right DeclContext. | |||
7199 | if (SC == SC_None && !DC->isRecord() && | |||
7200 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && | |||
7201 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) | |||
7202 | SC = SC_Extern; | |||
7203 | ||||
7204 | DeclContext *OriginalDC = DC; | |||
7205 | bool IsLocalExternDecl = SC == SC_Extern && | |||
7206 | adjustContextForLocalExternDecl(DC); | |||
7207 | ||||
7208 | if (SCSpec == DeclSpec::SCS_mutable) { | |||
7209 | // mutable can only appear on non-static class members, so it's always | |||
7210 | // an error here | |||
7211 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); | |||
7212 | D.setInvalidType(); | |||
7213 | SC = SC_None; | |||
7214 | } | |||
7215 | ||||
7216 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && | |||
7217 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( | |||
7218 | D.getDeclSpec().getStorageClassSpecLoc())) { | |||
7219 | // In C++11, the 'register' storage class specifier is deprecated. | |||
7220 | // Suppress the warning in system macros, it's used in macros in some | |||
7221 | // popular C system headers, such as in glibc's htonl() macro. | |||
7222 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
7223 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | |||
7224 | : diag::warn_deprecated_register) | |||
7225 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
7226 | } | |||
7227 | ||||
7228 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
7229 | ||||
7230 | if (!DC->isRecord() && S->getFnParent() == nullptr) { | |||
7231 | // C99 6.9p2: The storage-class specifiers auto and register shall not | |||
7232 | // appear in the declaration specifiers in an external declaration. | |||
7233 | // Global Register+Asm is a GNU extension we support. | |||
7234 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { | |||
7235 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); | |||
7236 | D.setInvalidType(); | |||
7237 | } | |||
7238 | } | |||
7239 | ||||
7240 | // If this variable has a VLA type and an initializer, try to | |||
7241 | // fold to a constant-sized type. This is otherwise invalid. | |||
7242 | if (D.hasInitializer() && R->isVariableArrayType()) | |||
7243 | tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(), | |||
7244 | /*DiagID=*/0); | |||
7245 | ||||
7246 | bool IsMemberSpecialization = false; | |||
7247 | bool IsVariableTemplateSpecialization = false; | |||
7248 | bool IsPartialSpecialization = false; | |||
7249 | bool IsVariableTemplate = false; | |||
7250 | VarDecl *NewVD = nullptr; | |||
7251 | VarTemplateDecl *NewTemplate = nullptr; | |||
7252 | TemplateParameterList *TemplateParams = nullptr; | |||
7253 | if (!getLangOpts().CPlusPlus) { | |||
7254 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), | |||
7255 | II, R, TInfo, SC); | |||
7256 | ||||
7257 | if (R->getContainedDeducedType()) | |||
7258 | ParsingInitForAutoVars.insert(NewVD); | |||
7259 | ||||
7260 | if (D.isInvalidType()) | |||
7261 | NewVD->setInvalidDecl(); | |||
7262 | ||||
7263 | if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && | |||
7264 | NewVD->hasLocalStorage()) | |||
7265 | checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), | |||
7266 | NTCUC_AutoVar, NTCUK_Destruct); | |||
7267 | } else { | |||
7268 | bool Invalid = false; | |||
7269 | ||||
7270 | if (DC->isRecord() && !CurContext->isRecord()) { | |||
7271 | // This is an out-of-line definition of a static data member. | |||
7272 | switch (SC) { | |||
7273 | case SC_None: | |||
7274 | break; | |||
7275 | case SC_Static: | |||
7276 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
7277 | diag::err_static_out_of_line) | |||
7278 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
7279 | break; | |||
7280 | case SC_Auto: | |||
7281 | case SC_Register: | |||
7282 | case SC_Extern: | |||
7283 | // [dcl.stc] p2: The auto or register specifiers shall be applied only | |||
7284 | // to names of variables declared in a block or to function parameters. | |||
7285 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration | |||
7286 | // of class members | |||
7287 | ||||
7288 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
7289 | diag::err_storage_class_for_static_member) | |||
7290 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
7291 | break; | |||
7292 | case SC_PrivateExtern: | |||
7293 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "clang/lib/Sema/SemaDecl.cpp" , 7293); | |||
7294 | } | |||
7295 | } | |||
7296 | ||||
7297 | if (SC == SC_Static && CurContext->isRecord()) { | |||
7298 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { | |||
7299 | // Walk up the enclosing DeclContexts to check for any that are | |||
7300 | // incompatible with static data members. | |||
7301 | const DeclContext *FunctionOrMethod = nullptr; | |||
7302 | const CXXRecordDecl *AnonStruct = nullptr; | |||
7303 | for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { | |||
7304 | if (Ctxt->isFunctionOrMethod()) { | |||
7305 | FunctionOrMethod = Ctxt; | |||
7306 | break; | |||
7307 | } | |||
7308 | const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); | |||
7309 | if (ParentDecl && !ParentDecl->getDeclName()) { | |||
7310 | AnonStruct = ParentDecl; | |||
7311 | break; | |||
7312 | } | |||
7313 | } | |||
7314 | if (FunctionOrMethod) { | |||
7315 | // C++ [class.static.data]p5: A local class shall not have static data | |||
7316 | // members. | |||
7317 | Diag(D.getIdentifierLoc(), | |||
7318 | diag::err_static_data_member_not_allowed_in_local_class) | |||
7319 | << Name << RD->getDeclName() << RD->getTagKind(); | |||
7320 | } else if (AnonStruct) { | |||
7321 | // C++ [class.static.data]p4: Unnamed classes and classes contained | |||
7322 | // directly or indirectly within unnamed classes shall not contain | |||
7323 | // static data members. | |||
7324 | Diag(D.getIdentifierLoc(), | |||
7325 | diag::err_static_data_member_not_allowed_in_anon_struct) | |||
7326 | << Name << AnonStruct->getTagKind(); | |||
7327 | Invalid = true; | |||
7328 | } else if (RD->isUnion()) { | |||
7329 | // C++98 [class.union]p1: If a union contains a static data member, | |||
7330 | // the program is ill-formed. C++11 drops this restriction. | |||
7331 | Diag(D.getIdentifierLoc(), | |||
7332 | getLangOpts().CPlusPlus11 | |||
7333 | ? diag::warn_cxx98_compat_static_data_member_in_union | |||
7334 | : diag::ext_static_data_member_in_union) << Name; | |||
7335 | } | |||
7336 | } | |||
7337 | } | |||
7338 | ||||
7339 | // Match up the template parameter lists with the scope specifier, then | |||
7340 | // determine whether we have a template or a template specialization. | |||
7341 | bool InvalidScope = false; | |||
7342 | TemplateParams = MatchTemplateParametersToScopeSpecifier( | |||
7343 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | |||
7344 | D.getCXXScopeSpec(), | |||
7345 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | |||
7346 | ? D.getName().TemplateId | |||
7347 | : nullptr, | |||
7348 | TemplateParamLists, | |||
7349 | /*never a friend*/ false, IsMemberSpecialization, InvalidScope); | |||
7350 | Invalid |= InvalidScope; | |||
7351 | ||||
7352 | if (TemplateParams) { | |||
7353 | if (!TemplateParams->size() && | |||
7354 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | |||
7355 | // There is an extraneous 'template<>' for this variable. Complain | |||
7356 | // about it, but allow the declaration of the variable. | |||
7357 | Diag(TemplateParams->getTemplateLoc(), | |||
7358 | diag::err_template_variable_noparams) | |||
7359 | << II | |||
7360 | << SourceRange(TemplateParams->getTemplateLoc(), | |||
7361 | TemplateParams->getRAngleLoc()); | |||
7362 | TemplateParams = nullptr; | |||
7363 | } else { | |||
7364 | // Check that we can declare a template here. | |||
7365 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
7366 | return nullptr; | |||
7367 | ||||
7368 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
7369 | // This is an explicit specialization or a partial specialization. | |||
7370 | IsVariableTemplateSpecialization = true; | |||
7371 | IsPartialSpecialization = TemplateParams->size() > 0; | |||
7372 | } else { // if (TemplateParams->size() > 0) | |||
7373 | // This is a template declaration. | |||
7374 | IsVariableTemplate = true; | |||
7375 | ||||
7376 | // Only C++1y supports variable templates (N3651). | |||
7377 | Diag(D.getIdentifierLoc(), | |||
7378 | getLangOpts().CPlusPlus14 | |||
7379 | ? diag::warn_cxx11_compat_variable_template | |||
7380 | : diag::ext_variable_template); | |||
7381 | } | |||
7382 | } | |||
7383 | } else { | |||
7384 | // Check that we can declare a member specialization here. | |||
7385 | if (!TemplateParamLists.empty() && IsMemberSpecialization && | |||
7386 | CheckTemplateDeclScope(S, TemplateParamLists.back())) | |||
7387 | return nullptr; | |||
7388 | assert((Invalid ||(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 7390, __extension__ __PRETTY_FUNCTION__ )) | |||
7389 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 7390, __extension__ __PRETTY_FUNCTION__ )) | |||
7390 | "should have a 'template<>' for this decl")(static_cast <bool> ((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 7390, __extension__ __PRETTY_FUNCTION__ )); | |||
7391 | } | |||
7392 | ||||
7393 | if (IsVariableTemplateSpecialization) { | |||
7394 | SourceLocation TemplateKWLoc = | |||
7395 | TemplateParamLists.size() > 0 | |||
7396 | ? TemplateParamLists[0]->getTemplateLoc() | |||
7397 | : SourceLocation(); | |||
7398 | DeclResult Res = ActOnVarTemplateSpecialization( | |||
7399 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, | |||
7400 | IsPartialSpecialization); | |||
7401 | if (Res.isInvalid()) | |||
7402 | return nullptr; | |||
7403 | NewVD = cast<VarDecl>(Res.get()); | |||
7404 | AddToScope = false; | |||
7405 | } else if (D.isDecompositionDeclarator()) { | |||
7406 | NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), | |||
7407 | D.getIdentifierLoc(), R, TInfo, SC, | |||
7408 | Bindings); | |||
7409 | } else | |||
7410 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), | |||
7411 | D.getIdentifierLoc(), II, R, TInfo, SC); | |||
7412 | ||||
7413 | // If this is supposed to be a variable template, create it as such. | |||
7414 | if (IsVariableTemplate) { | |||
7415 | NewTemplate = | |||
7416 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, | |||
7417 | TemplateParams, NewVD); | |||
7418 | NewVD->setDescribedVarTemplate(NewTemplate); | |||
7419 | } | |||
7420 | ||||
7421 | // If this decl has an auto type in need of deduction, make a note of the | |||
7422 | // Decl so we can diagnose uses of it in its own initializer. | |||
7423 | if (R->getContainedDeducedType()) | |||
7424 | ParsingInitForAutoVars.insert(NewVD); | |||
7425 | ||||
7426 | if (D.isInvalidType() || Invalid) { | |||
7427 | NewVD->setInvalidDecl(); | |||
7428 | if (NewTemplate) | |||
7429 | NewTemplate->setInvalidDecl(); | |||
7430 | } | |||
7431 | ||||
7432 | SetNestedNameSpecifier(*this, NewVD, D); | |||
7433 | ||||
7434 | // If we have any template parameter lists that don't directly belong to | |||
7435 | // the variable (matching the scope specifier), store them. | |||
7436 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; | |||
7437 | if (TemplateParamLists.size() > VDTemplateParamLists) | |||
7438 | NewVD->setTemplateParameterListsInfo( | |||
7439 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); | |||
7440 | } | |||
7441 | ||||
7442 | if (D.getDeclSpec().isInlineSpecified()) { | |||
7443 | if (!getLangOpts().CPlusPlus) { | |||
7444 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
7445 | << 0; | |||
7446 | } else if (CurContext->isFunctionOrMethod()) { | |||
7447 | // 'inline' is not allowed on block scope variable declaration. | |||
7448 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
7449 | diag::err_inline_declaration_block_scope) << Name | |||
7450 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | |||
7451 | } else { | |||
7452 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
7453 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable | |||
7454 | : diag::ext_inline_variable); | |||
7455 | NewVD->setInlineSpecified(); | |||
7456 | } | |||
7457 | } | |||
7458 | ||||
7459 | // Set the lexical context. If the declarator has a C++ scope specifier, the | |||
7460 | // lexical context will be different from the semantic context. | |||
7461 | NewVD->setLexicalDeclContext(CurContext); | |||
7462 | if (NewTemplate) | |||
7463 | NewTemplate->setLexicalDeclContext(CurContext); | |||
7464 | ||||
7465 | if (IsLocalExternDecl) { | |||
7466 | if (D.isDecompositionDeclarator()) | |||
7467 | for (auto *B : Bindings) | |||
7468 | B->setLocalExternDecl(); | |||
7469 | else | |||
7470 | NewVD->setLocalExternDecl(); | |||
7471 | } | |||
7472 | ||||
7473 | bool EmitTLSUnsupportedError = false; | |||
7474 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { | |||
7475 | // C++11 [dcl.stc]p4: | |||
7476 | // When thread_local is applied to a variable of block scope the | |||
7477 | // storage-class-specifier static is implied if it does not appear | |||
7478 | // explicitly. | |||
7479 | // Core issue: 'static' is not implied if the variable is declared | |||
7480 | // 'extern'. | |||
7481 | if (NewVD->hasLocalStorage() && | |||
7482 | (SCSpec != DeclSpec::SCS_unspecified || | |||
7483 | TSCS != DeclSpec::TSCS_thread_local || | |||
7484 | !DC->isFunctionOrMethod())) | |||
7485 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
7486 | diag::err_thread_non_global) | |||
7487 | << DeclSpec::getSpecifierName(TSCS); | |||
7488 | else if (!Context.getTargetInfo().isTLSSupported()) { | |||
7489 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || | |||
7490 | getLangOpts().SYCLIsDevice) { | |||
7491 | // Postpone error emission until we've collected attributes required to | |||
7492 | // figure out whether it's a host or device variable and whether the | |||
7493 | // error should be ignored. | |||
7494 | EmitTLSUnsupportedError = true; | |||
7495 | // We still need to mark the variable as TLS so it shows up in AST with | |||
7496 | // proper storage class for other tools to use even if we're not going | |||
7497 | // to emit any code for it. | |||
7498 | NewVD->setTSCSpec(TSCS); | |||
7499 | } else | |||
7500 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
7501 | diag::err_thread_unsupported); | |||
7502 | } else | |||
7503 | NewVD->setTSCSpec(TSCS); | |||
7504 | } | |||
7505 | ||||
7506 | switch (D.getDeclSpec().getConstexprSpecifier()) { | |||
7507 | case ConstexprSpecKind::Unspecified: | |||
7508 | break; | |||
7509 | ||||
7510 | case ConstexprSpecKind::Consteval: | |||
7511 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | |||
7512 | diag::err_constexpr_wrong_decl_kind) | |||
7513 | << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); | |||
7514 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
7515 | ||||
7516 | case ConstexprSpecKind::Constexpr: | |||
7517 | NewVD->setConstexpr(true); | |||
7518 | // C++1z [dcl.spec.constexpr]p1: | |||
7519 | // A static data member declared with the constexpr specifier is | |||
7520 | // implicitly an inline variable. | |||
7521 | if (NewVD->isStaticDataMember() && | |||
7522 | (getLangOpts().CPlusPlus17 || | |||
7523 | Context.getTargetInfo().getCXXABI().isMicrosoft())) | |||
7524 | NewVD->setImplicitlyInline(); | |||
7525 | break; | |||
7526 | ||||
7527 | case ConstexprSpecKind::Constinit: | |||
7528 | if (!NewVD->hasGlobalStorage()) | |||
7529 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | |||
7530 | diag::err_constinit_local_variable); | |||
7531 | else | |||
7532 | NewVD->addAttr(ConstInitAttr::Create( | |||
7533 | Context, D.getDeclSpec().getConstexprSpecLoc(), | |||
7534 | AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); | |||
7535 | break; | |||
7536 | } | |||
7537 | ||||
7538 | // C99 6.7.4p3 | |||
7539 | // An inline definition of a function with external linkage shall | |||
7540 | // not contain a definition of a modifiable object with static or | |||
7541 | // thread storage duration... | |||
7542 | // We only apply this when the function is required to be defined | |||
7543 | // elsewhere, i.e. when the function is not 'extern inline'. Note | |||
7544 | // that a local variable with thread storage duration still has to | |||
7545 | // be marked 'static'. Also note that it's possible to get these | |||
7546 | // semantics in C++ using __attribute__((gnu_inline)). | |||
7547 | if (SC == SC_Static && S->getFnParent() != nullptr && | |||
7548 | !NewVD->getType().isConstQualified()) { | |||
7549 | FunctionDecl *CurFD = getCurFunctionDecl(); | |||
7550 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { | |||
7551 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
7552 | diag::warn_static_local_in_extern_inline); | |||
7553 | MaybeSuggestAddingStaticToDecl(CurFD); | |||
7554 | } | |||
7555 | } | |||
7556 | ||||
7557 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
7558 | if (IsVariableTemplateSpecialization) | |||
7559 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | |||
7560 | << (IsPartialSpecialization ? 1 : 0) | |||
7561 | << FixItHint::CreateRemoval( | |||
7562 | D.getDeclSpec().getModulePrivateSpecLoc()); | |||
7563 | else if (IsMemberSpecialization) | |||
7564 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | |||
7565 | << 2 | |||
7566 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
7567 | else if (NewVD->hasLocalStorage()) | |||
7568 | Diag(NewVD->getLocation(), diag::err_module_private_local) | |||
7569 | << 0 << NewVD | |||
7570 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
7571 | << FixItHint::CreateRemoval( | |||
7572 | D.getDeclSpec().getModulePrivateSpecLoc()); | |||
7573 | else { | |||
7574 | NewVD->setModulePrivate(); | |||
7575 | if (NewTemplate) | |||
7576 | NewTemplate->setModulePrivate(); | |||
7577 | for (auto *B : Bindings) | |||
7578 | B->setModulePrivate(); | |||
7579 | } | |||
7580 | } | |||
7581 | ||||
7582 | if (getLangOpts().OpenCL) { | |||
7583 | deduceOpenCLAddressSpace(NewVD); | |||
7584 | ||||
7585 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); | |||
7586 | if (TSC != TSCS_unspecified) { | |||
7587 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
7588 | diag::err_opencl_unknown_type_specifier) | |||
7589 | << getLangOpts().getOpenCLVersionString() | |||
7590 | << DeclSpec::getSpecifierName(TSC) << 1; | |||
7591 | NewVD->setInvalidDecl(); | |||
7592 | } | |||
7593 | } | |||
7594 | ||||
7595 | // Handle attributes prior to checking for duplicates in MergeVarDecl | |||
7596 | ProcessDeclAttributes(S, NewVD, D); | |||
7597 | ||||
7598 | // FIXME: This is probably the wrong location to be doing this and we should | |||
7599 | // probably be doing this for more attributes (especially for function | |||
7600 | // pointer attributes such as format, warn_unused_result, etc.). Ideally | |||
7601 | // the code to copy attributes would be generated by TableGen. | |||
7602 | if (R->isFunctionPointerType()) | |||
7603 | if (const auto *TT = R->getAs<TypedefType>()) | |||
7604 | copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT); | |||
7605 | ||||
7606 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || | |||
7607 | getLangOpts().SYCLIsDevice) { | |||
7608 | if (EmitTLSUnsupportedError && | |||
7609 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || | |||
7610 | (getLangOpts().OpenMPIsDevice && | |||
7611 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) | |||
7612 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
7613 | diag::err_thread_unsupported); | |||
7614 | ||||
7615 | if (EmitTLSUnsupportedError && | |||
7616 | (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) | |||
7617 | targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); | |||
7618 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static | |||
7619 | // storage [duration]." | |||
7620 | if (SC == SC_None && S->getFnParent() != nullptr && | |||
7621 | (NewVD->hasAttr<CUDASharedAttr>() || | |||
7622 | NewVD->hasAttr<CUDAConstantAttr>())) { | |||
7623 | NewVD->setStorageClass(SC_Static); | |||
7624 | } | |||
7625 | } | |||
7626 | ||||
7627 | // Ensure that dllimport globals without explicit storage class are treated as | |||
7628 | // extern. The storage class is set above using parsed attributes. Now we can | |||
7629 | // check the VarDecl itself. | |||
7630 | assert(!NewVD->hasAttr<DLLImportAttr>() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "clang/lib/Sema/SemaDecl.cpp", 7632, __extension__ __PRETTY_FUNCTION__ )) | |||
7631 | NewVD->getAttr<DLLImportAttr>()->isInherited() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "clang/lib/Sema/SemaDecl.cpp", 7632, __extension__ __PRETTY_FUNCTION__ )) | |||
7632 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr >() || NewVD->getAttr<DLLImportAttr>()->isInherited () || NewVD->isStaticDataMember() || NewVD->getStorageClass () != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "clang/lib/Sema/SemaDecl.cpp", 7632, __extension__ __PRETTY_FUNCTION__ )); | |||
7633 | ||||
7634 | // In auto-retain/release, infer strong retension for variables of | |||
7635 | // retainable type. | |||
7636 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) | |||
7637 | NewVD->setInvalidDecl(); | |||
7638 | ||||
7639 | // Handle GNU asm-label extension (encoded as an attribute). | |||
7640 | if (Expr *E = (Expr*)D.getAsmLabel()) { | |||
7641 | // The parser guarantees this is a string. | |||
7642 | StringLiteral *SE = cast<StringLiteral>(E); | |||
7643 | StringRef Label = SE->getString(); | |||
7644 | if (S->getFnParent() != nullptr) { | |||
7645 | switch (SC) { | |||
7646 | case SC_None: | |||
7647 | case SC_Auto: | |||
7648 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; | |||
7649 | break; | |||
7650 | case SC_Register: | |||
7651 | // Local Named register | |||
7652 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && | |||
7653 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) | |||
7654 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | |||
7655 | break; | |||
7656 | case SC_Static: | |||
7657 | case SC_Extern: | |||
7658 | case SC_PrivateExtern: | |||
7659 | break; | |||
7660 | } | |||
7661 | } else if (SC == SC_Register) { | |||
7662 | // Global Named register | |||
7663 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { | |||
7664 | const auto &TI = Context.getTargetInfo(); | |||
7665 | bool HasSizeMismatch; | |||
7666 | ||||
7667 | if (!TI.isValidGCCRegisterName(Label)) | |||
7668 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | |||
7669 | else if (!TI.validateGlobalRegisterVariable(Label, | |||
7670 | Context.getTypeSize(R), | |||
7671 | HasSizeMismatch)) | |||
7672 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; | |||
7673 | else if (HasSizeMismatch) | |||
7674 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; | |||
7675 | } | |||
7676 | ||||
7677 | if (!R->isIntegralType(Context) && !R->isPointerType()) { | |||
7678 | Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); | |||
7679 | NewVD->setInvalidDecl(true); | |||
7680 | } | |||
7681 | } | |||
7682 | ||||
7683 | NewVD->addAttr(AsmLabelAttr::Create(Context, Label, | |||
7684 | /*IsLiteralLabel=*/true, | |||
7685 | SE->getStrTokenLoc(0))); | |||
7686 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | |||
7687 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | |||
7688 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); | |||
7689 | if (I != ExtnameUndeclaredIdentifiers.end()) { | |||
7690 | if (isDeclExternC(NewVD)) { | |||
7691 | NewVD->addAttr(I->second); | |||
7692 | ExtnameUndeclaredIdentifiers.erase(I); | |||
7693 | } else | |||
7694 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) | |||
7695 | << /*Variable*/1 << NewVD; | |||
7696 | } | |||
7697 | } | |||
7698 | ||||
7699 | // Find the shadowed declaration before filtering for scope. | |||
7700 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() | |||
7701 | ? getShadowedDeclaration(NewVD, Previous) | |||
7702 | : nullptr; | |||
7703 | ||||
7704 | // Don't consider existing declarations that are in a different | |||
7705 | // scope and are out-of-semantic-context declarations (if the new | |||
7706 | // declaration has linkage). | |||
7707 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), | |||
7708 | D.getCXXScopeSpec().isNotEmpty() || | |||
7709 | IsMemberSpecialization || | |||
7710 | IsVariableTemplateSpecialization); | |||
7711 | ||||
7712 | // Check whether the previous declaration is in the same block scope. This | |||
7713 | // affects whether we merge types with it, per C++11 [dcl.array]p3. | |||
7714 | if (getLangOpts().CPlusPlus && | |||
7715 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) | |||
7716 | NewVD->setPreviousDeclInSameBlockScope( | |||
7717 | Previous.isSingleResult() && !Previous.isShadowed() && | |||
7718 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); | |||
7719 | ||||
7720 | if (!getLangOpts().CPlusPlus) { | |||
7721 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | |||
7722 | } else { | |||
7723 | // If this is an explicit specialization of a static data member, check it. | |||
7724 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && | |||
7725 | CheckMemberSpecialization(NewVD, Previous)) | |||
7726 | NewVD->setInvalidDecl(); | |||
7727 | ||||
7728 | // Merge the decl with the existing one if appropriate. | |||
7729 | if (!Previous.empty()) { | |||
7730 | if (Previous.isSingleResult() && | |||
7731 | isa<FieldDecl>(Previous.getFoundDecl()) && | |||
7732 | D.getCXXScopeSpec().isSet()) { | |||
7733 | // The user tried to define a non-static data member | |||
7734 | // out-of-line (C++ [dcl.meaning]p1). | |||
7735 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) | |||
7736 | << D.getCXXScopeSpec().getRange(); | |||
7737 | Previous.clear(); | |||
7738 | NewVD->setInvalidDecl(); | |||
7739 | } | |||
7740 | } else if (D.getCXXScopeSpec().isSet()) { | |||
7741 | // No previous declaration in the qualifying scope. | |||
7742 | Diag(D.getIdentifierLoc(), diag::err_no_member) | |||
7743 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) | |||
7744 | << D.getCXXScopeSpec().getRange(); | |||
7745 | NewVD->setInvalidDecl(); | |||
7746 | } | |||
7747 | ||||
7748 | if (!IsVariableTemplateSpecialization) | |||
7749 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | |||
7750 | ||||
7751 | if (NewTemplate) { | |||
7752 | VarTemplateDecl *PrevVarTemplate = | |||
7753 | NewVD->getPreviousDecl() | |||
7754 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() | |||
7755 | : nullptr; | |||
7756 | ||||
7757 | // Check the template parameter list of this declaration, possibly | |||
7758 | // merging in the template parameter list from the previous variable | |||
7759 | // template declaration. | |||
7760 | if (CheckTemplateParameterList( | |||
7761 | TemplateParams, | |||
7762 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() | |||
7763 | : nullptr, | |||
7764 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && | |||
7765 | DC->isDependentContext()) | |||
7766 | ? TPC_ClassTemplateMember | |||
7767 | : TPC_VarTemplate)) | |||
7768 | NewVD->setInvalidDecl(); | |||
7769 | ||||
7770 | // If we are providing an explicit specialization of a static variable | |||
7771 | // template, make a note of that. | |||
7772 | if (PrevVarTemplate && | |||
7773 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) | |||
7774 | PrevVarTemplate->setMemberSpecialization(); | |||
7775 | } | |||
7776 | } | |||
7777 | ||||
7778 | // Diagnose shadowed variables iff this isn't a redeclaration. | |||
7779 | if (ShadowedDecl && !D.isRedeclaration()) | |||
7780 | CheckShadow(NewVD, ShadowedDecl, Previous); | |||
7781 | ||||
7782 | ProcessPragmaWeak(S, NewVD); | |||
7783 | ||||
7784 | // If this is the first declaration of an extern C variable, update | |||
7785 | // the map of such variables. | |||
7786 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && | |||
7787 | isIncompleteDeclExternC(*this, NewVD)) | |||
7788 | RegisterLocallyScopedExternCDecl(NewVD, S); | |||
7789 | ||||
7790 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | |||
7791 | MangleNumberingContext *MCtx; | |||
7792 | Decl *ManglingContextDecl; | |||
7793 | std::tie(MCtx, ManglingContextDecl) = | |||
7794 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | |||
7795 | if (MCtx) { | |||
7796 | Context.setManglingNumber( | |||
7797 | NewVD, MCtx->getManglingNumber( | |||
7798 | NewVD, getMSManglingNumber(getLangOpts(), S))); | |||
7799 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | |||
7800 | } | |||
7801 | } | |||
7802 | ||||
7803 | // Special handling of variable named 'main'. | |||
7804 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && | |||
7805 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && | |||
7806 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { | |||
7807 | ||||
7808 | // C++ [basic.start.main]p3 | |||
7809 | // A program that declares a variable main at global scope is ill-formed. | |||
7810 | if (getLangOpts().CPlusPlus) | |||
7811 | Diag(D.getBeginLoc(), diag::err_main_global_variable); | |||
7812 | ||||
7813 | // In C, and external-linkage variable named main results in undefined | |||
7814 | // behavior. | |||
7815 | else if (NewVD->hasExternalFormalLinkage()) | |||
7816 | Diag(D.getBeginLoc(), diag::warn_main_redefined); | |||
7817 | } | |||
7818 | ||||
7819 | if (D.isRedeclaration() && !Previous.empty()) { | |||
7820 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | |||
7821 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, | |||
7822 | D.isFunctionDefinition()); | |||
7823 | } | |||
7824 | ||||
7825 | if (NewTemplate) { | |||
7826 | if (NewVD->isInvalidDecl()) | |||
7827 | NewTemplate->setInvalidDecl(); | |||
7828 | ActOnDocumentableDecl(NewTemplate); | |||
7829 | return NewTemplate; | |||
7830 | } | |||
7831 | ||||
7832 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) | |||
7833 | CompleteMemberSpecialization(NewVD, Previous); | |||
7834 | ||||
7835 | return NewVD; | |||
7836 | } | |||
7837 | ||||
7838 | /// Enum describing the %select options in diag::warn_decl_shadow. | |||
7839 | enum ShadowedDeclKind { | |||
7840 | SDK_Local, | |||
7841 | SDK_Global, | |||
7842 | SDK_StaticMember, | |||
7843 | SDK_Field, | |||
7844 | SDK_Typedef, | |||
7845 | SDK_Using, | |||
7846 | SDK_StructuredBinding | |||
7847 | }; | |||
7848 | ||||
7849 | /// Determine what kind of declaration we're shadowing. | |||
7850 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, | |||
7851 | const DeclContext *OldDC) { | |||
7852 | if (isa<TypeAliasDecl>(ShadowedDecl)) | |||
7853 | return SDK_Using; | |||
7854 | else if (isa<TypedefDecl>(ShadowedDecl)) | |||
7855 | return SDK_Typedef; | |||
7856 | else if (isa<BindingDecl>(ShadowedDecl)) | |||
7857 | return SDK_StructuredBinding; | |||
7858 | else if (isa<RecordDecl>(OldDC)) | |||
7859 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; | |||
7860 | ||||
7861 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; | |||
7862 | } | |||
7863 | ||||
7864 | /// Return the location of the capture if the given lambda captures the given | |||
7865 | /// variable \p VD, or an invalid source location otherwise. | |||
7866 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, | |||
7867 | const VarDecl *VD) { | |||
7868 | for (const Capture &Capture : LSI->Captures) { | |||
7869 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) | |||
7870 | return Capture.getLocation(); | |||
7871 | } | |||
7872 | return SourceLocation(); | |||
7873 | } | |||
7874 | ||||
7875 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, | |||
7876 | const LookupResult &R) { | |||
7877 | // Only diagnose if we're shadowing an unambiguous field or variable. | |||
7878 | if (R.getResultKind() != LookupResult::Found) | |||
7879 | return false; | |||
7880 | ||||
7881 | // Return false if warning is ignored. | |||
7882 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); | |||
7883 | } | |||
7884 | ||||
7885 | /// Return the declaration shadowed by the given variable \p D, or null | |||
7886 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | |||
7887 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, | |||
7888 | const LookupResult &R) { | |||
7889 | if (!shouldWarnIfShadowedDecl(Diags, R)) | |||
7890 | return nullptr; | |||
7891 | ||||
7892 | // Don't diagnose declarations at file scope. | |||
7893 | if (D->hasGlobalStorage()) | |||
7894 | return nullptr; | |||
7895 | ||||
7896 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | |||
7897 | return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl | |||
7898 | : nullptr; | |||
7899 | } | |||
7900 | ||||
7901 | /// Return the declaration shadowed by the given typedef \p D, or null | |||
7902 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | |||
7903 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, | |||
7904 | const LookupResult &R) { | |||
7905 | // Don't warn if typedef declaration is part of a class | |||
7906 | if (D->getDeclContext()->isRecord()) | |||
7907 | return nullptr; | |||
7908 | ||||
7909 | if (!shouldWarnIfShadowedDecl(Diags, R)) | |||
7910 | return nullptr; | |||
7911 | ||||
7912 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | |||
7913 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; | |||
7914 | } | |||
7915 | ||||
7916 | /// Return the declaration shadowed by the given variable \p D, or null | |||
7917 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | |||
7918 | NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D, | |||
7919 | const LookupResult &R) { | |||
7920 | if (!shouldWarnIfShadowedDecl(Diags, R)) | |||
7921 | return nullptr; | |||
7922 | ||||
7923 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | |||
7924 | return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl | |||
7925 | : nullptr; | |||
7926 | } | |||
7927 | ||||
7928 | /// Diagnose variable or built-in function shadowing. Implements | |||
7929 | /// -Wshadow. | |||
7930 | /// | |||
7931 | /// This method is called whenever a VarDecl is added to a "useful" | |||
7932 | /// scope. | |||
7933 | /// | |||
7934 | /// \param ShadowedDecl the declaration that is shadowed by the given variable | |||
7935 | /// \param R the lookup of the name | |||
7936 | /// | |||
7937 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | |||
7938 | const LookupResult &R) { | |||
7939 | DeclContext *NewDC = D->getDeclContext(); | |||
7940 | ||||
7941 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { | |||
7942 | // Fields are not shadowed by variables in C++ static methods. | |||
7943 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) | |||
7944 | if (MD->isStatic()) | |||
7945 | return; | |||
7946 | ||||
7947 | // Fields shadowed by constructor parameters are a special case. Usually | |||
7948 | // the constructor initializes the field with the parameter. | |||
7949 | if (isa<CXXConstructorDecl>(NewDC)) | |||
7950 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { | |||
7951 | // Remember that this was shadowed so we can either warn about its | |||
7952 | // modification or its existence depending on warning settings. | |||
7953 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); | |||
7954 | return; | |||
7955 | } | |||
7956 | } | |||
7957 | ||||
7958 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) | |||
7959 | if (shadowedVar->isExternC()) { | |||
7960 | // For shadowing external vars, make sure that we point to the global | |||
7961 | // declaration, not a locally scoped extern declaration. | |||
7962 | for (auto I : shadowedVar->redecls()) | |||
7963 | if (I->isFileVarDecl()) { | |||
7964 | ShadowedDecl = I; | |||
7965 | break; | |||
7966 | } | |||
7967 | } | |||
7968 | ||||
7969 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); | |||
7970 | ||||
7971 | unsigned WarningDiag = diag::warn_decl_shadow; | |||
7972 | SourceLocation CaptureLoc; | |||
7973 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && | |||
7974 | isa<CXXMethodDecl>(NewDC)) { | |||
7975 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { | |||
7976 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { | |||
7977 | if (RD->getLambdaCaptureDefault() == LCD_None) { | |||
7978 | // Try to avoid warnings for lambdas with an explicit capture list. | |||
7979 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); | |||
7980 | // Warn only when the lambda captures the shadowed decl explicitly. | |||
7981 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); | |||
7982 | if (CaptureLoc.isInvalid()) | |||
7983 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; | |||
7984 | } else { | |||
7985 | // Remember that this was shadowed so we can avoid the warning if the | |||
7986 | // shadowed decl isn't captured and the warning settings allow it. | |||
7987 | cast<LambdaScopeInfo>(getCurFunction()) | |||
7988 | ->ShadowingDecls.push_back( | |||
7989 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); | |||
7990 | return; | |||
7991 | } | |||
7992 | } | |||
7993 | ||||
7994 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { | |||
7995 | // A variable can't shadow a local variable in an enclosing scope, if | |||
7996 | // they are separated by a non-capturing declaration context. | |||
7997 | for (DeclContext *ParentDC = NewDC; | |||
7998 | ParentDC && !ParentDC->Equals(OldDC); | |||
7999 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { | |||
8000 | // Only block literals, captured statements, and lambda expressions | |||
8001 | // can capture; other scopes don't. | |||
8002 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && | |||
8003 | !isLambdaCallOperator(ParentDC)) { | |||
8004 | return; | |||
8005 | } | |||
8006 | } | |||
8007 | } | |||
8008 | } | |||
8009 | } | |||
8010 | ||||
8011 | // Only warn about certain kinds of shadowing for class members. | |||
8012 | if (NewDC && NewDC->isRecord()) { | |||
8013 | // In particular, don't warn about shadowing non-class members. | |||
8014 | if (!OldDC->isRecord()) | |||
8015 | return; | |||
8016 | ||||
8017 | // TODO: should we warn about static data members shadowing | |||
8018 | // static data members from base classes? | |||
8019 | ||||
8020 | // TODO: don't diagnose for inaccessible shadowed members. | |||
8021 | // This is hard to do perfectly because we might friend the | |||
8022 | // shadowing context, but that's just a false negative. | |||
8023 | } | |||
8024 | ||||
8025 | ||||
8026 | DeclarationName Name = R.getLookupName(); | |||
8027 | ||||
8028 | // Emit warning and note. | |||
8029 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); | |||
8030 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; | |||
8031 | if (!CaptureLoc.isInvalid()) | |||
8032 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | |||
8033 | << Name << /*explicitly*/ 1; | |||
8034 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
8035 | } | |||
8036 | ||||
8037 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD | |||
8038 | /// when these variables are captured by the lambda. | |||
8039 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { | |||
8040 | for (const auto &Shadow : LSI->ShadowingDecls) { | |||
8041 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; | |||
8042 | // Try to avoid the warning when the shadowed decl isn't captured. | |||
8043 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); | |||
8044 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | |||
8045 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() | |||
8046 | ? diag::warn_decl_shadow_uncaptured_local | |||
8047 | : diag::warn_decl_shadow) | |||
8048 | << Shadow.VD->getDeclName() | |||
8049 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; | |||
8050 | if (!CaptureLoc.isInvalid()) | |||
8051 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | |||
8052 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; | |||
8053 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
8054 | } | |||
8055 | } | |||
8056 | ||||
8057 | /// Check -Wshadow without the advantage of a previous lookup. | |||
8058 | void Sema::CheckShadow(Scope *S, VarDecl *D) { | |||
8059 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) | |||
8060 | return; | |||
8061 | ||||
8062 | LookupResult R(*this, D->getDeclName(), D->getLocation(), | |||
8063 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); | |||
8064 | LookupName(R, S); | |||
8065 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) | |||
8066 | CheckShadow(D, ShadowedDecl, R); | |||
8067 | } | |||
8068 | ||||
8069 | /// Check if 'E', which is an expression that is about to be modified, refers | |||
8070 | /// to a constructor parameter that shadows a field. | |||
8071 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { | |||
8072 | // Quickly ignore expressions that can't be shadowing ctor parameters. | |||
8073 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) | |||
8074 | return; | |||
8075 | E = E->IgnoreParenImpCasts(); | |||
8076 | auto *DRE = dyn_cast<DeclRefExpr>(E); | |||
8077 | if (!DRE) | |||
8078 | return; | |||
8079 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); | |||
8080 | auto I = ShadowingDecls.find(D); | |||
8081 | if (I == ShadowingDecls.end()) | |||
8082 | return; | |||
8083 | const NamedDecl *ShadowedDecl = I->second; | |||
8084 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | |||
8085 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; | |||
8086 | Diag(D->getLocation(), diag::note_var_declared_here) << D; | |||
8087 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | |||
8088 | ||||
8089 | // Avoid issuing multiple warnings about the same decl. | |||
8090 | ShadowingDecls.erase(I); | |||
8091 | } | |||
8092 | ||||
8093 | /// Check for conflict between this global or extern "C" declaration and | |||
8094 | /// previous global or extern "C" declarations. This is only used in C++. | |||
8095 | template<typename T> | |||
8096 | static bool checkGlobalOrExternCConflict( | |||
8097 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { | |||
8098 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")(static_cast <bool> (S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"" , "clang/lib/Sema/SemaDecl.cpp", 8098, __extension__ __PRETTY_FUNCTION__ )); | |||
8099 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); | |||
8100 | ||||
8101 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { | |||
8102 | // The common case: this global doesn't conflict with any extern "C" | |||
8103 | // declaration. | |||
8104 | return false; | |||
8105 | } | |||
8106 | ||||
8107 | if (Prev) { | |||
8108 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { | |||
8109 | // Both the old and new declarations have C language linkage. This is a | |||
8110 | // redeclaration. | |||
8111 | Previous.clear(); | |||
8112 | Previous.addDecl(Prev); | |||
8113 | return true; | |||
8114 | } | |||
8115 | ||||
8116 | // This is a global, non-extern "C" declaration, and there is a previous | |||
8117 | // non-global extern "C" declaration. Diagnose if this is a variable | |||
8118 | // declaration. | |||
8119 | if (!isa<VarDecl>(ND)) | |||
8120 | return false; | |||
8121 | } else { | |||
8122 | // The declaration is extern "C". Check for any declaration in the | |||
8123 | // translation unit which might conflict. | |||
8124 | if (IsGlobal) { | |||
8125 | // We have already performed the lookup into the translation unit. | |||
8126 | IsGlobal = false; | |||
8127 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
8128 | I != E; ++I) { | |||
8129 | if (isa<VarDecl>(*I)) { | |||
8130 | Prev = *I; | |||
8131 | break; | |||
8132 | } | |||
8133 | } | |||
8134 | } else { | |||
8135 | DeclContext::lookup_result R = | |||
8136 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); | |||
8137 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); | |||
8138 | I != E; ++I) { | |||
8139 | if (isa<VarDecl>(*I)) { | |||
8140 | Prev = *I; | |||
8141 | break; | |||
8142 | } | |||
8143 | // FIXME: If we have any other entity with this name in global scope, | |||
8144 | // the declaration is ill-formed, but that is a defect: it breaks the | |||
8145 | // 'stat' hack, for instance. Only variables can have mangled name | |||
8146 | // clashes with extern "C" declarations, so only they deserve a | |||
8147 | // diagnostic. | |||
8148 | } | |||
8149 | } | |||
8150 | ||||
8151 | if (!Prev) | |||
8152 | return false; | |||
8153 | } | |||
8154 | ||||
8155 | // Use the first declaration's location to ensure we point at something which | |||
8156 | // is lexically inside an extern "C" linkage-spec. | |||
8157 | assert(Prev && "should have found a previous declaration to diagnose")(static_cast <bool> (Prev && "should have found a previous declaration to diagnose" ) ? void (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"" , "clang/lib/Sema/SemaDecl.cpp", 8157, __extension__ __PRETTY_FUNCTION__ )); | |||
8158 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) | |||
8159 | Prev = FD->getFirstDecl(); | |||
8160 | else | |||
8161 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); | |||
8162 | ||||
8163 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) | |||
8164 | << IsGlobal << ND; | |||
8165 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) | |||
8166 | << IsGlobal; | |||
8167 | return false; | |||
8168 | } | |||
8169 | ||||
8170 | /// Apply special rules for handling extern "C" declarations. Returns \c true | |||
8171 | /// if we have found that this is a redeclaration of some prior entity. | |||
8172 | /// | |||
8173 | /// Per C++ [dcl.link]p6: | |||
8174 | /// Two declarations [for a function or variable] with C language linkage | |||
8175 | /// with the same name that appear in different scopes refer to the same | |||
8176 | /// [entity]. An entity with C language linkage shall not be declared with | |||
8177 | /// the same name as an entity in global scope. | |||
8178 | template<typename T> | |||
8179 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, | |||
8180 | LookupResult &Previous) { | |||
8181 | if (!S.getLangOpts().CPlusPlus) { | |||
8182 | // In C, when declaring a global variable, look for a corresponding 'extern' | |||
8183 | // variable declared in function scope. We don't need this in C++, because | |||
8184 | // we find local extern decls in the surrounding file-scope DeclContext. | |||
8185 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
8186 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { | |||
8187 | Previous.clear(); | |||
8188 | Previous.addDecl(Prev); | |||
8189 | return true; | |||
8190 | } | |||
8191 | } | |||
8192 | return false; | |||
8193 | } | |||
8194 | ||||
8195 | // A declaration in the translation unit can conflict with an extern "C" | |||
8196 | // declaration. | |||
8197 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) | |||
8198 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); | |||
8199 | ||||
8200 | // An extern "C" declaration can conflict with a declaration in the | |||
8201 | // translation unit or can be a redeclaration of an extern "C" declaration | |||
8202 | // in another scope. | |||
8203 | if (isIncompleteDeclExternC(S,ND)) | |||
8204 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); | |||
8205 | ||||
8206 | // Neither global nor extern "C": nothing to do. | |||
8207 | return false; | |||
8208 | } | |||
8209 | ||||
8210 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { | |||
8211 | // If the decl is already known invalid, don't check it. | |||
8212 | if (NewVD->isInvalidDecl()) | |||
8213 | return; | |||
8214 | ||||
8215 | QualType T = NewVD->getType(); | |||
8216 | ||||
8217 | // Defer checking an 'auto' type until its initializer is attached. | |||
8218 | if (T->isUndeducedType()) | |||
8219 | return; | |||
8220 | ||||
8221 | if (NewVD->hasAttrs()) | |||
8222 | CheckAlignasUnderalignment(NewVD); | |||
8223 | ||||
8224 | if (T->isObjCObjectType()) { | |||
8225 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) | |||
8226 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); | |||
8227 | T = Context.getObjCObjectPointerType(T); | |||
8228 | NewVD->setType(T); | |||
8229 | } | |||
8230 | ||||
8231 | // Emit an error if an address space was applied to decl with local storage. | |||
8232 | // This includes arrays of objects with address space qualifiers, but not | |||
8233 | // automatic variables that point to other address spaces. | |||
8234 | // ISO/IEC TR 18037 S5.1.2 | |||
8235 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && | |||
8236 | T.getAddressSpace() != LangAS::Default) { | |||
8237 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; | |||
8238 | NewVD->setInvalidDecl(); | |||
8239 | return; | |||
8240 | } | |||
8241 | ||||
8242 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program | |||
8243 | // scope. | |||
8244 | if (getLangOpts().OpenCLVersion == 120 && | |||
8245 | !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers", | |||
8246 | getLangOpts()) && | |||
8247 | NewVD->isStaticLocal()) { | |||
8248 | Diag(NewVD->getLocation(), diag::err_static_function_scope); | |||
8249 | NewVD->setInvalidDecl(); | |||
8250 | return; | |||
8251 | } | |||
8252 | ||||
8253 | if (getLangOpts().OpenCL) { | |||
8254 | if (!diagnoseOpenCLTypes(*this, NewVD)) | |||
8255 | return; | |||
8256 | ||||
8257 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. | |||
8258 | if (NewVD->hasAttr<BlocksAttr>()) { | |||
8259 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); | |||
8260 | return; | |||
8261 | } | |||
8262 | ||||
8263 | if (T->isBlockPointerType()) { | |||
8264 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and | |||
8265 | // can't use 'extern' storage class. | |||
8266 | if (!T.isConstQualified()) { | |||
8267 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) | |||
8268 | << 0 /*const*/; | |||
8269 | NewVD->setInvalidDecl(); | |||
8270 | return; | |||
8271 | } | |||
8272 | if (NewVD->hasExternalStorage()) { | |||
8273 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); | |||
8274 | NewVD->setInvalidDecl(); | |||
8275 | return; | |||
8276 | } | |||
8277 | } | |||
8278 | ||||
8279 | // FIXME: Adding local AS in C++ for OpenCL might make sense. | |||
8280 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || | |||
8281 | NewVD->hasExternalStorage()) { | |||
8282 | if (!T->isSamplerT() && !T->isDependentType() && | |||
8283 | !(T.getAddressSpace() == LangAS::opencl_constant || | |||
8284 | (T.getAddressSpace() == LangAS::opencl_global && | |||
8285 | getOpenCLOptions().areProgramScopeVariablesSupported( | |||
8286 | getLangOpts())))) { | |||
8287 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; | |||
8288 | if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts())) | |||
8289 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | |||
8290 | << Scope << "global or constant"; | |||
8291 | else | |||
8292 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | |||
8293 | << Scope << "constant"; | |||
8294 | NewVD->setInvalidDecl(); | |||
8295 | return; | |||
8296 | } | |||
8297 | } else { | |||
8298 | if (T.getAddressSpace() == LangAS::opencl_global) { | |||
8299 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
8300 | << 1 /*is any function*/ << "global"; | |||
8301 | NewVD->setInvalidDecl(); | |||
8302 | return; | |||
8303 | } | |||
8304 | if (T.getAddressSpace() == LangAS::opencl_constant || | |||
8305 | T.getAddressSpace() == LangAS::opencl_local) { | |||
8306 | FunctionDecl *FD = getCurFunctionDecl(); | |||
8307 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables | |||
8308 | // in functions. | |||
8309 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { | |||
8310 | if (T.getAddressSpace() == LangAS::opencl_constant) | |||
8311 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
8312 | << 0 /*non-kernel only*/ << "constant"; | |||
8313 | else | |||
8314 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | |||
8315 | << 0 /*non-kernel only*/ << "local"; | |||
8316 | NewVD->setInvalidDecl(); | |||
8317 | return; | |||
8318 | } | |||
8319 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be | |||
8320 | // in the outermost scope of a kernel function. | |||
8321 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { | |||
8322 | if (!getCurScope()->isFunctionScope()) { | |||
8323 | if (T.getAddressSpace() == LangAS::opencl_constant) | |||
8324 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | |||
8325 | << "constant"; | |||
8326 | else | |||
8327 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | |||
8328 | << "local"; | |||
8329 | NewVD->setInvalidDecl(); | |||
8330 | return; | |||
8331 | } | |||
8332 | } | |||
8333 | } else if (T.getAddressSpace() != LangAS::opencl_private && | |||
8334 | // If we are parsing a template we didn't deduce an addr | |||
8335 | // space yet. | |||
8336 | T.getAddressSpace() != LangAS::Default) { | |||
8337 | // Do not allow other address spaces on automatic variable. | |||
8338 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; | |||
8339 | NewVD->setInvalidDecl(); | |||
8340 | return; | |||
8341 | } | |||
8342 | } | |||
8343 | } | |||
8344 | ||||
8345 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() | |||
8346 | && !NewVD->hasAttr<BlocksAttr>()) { | |||
8347 | if (getLangOpts().getGC() != LangOptions::NonGC) | |||
8348 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); | |||
8349 | else { | |||
8350 | assert(!getLangOpts().ObjCAutoRefCount)(static_cast <bool> (!getLangOpts().ObjCAutoRefCount) ? void (0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "clang/lib/Sema/SemaDecl.cpp", 8350, __extension__ __PRETTY_FUNCTION__ )); | |||
8351 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); | |||
8352 | } | |||
8353 | } | |||
8354 | ||||
8355 | bool isVM = T->isVariablyModifiedType(); | |||
8356 | if (isVM || NewVD->hasAttr<CleanupAttr>() || | |||
8357 | NewVD->hasAttr<BlocksAttr>()) | |||
8358 | setFunctionHasBranchProtectedScope(); | |||
8359 | ||||
8360 | if ((isVM && NewVD->hasLinkage()) || | |||
8361 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { | |||
8362 | bool SizeIsNegative; | |||
8363 | llvm::APSInt Oversized; | |||
8364 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | |||
8365 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); | |||
8366 | QualType FixedT; | |||
8367 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) | |||
8368 | FixedT = FixedTInfo->getType(); | |||
8369 | else if (FixedTInfo) { | |||
8370 | // Type and type-as-written are canonically different. We need to fix up | |||
8371 | // both types separately. | |||
8372 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, | |||
8373 | Oversized); | |||
8374 | } | |||
8375 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { | |||
8376 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); | |||
8377 | // FIXME: This won't give the correct result for | |||
8378 | // int a[10][n]; | |||
8379 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); | |||
8380 | ||||
8381 | if (NewVD->isFileVarDecl()) | |||
8382 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) | |||
8383 | << SizeRange; | |||
8384 | else if (NewVD->isStaticLocal()) | |||
8385 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) | |||
8386 | << SizeRange; | |||
8387 | else | |||
8388 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) | |||
8389 | << SizeRange; | |||
8390 | NewVD->setInvalidDecl(); | |||
8391 | return; | |||
8392 | } | |||
8393 | ||||
8394 | if (!FixedTInfo) { | |||
8395 | if (NewVD->isFileVarDecl()) | |||
8396 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); | |||
8397 | else | |||
8398 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); | |||
8399 | NewVD->setInvalidDecl(); | |||
8400 | return; | |||
8401 | } | |||
8402 | ||||
8403 | Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant); | |||
8404 | NewVD->setType(FixedT); | |||
8405 | NewVD->setTypeSourceInfo(FixedTInfo); | |||
8406 | } | |||
8407 | ||||
8408 | if (T->isVoidType()) { | |||
8409 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names | |||
8410 | // of objects and functions. | |||
8411 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { | |||
8412 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) | |||
8413 | << T; | |||
8414 | NewVD->setInvalidDecl(); | |||
8415 | return; | |||
8416 | } | |||
8417 | } | |||
8418 | ||||
8419 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { | |||
8420 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); | |||
8421 | NewVD->setInvalidDecl(); | |||
8422 | return; | |||
8423 | } | |||
8424 | ||||
8425 | if (!NewVD->hasLocalStorage() && T->isSizelessType()) { | |||
8426 | Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; | |||
8427 | NewVD->setInvalidDecl(); | |||
8428 | return; | |||
8429 | } | |||
8430 | ||||
8431 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { | |||
8432 | Diag(NewVD->getLocation(), diag::err_block_on_vm); | |||
8433 | NewVD->setInvalidDecl(); | |||
8434 | return; | |||
8435 | } | |||
8436 | ||||
8437 | if (NewVD->isConstexpr() && !T->isDependentType() && | |||
8438 | RequireLiteralType(NewVD->getLocation(), T, | |||
8439 | diag::err_constexpr_var_non_literal)) { | |||
8440 | NewVD->setInvalidDecl(); | |||
8441 | return; | |||
8442 | } | |||
8443 | ||||
8444 | // PPC MMA non-pointer types are not allowed as non-local variable types. | |||
8445 | if (Context.getTargetInfo().getTriple().isPPC64() && | |||
8446 | !NewVD->isLocalVarDecl() && | |||
8447 | CheckPPCMMAType(T, NewVD->getLocation())) { | |||
8448 | NewVD->setInvalidDecl(); | |||
8449 | return; | |||
8450 | } | |||
8451 | } | |||
8452 | ||||
8453 | /// Perform semantic checking on a newly-created variable | |||
8454 | /// declaration. | |||
8455 | /// | |||
8456 | /// This routine performs all of the type-checking required for a | |||
8457 | /// variable declaration once it has been built. It is used both to | |||
8458 | /// check variables after they have been parsed and their declarators | |||
8459 | /// have been translated into a declaration, and to check variables | |||
8460 | /// that have been instantiated from a template. | |||
8461 | /// | |||
8462 | /// Sets NewVD->isInvalidDecl() if an error was encountered. | |||
8463 | /// | |||
8464 | /// Returns true if the variable declaration is a redeclaration. | |||
8465 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { | |||
8466 | CheckVariableDeclarationType(NewVD); | |||
8467 | ||||
8468 | // If the decl is already known invalid, don't check it. | |||
8469 | if (NewVD->isInvalidDecl()) | |||
8470 | return false; | |||
8471 | ||||
8472 | // If we did not find anything by this name, look for a non-visible | |||
8473 | // extern "C" declaration with the same name. | |||
8474 | if (Previous.empty() && | |||
8475 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) | |||
8476 | Previous.setShadowed(); | |||
8477 | ||||
8478 | if (!Previous.empty()) { | |||
8479 | MergeVarDecl(NewVD, Previous); | |||
8480 | return true; | |||
8481 | } | |||
8482 | return false; | |||
8483 | } | |||
8484 | ||||
8485 | /// AddOverriddenMethods - See if a method overrides any in the base classes, | |||
8486 | /// and if so, check that it's a valid override and remember it. | |||
8487 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { | |||
8488 | llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden; | |||
8489 | ||||
8490 | // Look for methods in base classes that this method might override. | |||
8491 | CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, | |||
8492 | /*DetectVirtual=*/false); | |||
8493 | auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | |||
8494 | CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl(); | |||
8495 | DeclarationName Name = MD->getDeclName(); | |||
8496 | ||||
8497 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
8498 | // We really want to find the base class destructor here. | |||
8499 | QualType T = Context.getTypeDeclType(BaseRecord); | |||
8500 | CanQualType CT = Context.getCanonicalType(T); | |||
8501 | Name = Context.DeclarationNames.getCXXDestructorName(CT); | |||
8502 | } | |||
8503 | ||||
8504 | for (NamedDecl *BaseND : BaseRecord->lookup(Name)) { | |||
8505 | CXXMethodDecl *BaseMD = | |||
8506 | dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl()); | |||
8507 | if (!BaseMD || !BaseMD->isVirtual() || | |||
8508 | IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false, | |||
8509 | /*ConsiderCudaAttrs=*/true, | |||
8510 | // C++2a [class.virtual]p2 does not consider requires | |||
8511 | // clauses when overriding. | |||
8512 | /*ConsiderRequiresClauses=*/false)) | |||
8513 | continue; | |||
8514 | ||||
8515 | if (Overridden.insert(BaseMD).second) { | |||
8516 | MD->addOverriddenMethod(BaseMD); | |||
8517 | CheckOverridingFunctionReturnType(MD, BaseMD); | |||
8518 | CheckOverridingFunctionAttributes(MD, BaseMD); | |||
8519 | CheckOverridingFunctionExceptionSpec(MD, BaseMD); | |||
8520 | CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD); | |||
8521 | } | |||
8522 | ||||
8523 | // A method can only override one function from each base class. We | |||
8524 | // don't track indirectly overridden methods from bases of bases. | |||
8525 | return true; | |||
8526 | } | |||
8527 | ||||
8528 | return false; | |||
8529 | }; | |||
8530 | ||||
8531 | DC->lookupInBases(VisitBase, Paths); | |||
8532 | return !Overridden.empty(); | |||
8533 | } | |||
8534 | ||||
8535 | namespace { | |||
8536 | // Struct for holding all of the extra arguments needed by | |||
8537 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. | |||
8538 | struct ActOnFDArgs { | |||
8539 | Scope *S; | |||
8540 | Declarator &D; | |||
8541 | MultiTemplateParamsArg TemplateParamLists; | |||
8542 | bool AddToScope; | |||
8543 | }; | |||
8544 | } // end anonymous namespace | |||
8545 | ||||
8546 | namespace { | |||
8547 | ||||
8548 | // Callback to only accept typo corrections that have a non-zero edit distance. | |||
8549 | // Also only accept corrections that have the same parent decl. | |||
8550 | class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { | |||
8551 | public: | |||
8552 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, | |||
8553 | CXXRecordDecl *Parent) | |||
8554 | : Context(Context), OriginalFD(TypoFD), | |||
8555 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} | |||
8556 | ||||
8557 | bool ValidateCandidate(const TypoCorrection &candidate) override { | |||
8558 | if (candidate.getEditDistance() == 0) | |||
8559 | return false; | |||
8560 | ||||
8561 | SmallVector<unsigned, 1> MismatchedParams; | |||
8562 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), | |||
8563 | CDeclEnd = candidate.end(); | |||
8564 | CDecl != CDeclEnd; ++CDecl) { | |||
8565 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | |||
8566 | ||||
8567 | if (FD && !FD->hasBody() && | |||
8568 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { | |||
8569 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
8570 | CXXRecordDecl *Parent = MD->getParent(); | |||
8571 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) | |||
8572 | return true; | |||
8573 | } else if (!ExpectedParent) { | |||
8574 | return true; | |||
8575 | } | |||
8576 | } | |||
8577 | } | |||
8578 | ||||
8579 | return false; | |||
8580 | } | |||
8581 | ||||
8582 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | |||
8583 | return std::make_unique<DifferentNameValidatorCCC>(*this); | |||
8584 | } | |||
8585 | ||||
8586 | private: | |||
8587 | ASTContext &Context; | |||
8588 | FunctionDecl *OriginalFD; | |||
8589 | CXXRecordDecl *ExpectedParent; | |||
8590 | }; | |||
8591 | ||||
8592 | } // end anonymous namespace | |||
8593 | ||||
8594 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { | |||
8595 | TypoCorrectedFunctionDefinitions.insert(F); | |||
8596 | } | |||
8597 | ||||
8598 | /// Generate diagnostics for an invalid function redeclaration. | |||
8599 | /// | |||
8600 | /// This routine handles generating the diagnostic messages for an invalid | |||
8601 | /// function redeclaration, including finding possible similar declarations | |||
8602 | /// or performing typo correction if there are no previous declarations with | |||
8603 | /// the same name. | |||
8604 | /// | |||
8605 | /// Returns a NamedDecl iff typo correction was performed and substituting in | |||
8606 | /// the new declaration name does not cause new errors. | |||
8607 | static NamedDecl *DiagnoseInvalidRedeclaration( | |||
8608 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, | |||
8609 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { | |||
8610 | DeclarationName Name = NewFD->getDeclName(); | |||
8611 | DeclContext *NewDC = NewFD->getDeclContext(); | |||
8612 | SmallVector<unsigned, 1> MismatchedParams; | |||
8613 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; | |||
8614 | TypoCorrection Correction; | |||
8615 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); | |||
8616 | unsigned DiagMsg = | |||
8617 | IsLocalFriend ? diag::err_no_matching_local_friend : | |||
8618 | NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : | |||
8619 | diag::err_member_decl_does_not_match; | |||
8620 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), | |||
8621 | IsLocalFriend ? Sema::LookupLocalFriendName | |||
8622 | : Sema::LookupOrdinaryName, | |||
8623 | Sema::ForVisibleRedeclaration); | |||
8624 | ||||
8625 | NewFD->setInvalidDecl(); | |||
8626 | if (IsLocalFriend) | |||
8627 | SemaRef.LookupName(Prev, S); | |||
8628 | else | |||
8629 | SemaRef.LookupQualifiedName(Prev, NewDC); | |||
8630 | assert(!Prev.isAmbiguous() &&(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "clang/lib/Sema/SemaDecl.cpp", 8631, __extension__ __PRETTY_FUNCTION__ )) | |||
8631 | "Cannot have an ambiguity in previous-declaration lookup")(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "clang/lib/Sema/SemaDecl.cpp", 8631, __extension__ __PRETTY_FUNCTION__ )); | |||
8632 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | |||
8633 | DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, | |||
8634 | MD ? MD->getParent() : nullptr); | |||
8635 | if (!Prev.empty()) { | |||
8636 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); | |||
8637 | Func != FuncEnd; ++Func) { | |||
8638 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); | |||
8639 | if (FD && | |||
8640 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | |||
8641 | // Add 1 to the index so that 0 can mean the mismatch didn't | |||
8642 | // involve a parameter | |||
8643 | unsigned ParamNum = | |||
8644 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; | |||
8645 | NearMatches.push_back(std::make_pair(FD, ParamNum)); | |||
8646 | } | |||
8647 | } | |||
8648 | // If the qualified name lookup yielded nothing, try typo correction | |||
8649 | } else if ((Correction = SemaRef.CorrectTypo( | |||
8650 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, | |||
8651 | &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, | |||
8652 | IsLocalFriend ? nullptr : NewDC))) { | |||
8653 | // Set up everything for the call to ActOnFunctionDeclarator | |||
8654 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), | |||
8655 | ExtraArgs.D.getIdentifierLoc()); | |||
8656 | Previous.clear(); | |||
8657 | Previous.setLookupName(Correction.getCorrection()); | |||
8658 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), | |||
8659 | CDeclEnd = Correction.end(); | |||
8660 | CDecl != CDeclEnd; ++CDecl) { | |||
8661 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | |||
8662 | if (FD && !FD->hasBody() && | |||
8663 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | |||
8664 | Previous.addDecl(FD); | |||
8665 | } | |||
8666 | } | |||
8667 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); | |||
8668 | ||||
8669 | NamedDecl *Result; | |||
8670 | // Retry building the function declaration with the new previous | |||
8671 | // declarations, and with errors suppressed. | |||
8672 | { | |||
8673 | // Trap errors. | |||
8674 | Sema::SFINAETrap Trap(SemaRef); | |||
8675 | ||||
8676 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the | |||
8677 | // pieces need to verify the typo-corrected C++ declaration and hopefully | |||
8678 | // eliminate the need for the parameter pack ExtraArgs. | |||
8679 | Result = SemaRef.ActOnFunctionDeclarator( | |||
8680 | ExtraArgs.S, ExtraArgs.D, | |||
8681 | Correction.getCorrectionDecl()->getDeclContext(), | |||
8682 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, | |||
8683 | ExtraArgs.AddToScope); | |||
8684 | ||||
8685 | if (Trap.hasErrorOccurred()) | |||
8686 | Result = nullptr; | |||
8687 | } | |||
8688 | ||||
8689 | if (Result) { | |||
8690 | // Determine which correction we picked. | |||
8691 | Decl *Canonical = Result->getCanonicalDecl(); | |||
8692 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | |||
8693 | I != E; ++I) | |||
8694 | if ((*I)->getCanonicalDecl() == Canonical) | |||
8695 | Correction.setCorrectionDecl(*I); | |||
8696 | ||||
8697 | // Let Sema know about the correction. | |||
8698 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); | |||
8699 | SemaRef.diagnoseTypo( | |||
8700 | Correction, | |||
8701 | SemaRef.PDiag(IsLocalFriend | |||
8702 | ? diag::err_no_matching_local_friend_suggest | |||
8703 | : diag::err_member_decl_does_not_match_suggest) | |||
8704 | << Name << NewDC << IsDefinition); | |||
8705 | return Result; | |||
8706 | } | |||
8707 | ||||
8708 | // Pretend the typo correction never occurred | |||
8709 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), | |||
8710 | ExtraArgs.D.getIdentifierLoc()); | |||
8711 | ExtraArgs.D.setRedeclaration(wasRedeclaration); | |||
8712 | Previous.clear(); | |||
8713 | Previous.setLookupName(Name); | |||
8714 | } | |||
8715 | ||||
8716 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) | |||
8717 | << Name << NewDC << IsDefinition << NewFD->getLocation(); | |||
8718 | ||||
8719 | bool NewFDisConst = false; | |||
8720 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) | |||
8721 | NewFDisConst = NewMD->isConst(); | |||
8722 | ||||
8723 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator | |||
8724 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); | |||
8725 | NearMatch != NearMatchEnd; ++NearMatch) { | |||
8726 | FunctionDecl *FD = NearMatch->first; | |||
8727 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | |||
8728 | bool FDisConst = MD && MD->isConst(); | |||
8729 | bool IsMember = MD || !IsLocalFriend; | |||
8730 | ||||
8731 | // FIXME: These notes are poorly worded for the local friend case. | |||
8732 | if (unsigned Idx = NearMatch->second) { | |||
8733 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); | |||
8734 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); | |||
8735 | if (Loc.isInvalid()) Loc = FD->getLocation(); | |||
8736 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match | |||
8737 | : diag::note_local_decl_close_param_match) | |||
8738 | << Idx << FDParam->getType() | |||
8739 | << NewFD->getParamDecl(Idx - 1)->getType(); | |||
8740 | } else if (FDisConst != NewFDisConst) { | |||
8741 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) | |||
8742 | << NewFDisConst << FD->getSourceRange().getEnd() | |||
8743 | << (NewFDisConst | |||
8744 | ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo() | |||
8745 | .getConstQualifierLoc()) | |||
8746 | : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo() | |||
8747 | .getRParenLoc() | |||
8748 | .getLocWithOffset(1), | |||
8749 | " const")); | |||
8750 | } else | |||
8751 | SemaRef.Diag(FD->getLocation(), | |||
8752 | IsMember ? diag::note_member_def_close_match | |||
8753 | : diag::note_local_decl_close_match); | |||
8754 | } | |||
8755 | return nullptr; | |||
8756 | } | |||
8757 | ||||
8758 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { | |||
8759 | switch (D.getDeclSpec().getStorageClassSpec()) { | |||
8760 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "clang/lib/Sema/SemaDecl.cpp" , 8760); | |||
8761 | case DeclSpec::SCS_auto: | |||
8762 | case DeclSpec::SCS_register: | |||
8763 | case DeclSpec::SCS_mutable: | |||
8764 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
8765 | diag::err_typecheck_sclass_func); | |||
8766 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
8767 | D.setInvalidType(); | |||
8768 | break; | |||
8769 | case DeclSpec::SCS_unspecified: break; | |||
8770 | case DeclSpec::SCS_extern: | |||
8771 | if (D.getDeclSpec().isExternInLinkageSpec()) | |||
8772 | return SC_None; | |||
8773 | return SC_Extern; | |||
8774 | case DeclSpec::SCS_static: { | |||
8775 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { | |||
8776 | // C99 6.7.1p5: | |||
8777 | // The declaration of an identifier for a function that has | |||
8778 | // block scope shall have no explicit storage-class specifier | |||
8779 | // other than extern | |||
8780 | // See also (C++ [dcl.stc]p4). | |||
8781 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
8782 | diag::err_static_block_func); | |||
8783 | break; | |||
8784 | } else | |||
8785 | return SC_Static; | |||
8786 | } | |||
8787 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | |||
8788 | } | |||
8789 | ||||
8790 | // No explicit storage class has already been returned | |||
8791 | return SC_None; | |||
8792 | } | |||
8793 | ||||
8794 | static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, | |||
8795 | DeclContext *DC, QualType &R, | |||
8796 | TypeSourceInfo *TInfo, | |||
8797 | StorageClass SC, | |||
8798 | bool &IsVirtualOkay) { | |||
8799 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); | |||
8800 | DeclarationName Name = NameInfo.getName(); | |||
8801 | ||||
8802 | FunctionDecl *NewFD = nullptr; | |||
8803 | bool isInline = D.getDeclSpec().isInlineSpecified(); | |||
8804 | ||||
8805 | if (!SemaRef.getLangOpts().CPlusPlus) { | |||
8806 | // Determine whether the function was written with a prototype. This is | |||
8807 | // true when: | |||
8808 | // - there is a prototype in the declarator, or | |||
8809 | // - the type R of the function is some kind of typedef or other non- | |||
8810 | // attributed reference to a type name (which eventually refers to a | |||
8811 | // function type). Note, we can't always look at the adjusted type to | |||
8812 | // check this case because attributes may cause a non-function | |||
8813 | // declarator to still have a function type. e.g., | |||
8814 | // typedef void func(int a); | |||
8815 | // __attribute__((noreturn)) func other_func; // This has a prototype | |||
8816 | bool HasPrototype = | |||
8817 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || | |||
8818 | (D.getDeclSpec().isTypeRep() && | |||
8819 | D.getDeclSpec().getRepAsType().get()->isFunctionProtoType()) || | |||
8820 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); | |||
8821 | ||||
8822 | NewFD = FunctionDecl::Create( | |||
8823 | SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, | |||
8824 | SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype, | |||
8825 | ConstexprSpecKind::Unspecified, | |||
8826 | /*TrailingRequiresClause=*/nullptr); | |||
8827 | if (D.isInvalidType()) | |||
8828 | NewFD->setInvalidDecl(); | |||
8829 | ||||
8830 | return NewFD; | |||
8831 | } | |||
8832 | ||||
8833 | ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); | |||
8834 | ||||
8835 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); | |||
8836 | if (ConstexprKind == ConstexprSpecKind::Constinit) { | |||
8837 | SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), | |||
8838 | diag::err_constexpr_wrong_decl_kind) | |||
8839 | << static_cast<int>(ConstexprKind); | |||
8840 | ConstexprKind = ConstexprSpecKind::Unspecified; | |||
8841 | D.getMutableDeclSpec().ClearConstexprSpec(); | |||
8842 | } | |||
8843 | Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); | |||
8844 | ||||
8845 | // Check that the return type is not an abstract class type. | |||
8846 | // For record types, this is done by the AbstractClassUsageDiagnoser once | |||
8847 | // the class has been completely parsed. | |||
8848 | if (!DC->isRecord() && | |||
8849 | SemaRef.RequireNonAbstractType( | |||
8850 | D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), | |||
8851 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) | |||
8852 | D.setInvalidType(); | |||
8853 | ||||
8854 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { | |||
8855 | // This is a C++ constructor declaration. | |||
8856 | assert(DC->isRecord() &&(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context" ) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "clang/lib/Sema/SemaDecl.cpp", 8857, __extension__ __PRETTY_FUNCTION__ )) | |||
8857 | "Constructors can only be declared in a member context")(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context" ) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "clang/lib/Sema/SemaDecl.cpp", 8857, __extension__ __PRETTY_FUNCTION__ )); | |||
8858 | ||||
8859 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); | |||
8860 | return CXXConstructorDecl::Create( | |||
8861 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | |||
8862 | TInfo, ExplicitSpecifier, SemaRef.getCurFPFeatures().isFPConstrained(), | |||
8863 | isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, | |||
8864 | InheritedConstructor(), TrailingRequiresClause); | |||
8865 | ||||
8866 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
8867 | // This is a C++ destructor declaration. | |||
8868 | if (DC->isRecord()) { | |||
8869 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); | |||
8870 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); | |||
8871 | CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( | |||
8872 | SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, | |||
8873 | SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | |||
8874 | /*isImplicitlyDeclared=*/false, ConstexprKind, | |||
8875 | TrailingRequiresClause); | |||
8876 | ||||
8877 | // If the destructor needs an implicit exception specification, set it | |||
8878 | // now. FIXME: It'd be nice to be able to create the right type to start | |||
8879 | // with, but the type needs to reference the destructor declaration. | |||
8880 | if (SemaRef.getLangOpts().CPlusPlus11) | |||
8881 | SemaRef.AdjustDestructorExceptionSpec(NewDD); | |||
8882 | ||||
8883 | IsVirtualOkay = true; | |||
8884 | return NewDD; | |||
8885 | ||||
8886 | } else { | |||
8887 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); | |||
8888 | D.setInvalidType(); | |||
8889 | ||||
8890 | // Create a FunctionDecl to satisfy the function definition parsing | |||
8891 | // code path. | |||
8892 | return FunctionDecl::Create( | |||
8893 | SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R, | |||
8894 | TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | |||
8895 | /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause); | |||
8896 | } | |||
8897 | ||||
8898 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | |||
8899 | if (!DC->isRecord()) { | |||
8900 | SemaRef.Diag(D.getIdentifierLoc(), | |||
8901 | diag::err_conv_function_not_member); | |||
8902 | return nullptr; | |||
8903 | } | |||
8904 | ||||
8905 | SemaRef.CheckConversionDeclarator(D, R, SC); | |||
8906 | if (D.isInvalidType()) | |||
8907 | return nullptr; | |||
8908 | ||||
8909 | IsVirtualOkay = true; | |||
8910 | return CXXConversionDecl::Create( | |||
8911 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | |||
8912 | TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | |||
8913 | ExplicitSpecifier, ConstexprKind, SourceLocation(), | |||
8914 | TrailingRequiresClause); | |||
8915 | ||||
8916 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { | |||
8917 | if (TrailingRequiresClause) | |||
8918 | SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), | |||
8919 | diag::err_trailing_requires_clause_on_deduction_guide) | |||
8920 | << TrailingRequiresClause->getSourceRange(); | |||
8921 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); | |||
8922 | ||||
8923 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | |||
8924 | ExplicitSpecifier, NameInfo, R, TInfo, | |||
8925 | D.getEndLoc()); | |||
8926 | } else if (DC->isRecord()) { | |||
8927 | // If the name of the function is the same as the name of the record, | |||
8928 | // then this must be an invalid constructor that has a return type. | |||
8929 | // (The parser checks for a return type and makes the declarator a | |||
8930 | // constructor if it has no return type). | |||
8931 | if (Name.getAsIdentifierInfo() && | |||
8932 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ | |||
8933 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) | |||
8934 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | |||
8935 | << SourceRange(D.getIdentifierLoc()); | |||
8936 | return nullptr; | |||
8937 | } | |||
8938 | ||||
8939 | // This is a C++ method declaration. | |||
8940 | CXXMethodDecl *Ret = CXXMethodDecl::Create( | |||
8941 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | |||
8942 | TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | |||
8943 | ConstexprKind, SourceLocation(), TrailingRequiresClause); | |||
8944 | IsVirtualOkay = !Ret->isStatic(); | |||
8945 | return Ret; | |||
8946 | } else { | |||
8947 | bool isFriend = | |||
8948 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); | |||
8949 | if (!isFriend && SemaRef.CurContext->isRecord()) | |||
8950 | return nullptr; | |||
8951 | ||||
8952 | // Determine whether the function was written with a | |||
8953 | // prototype. This true when: | |||
8954 | // - we're in C++ (where every function has a prototype), | |||
8955 | return FunctionDecl::Create( | |||
8956 | SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC, | |||
8957 | SemaRef.getCurFPFeatures().isFPConstrained(), isInline, | |||
8958 | true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause); | |||
8959 | } | |||
8960 | } | |||
8961 | ||||
8962 | enum OpenCLParamType { | |||
8963 | ValidKernelParam, | |||
8964 | PtrPtrKernelParam, | |||
8965 | PtrKernelParam, | |||
8966 | InvalidAddrSpacePtrKernelParam, | |||
8967 | InvalidKernelParam, | |||
8968 | RecordKernelParam | |||
8969 | }; | |||
8970 | ||||
8971 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { | |||
8972 | // Size dependent types are just typedefs to normal integer types | |||
8973 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to | |||
8974 | // integers other than by their names. | |||
8975 | StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; | |||
8976 | ||||
8977 | // Remove typedefs one by one until we reach a typedef | |||
8978 | // for a size dependent type. | |||
8979 | QualType DesugaredTy = Ty; | |||
8980 | do { | |||
8981 | ArrayRef<StringRef> Names(SizeTypeNames); | |||
8982 | auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); | |||
8983 | if (Names.end() != Match) | |||
8984 | return true; | |||
8985 | ||||
8986 | Ty = DesugaredTy; | |||
8987 | DesugaredTy = Ty.getSingleStepDesugaredType(C); | |||
8988 | } while (DesugaredTy != Ty); | |||
8989 | ||||
8990 | return false; | |||
8991 | } | |||
8992 | ||||
8993 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { | |||
8994 | if (PT->isDependentType()) | |||
8995 | return InvalidKernelParam; | |||
8996 | ||||
8997 | if (PT->isPointerType() || PT->isReferenceType()) { | |||
8998 | QualType PointeeType = PT->getPointeeType(); | |||
8999 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || | |||
9000 | PointeeType.getAddressSpace() == LangAS::opencl_private || | |||
9001 | PointeeType.getAddressSpace() == LangAS::Default) | |||
9002 | return InvalidAddrSpacePtrKernelParam; | |||
9003 | ||||
9004 | if (PointeeType->isPointerType()) { | |||
9005 | // This is a pointer to pointer parameter. | |||
9006 | // Recursively check inner type. | |||
9007 | OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType); | |||
9008 | if (ParamKind == InvalidAddrSpacePtrKernelParam || | |||
9009 | ParamKind == InvalidKernelParam) | |||
9010 | return ParamKind; | |||
9011 | ||||
9012 | return PtrPtrKernelParam; | |||
9013 | } | |||
9014 | ||||
9015 | // C++ for OpenCL v1.0 s2.4: | |||
9016 | // Moreover the types used in parameters of the kernel functions must be: | |||
9017 | // Standard layout types for pointer parameters. The same applies to | |||
9018 | // reference if an implementation supports them in kernel parameters. | |||
9019 | if (S.getLangOpts().OpenCLCPlusPlus && | |||
9020 | !S.getOpenCLOptions().isAvailableOption( | |||
9021 | "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && | |||
9022 | !PointeeType->isAtomicType() && !PointeeType->isVoidType() && | |||
9023 | !PointeeType->isStandardLayoutType()) | |||
9024 | return InvalidKernelParam; | |||
9025 | ||||
9026 | return PtrKernelParam; | |||
9027 | } | |||
9028 | ||||
9029 | // OpenCL v1.2 s6.9.k: | |||
9030 | // Arguments to kernel functions in a program cannot be declared with the | |||
9031 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | |||
9032 | // uintptr_t or a struct and/or union that contain fields declared to be one | |||
9033 | // of these built-in scalar types. | |||
9034 | if (isOpenCLSizeDependentType(S.getASTContext(), PT)) | |||
9035 | return InvalidKernelParam; | |||
9036 | ||||
9037 | if (PT->isImageType()) | |||
9038 | return PtrKernelParam; | |||
9039 | ||||
9040 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) | |||
9041 | return InvalidKernelParam; | |||
9042 | ||||
9043 | // OpenCL extension spec v1.2 s9.5: | |||
9044 | // This extension adds support for half scalar and vector types as built-in | |||
9045 | // types that can be used for arithmetic operations, conversions etc. | |||
9046 | if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) && | |||
9047 | PT->isHalfType()) | |||
9048 | return InvalidKernelParam; | |||
9049 | ||||
9050 | // Look into an array argument to check if it has a forbidden type. | |||
9051 | if (PT->isArrayType()) { | |||
9052 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); | |||
9053 | // Call ourself to check an underlying type of an array. Since the | |||
9054 | // getPointeeOrArrayElementType returns an innermost type which is not an | |||
9055 | // array, this recursive call only happens once. | |||
9056 | return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); | |||
9057 | } | |||
9058 | ||||
9059 | // C++ for OpenCL v1.0 s2.4: | |||
9060 | // Moreover the types used in parameters of the kernel functions must be: | |||
9061 | // Trivial and standard-layout types C++17 [basic.types] (plain old data | |||
9062 | // types) for parameters passed by value; | |||
9063 | if (S.getLangOpts().OpenCLCPlusPlus && | |||
9064 | !S.getOpenCLOptions().isAvailableOption( | |||
9065 | "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) && | |||
9066 | !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context)) | |||
9067 | return InvalidKernelParam; | |||
9068 | ||||
9069 | if (PT->isRecordType()) | |||
9070 | return RecordKernelParam; | |||
9071 | ||||
9072 | return ValidKernelParam; | |||
9073 | } | |||
9074 | ||||
9075 | static void checkIsValidOpenCLKernelParameter( | |||
9076 | Sema &S, | |||
9077 | Declarator &D, | |||
9078 | ParmVarDecl *Param, | |||
9079 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { | |||
9080 | QualType PT = Param->getType(); | |||
9081 | ||||
9082 | // Cache the valid types we encounter to avoid rechecking structs that are | |||
9083 | // used again | |||
9084 | if (ValidTypes.count(PT.getTypePtr())) | |||
9085 | return; | |||
9086 | ||||
9087 | switch (getOpenCLKernelParameterType(S, PT)) { | |||
9088 | case PtrPtrKernelParam: | |||
9089 | // OpenCL v3.0 s6.11.a: | |||
9090 | // A kernel function argument cannot be declared as a pointer to a pointer | |||
9091 | // type. [...] This restriction only applies to OpenCL C 1.2 or below. | |||
9092 | if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) { | |||
9093 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); | |||
9094 | D.setInvalidType(); | |||
9095 | return; | |||
9096 | } | |||
9097 | ||||
9098 | ValidTypes.insert(PT.getTypePtr()); | |||
9099 | return; | |||
9100 | ||||
9101 | case InvalidAddrSpacePtrKernelParam: | |||
9102 | // OpenCL v1.0 s6.5: | |||
9103 | // __kernel function arguments declared to be a pointer of a type can point | |||
9104 | // to one of the following address spaces only : __global, __local or | |||
9105 | // __constant. | |||
9106 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); | |||
9107 | D.setInvalidType(); | |||
9108 | return; | |||
9109 | ||||
9110 | // OpenCL v1.2 s6.9.k: | |||
9111 | // Arguments to kernel functions in a program cannot be declared with the | |||
9112 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | |||
9113 | // uintptr_t or a struct and/or union that contain fields declared to be | |||
9114 | // one of these built-in scalar types. | |||
9115 | ||||
9116 | case InvalidKernelParam: | |||
9117 | // OpenCL v1.2 s6.8 n: | |||
9118 | // A kernel function argument cannot be declared | |||
9119 | // of event_t type. | |||
9120 | // Do not diagnose half type since it is diagnosed as invalid argument | |||
9121 | // type for any function elsewhere. | |||
9122 | if (!PT->isHalfType()) { | |||
9123 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | |||
9124 | ||||
9125 | // Explain what typedefs are involved. | |||
9126 | const TypedefType *Typedef = nullptr; | |||
9127 | while ((Typedef = PT->getAs<TypedefType>())) { | |||
9128 | SourceLocation Loc = Typedef->getDecl()->getLocation(); | |||
9129 | // SourceLocation may be invalid for a built-in type. | |||
9130 | if (Loc.isValid()) | |||
9131 | S.Diag(Loc, diag::note_entity_declared_at) << PT; | |||
9132 | PT = Typedef->desugar(); | |||
9133 | } | |||
9134 | } | |||
9135 | ||||
9136 | D.setInvalidType(); | |||
9137 | return; | |||
9138 | ||||
9139 | case PtrKernelParam: | |||
9140 | case ValidKernelParam: | |||
9141 | ValidTypes.insert(PT.getTypePtr()); | |||
9142 | return; | |||
9143 | ||||
9144 | case RecordKernelParam: | |||
9145 | break; | |||
9146 | } | |||
9147 | ||||
9148 | // Track nested structs we will inspect | |||
9149 | SmallVector<const Decl *, 4> VisitStack; | |||
9150 | ||||
9151 | // Track where we are in the nested structs. Items will migrate from | |||
9152 | // VisitStack to HistoryStack as we do the DFS for bad field. | |||
9153 | SmallVector<const FieldDecl *, 4> HistoryStack; | |||
9154 | HistoryStack.push_back(nullptr); | |||
9155 | ||||
9156 | // At this point we already handled everything except of a RecordType or | |||
9157 | // an ArrayType of a RecordType. | |||
9158 | assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(static_cast <bool> ((PT->isArrayType() || PT->isRecordType ()) && "Unexpected type.") ? void (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\"" , "clang/lib/Sema/SemaDecl.cpp", 9158, __extension__ __PRETTY_FUNCTION__ )); | |||
9159 | const RecordType *RecTy = | |||
9160 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); | |||
9161 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); | |||
9162 | ||||
9163 | VisitStack.push_back(RecTy->getDecl()); | |||
9164 | assert(VisitStack.back() && "First decl null?")(static_cast <bool> (VisitStack.back() && "First decl null?" ) ? void (0) : __assert_fail ("VisitStack.back() && \"First decl null?\"" , "clang/lib/Sema/SemaDecl.cpp", 9164, __extension__ __PRETTY_FUNCTION__ )); | |||
9165 | ||||
9166 | do { | |||
9167 | const Decl *Next = VisitStack.pop_back_val(); | |||
9168 | if (!Next) { | |||
9169 | assert(!HistoryStack.empty())(static_cast <bool> (!HistoryStack.empty()) ? void (0) : __assert_fail ("!HistoryStack.empty()", "clang/lib/Sema/SemaDecl.cpp" , 9169, __extension__ __PRETTY_FUNCTION__)); | |||
9170 | // Found a marker, we have gone up a level | |||
9171 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) | |||
9172 | ValidTypes.insert(Hist->getType().getTypePtr()); | |||
9173 | ||||
9174 | continue; | |||
9175 | } | |||
9176 | ||||
9177 | // Adds everything except the original parameter declaration (which is not a | |||
9178 | // field itself) to the history stack. | |||
9179 | const RecordDecl *RD; | |||
9180 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { | |||
9181 | HistoryStack.push_back(Field); | |||
9182 | ||||
9183 | QualType FieldTy = Field->getType(); | |||
9184 | // Other field types (known to be valid or invalid) are handled while we | |||
9185 | // walk around RecordDecl::fields(). | |||
9186 | assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(static_cast <bool> ((FieldTy->isArrayType() || FieldTy ->isRecordType()) && "Unexpected type.") ? void (0 ) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "clang/lib/Sema/SemaDecl.cpp", 9187, __extension__ __PRETTY_FUNCTION__ )) | |||
9187 | "Unexpected type.")(static_cast <bool> ((FieldTy->isArrayType() || FieldTy ->isRecordType()) && "Unexpected type.") ? void (0 ) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "clang/lib/Sema/SemaDecl.cpp", 9187, __extension__ __PRETTY_FUNCTION__ )); | |||
9188 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); | |||
9189 | ||||
9190 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); | |||
9191 | } else { | |||
9192 | RD = cast<RecordDecl>(Next); | |||
9193 | } | |||
9194 | ||||
9195 | // Add a null marker so we know when we've gone back up a level | |||
9196 | VisitStack.push_back(nullptr); | |||
9197 | ||||
9198 | for (const auto *FD : RD->fields()) { | |||
9199 | QualType QT = FD->getType(); | |||
9200 | ||||
9201 | if (ValidTypes.count(QT.getTypePtr())) | |||
9202 | continue; | |||
9203 | ||||
9204 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); | |||
9205 | if (ParamType == ValidKernelParam) | |||
9206 | continue; | |||
9207 | ||||
9208 | if (ParamType == RecordKernelParam) { | |||
9209 | VisitStack.push_back(FD); | |||
9210 | continue; | |||
9211 | } | |||
9212 | ||||
9213 | // OpenCL v1.2 s6.9.p: | |||
9214 | // Arguments to kernel functions that are declared to be a struct or union | |||
9215 | // do not allow OpenCL objects to be passed as elements of the struct or | |||
9216 | // union. | |||
9217 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || | |||
9218 | ParamType == InvalidAddrSpacePtrKernelParam) { | |||
9219 | S.Diag(Param->getLocation(), | |||
9220 | diag::err_record_with_pointers_kernel_param) | |||
9221 | << PT->isUnionType() | |||
9222 | << PT; | |||
9223 | } else { | |||
9224 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | |||
9225 | } | |||
9226 | ||||
9227 | S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) | |||
9228 | << OrigRecDecl->getDeclName(); | |||
9229 | ||||
9230 | // We have an error, now let's go back up through history and show where | |||
9231 | // the offending field came from | |||
9232 | for (ArrayRef<const FieldDecl *>::const_iterator | |||
9233 | I = HistoryStack.begin() + 1, | |||
9234 | E = HistoryStack.end(); | |||
9235 | I != E; ++I) { | |||
9236 | const FieldDecl *OuterField = *I; | |||
9237 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) | |||
9238 | << OuterField->getType(); | |||
9239 | } | |||
9240 | ||||
9241 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) | |||
9242 | << QT->isPointerType() | |||
9243 | << QT; | |||
9244 | D.setInvalidType(); | |||
9245 | return; | |||
9246 | } | |||
9247 | } while (!VisitStack.empty()); | |||
9248 | } | |||
9249 | ||||
9250 | /// Find the DeclContext in which a tag is implicitly declared if we see an | |||
9251 | /// elaborated type specifier in the specified context, and lookup finds | |||
9252 | /// nothing. | |||
9253 | static DeclContext *getTagInjectionContext(DeclContext *DC) { | |||
9254 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) | |||
9255 | DC = DC->getParent(); | |||
9256 | return DC; | |||
9257 | } | |||
9258 | ||||
9259 | /// Find the Scope in which a tag is implicitly declared if we see an | |||
9260 | /// elaborated type specifier in the specified context, and lookup finds | |||
9261 | /// nothing. | |||
9262 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { | |||
9263 | while (S->isClassScope() || | |||
9264 | (LangOpts.CPlusPlus && | |||
9265 | S->isFunctionPrototypeScope()) || | |||
9266 | ((S->getFlags() & Scope::DeclScope) == 0) || | |||
9267 | (S->getEntity() && S->getEntity()->isTransparentContext())) | |||
9268 | S = S->getParent(); | |||
9269 | return S; | |||
9270 | } | |||
9271 | ||||
9272 | /// Determine whether a declaration matches a known function in namespace std. | |||
9273 | static bool isStdBuiltin(ASTContext &Ctx, FunctionDecl *FD, | |||
9274 | unsigned BuiltinID) { | |||
9275 | switch (BuiltinID) { | |||
9276 | case Builtin::BI__GetExceptionInfo: | |||
9277 | // No type checking whatsoever. | |||
9278 | return Ctx.getTargetInfo().getCXXABI().isMicrosoft(); | |||
9279 | ||||
9280 | case Builtin::BIaddressof: | |||
9281 | case Builtin::BI__addressof: | |||
9282 | case Builtin::BIforward: | |||
9283 | case Builtin::BImove: | |||
9284 | case Builtin::BImove_if_noexcept: | |||
9285 | case Builtin::BIas_const: { | |||
9286 | // Ensure that we don't treat the algorithm | |||
9287 | // OutputIt std::move(InputIt, InputIt, OutputIt) | |||
9288 | // as the builtin std::move. | |||
9289 | const auto *FPT = FD->getType()->castAs<FunctionProtoType>(); | |||
9290 | return FPT->getNumParams() == 1 && !FPT->isVariadic(); | |||
9291 | } | |||
9292 | ||||
9293 | default: | |||
9294 | return false; | |||
9295 | } | |||
9296 | } | |||
9297 | ||||
9298 | NamedDecl* | |||
9299 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, | |||
9300 | TypeSourceInfo *TInfo, LookupResult &Previous, | |||
9301 | MultiTemplateParamsArg TemplateParamListsRef, | |||
9302 | bool &AddToScope) { | |||
9303 | QualType R = TInfo->getType(); | |||
9304 | ||||
9305 | assert(R->isFunctionType())(static_cast <bool> (R->isFunctionType()) ? void (0) : __assert_fail ("R->isFunctionType()", "clang/lib/Sema/SemaDecl.cpp" , 9305, __extension__ __PRETTY_FUNCTION__)); | |||
9306 | if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) | |||
9307 | Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); | |||
9308 | ||||
9309 | SmallVector<TemplateParameterList *, 4> TemplateParamLists; | |||
9310 | llvm::append_range(TemplateParamLists, TemplateParamListsRef); | |||
9311 | if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { | |||
9312 | if (!TemplateParamLists.empty() && | |||
9313 | Invented->getDepth() == TemplateParamLists.back()->getDepth()) | |||
9314 | TemplateParamLists.back() = Invented; | |||
9315 | else | |||
9316 | TemplateParamLists.push_back(Invented); | |||
9317 | } | |||
9318 | ||||
9319 | // TODO: consider using NameInfo for diagnostic. | |||
9320 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | |||
9321 | DeclarationName Name = NameInfo.getName(); | |||
9322 | StorageClass SC = getFunctionStorageClass(*this, D); | |||
9323 | ||||
9324 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | |||
9325 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
9326 | diag::err_invalid_thread) | |||
9327 | << DeclSpec::getSpecifierName(TSCS); | |||
9328 | ||||
9329 | if (D.isFirstDeclarationOfMember()) | |||
9330 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), | |||
9331 | D.getIdentifierLoc()); | |||
9332 | ||||
9333 | bool isFriend = false; | |||
9334 | FunctionTemplateDecl *FunctionTemplate = nullptr; | |||
9335 | bool isMemberSpecialization = false; | |||
9336 | bool isFunctionTemplateSpecialization = false; | |||
9337 | ||||
9338 | bool isDependentClassScopeExplicitSpecialization = false; | |||
9339 | bool HasExplicitTemplateArgs = false; | |||
9340 | TemplateArgumentListInfo TemplateArgs; | |||
9341 | ||||
9342 | bool isVirtualOkay = false; | |||
9343 | ||||
9344 | DeclContext *OriginalDC = DC; | |||
9345 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); | |||
9346 | ||||
9347 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, | |||
9348 | isVirtualOkay); | |||
9349 | if (!NewFD) return nullptr; | |||
9350 | ||||
9351 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) | |||
9352 | NewFD->setTopLevelDeclInObjCContainer(); | |||
9353 | ||||
9354 | // Set the lexical context. If this is a function-scope declaration, or has a | |||
9355 | // C++ scope specifier, or is the object of a friend declaration, the lexical | |||
9356 | // context will be different from the semantic context. | |||
9357 | NewFD->setLexicalDeclContext(CurContext); | |||
9358 | ||||
9359 | if (IsLocalExternDecl) | |||
9360 | NewFD->setLocalExternDecl(); | |||
9361 | ||||
9362 | if (getLangOpts().CPlusPlus) { | |||
9363 | bool isInline = D.getDeclSpec().isInlineSpecified(); | |||
9364 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | |||
9365 | bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); | |||
9366 | isFriend = D.getDeclSpec().isFriendSpecified(); | |||
9367 | if (isFriend && !isInline && D.isFunctionDefinition()) { | |||
9368 | // C++ [class.friend]p5 | |||
9369 | // A function can be defined in a friend declaration of a | |||
9370 | // class . . . . Such a function is implicitly inline. | |||
9371 | NewFD->setImplicitlyInline(); | |||
9372 | } | |||
9373 | ||||
9374 | // If this is a method defined in an __interface, and is not a constructor | |||
9375 | // or an overloaded operator, then set the pure flag (isVirtual will already | |||
9376 | // return true). | |||
9377 | if (const CXXRecordDecl *Parent = | |||
9378 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { | |||
9379 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) | |||
9380 | NewFD->setPure(true); | |||
9381 | ||||
9382 | // C++ [class.union]p2 | |||
9383 | // A union can have member functions, but not virtual functions. | |||
9384 | if (isVirtual && Parent->isUnion()) { | |||
9385 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); | |||
9386 | NewFD->setInvalidDecl(); | |||
9387 | } | |||
9388 | if ((Parent->isClass() || Parent->isStruct()) && | |||
9389 | Parent->hasAttr<SYCLSpecialClassAttr>() && | |||
9390 | NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() && | |||
9391 | NewFD->getName() == "__init" && D.isFunctionDefinition()) { | |||
9392 | if (auto *Def = Parent->getDefinition()) | |||
9393 | Def->setInitMethod(true); | |||
9394 | } | |||
9395 | } | |||
9396 | ||||
9397 | SetNestedNameSpecifier(*this, NewFD, D); | |||
9398 | isMemberSpecialization = false; | |||
9399 | isFunctionTemplateSpecialization = false; | |||
9400 | if (D.isInvalidType()) | |||
9401 | NewFD->setInvalidDecl(); | |||
9402 | ||||
9403 | // Match up the template parameter lists with the scope specifier, then | |||
9404 | // determine whether we have a template or a template specialization. | |||
9405 | bool Invalid = false; | |||
9406 | TemplateParameterList *TemplateParams = | |||
9407 | MatchTemplateParametersToScopeSpecifier( | |||
9408 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | |||
9409 | D.getCXXScopeSpec(), | |||
9410 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | |||
9411 | ? D.getName().TemplateId | |||
9412 | : nullptr, | |||
9413 | TemplateParamLists, isFriend, isMemberSpecialization, | |||
9414 | Invalid); | |||
9415 | if (TemplateParams) { | |||
9416 | // Check that we can declare a template here. | |||
9417 | if (CheckTemplateDeclScope(S, TemplateParams)) | |||
9418 | NewFD->setInvalidDecl(); | |||
9419 | ||||
9420 | if (TemplateParams->size() > 0) { | |||
9421 | // This is a function template | |||
9422 | ||||
9423 | // A destructor cannot be a template. | |||
9424 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | |||
9425 | Diag(NewFD->getLocation(), diag::err_destructor_template); | |||
9426 | NewFD->setInvalidDecl(); | |||
9427 | } | |||
9428 | ||||
9429 | // If we're adding a template to a dependent context, we may need to | |||
9430 | // rebuilding some of the types used within the template parameter list, | |||
9431 | // now that we know what the current instantiation is. | |||
9432 | if (DC->isDependentContext()) { | |||
9433 | ContextRAII SavedContext(*this, DC); | |||
9434 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) | |||
9435 | Invalid = true; | |||
9436 | } | |||
9437 | ||||
9438 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, | |||
9439 | NewFD->getLocation(), | |||
9440 | Name, TemplateParams, | |||
9441 | NewFD); | |||
9442 | FunctionTemplate->setLexicalDeclContext(CurContext); | |||
9443 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); | |||
9444 | ||||
9445 | // For source fidelity, store the other template param lists. | |||
9446 | if (TemplateParamLists.size() > 1) { | |||
9447 | NewFD->setTemplateParameterListsInfo(Context, | |||
9448 | ArrayRef<TemplateParameterList *>(TemplateParamLists) | |||
9449 | .drop_back(1)); | |||
9450 | } | |||
9451 | } else { | |||
9452 | // This is a function template specialization. | |||
9453 | isFunctionTemplateSpecialization = true; | |||
9454 | // For source fidelity, store all the template param lists. | |||
9455 | if (TemplateParamLists.size() > 0) | |||
9456 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | |||
9457 | ||||
9458 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". | |||
9459 | if (isFriend) { | |||
9460 | // We want to remove the "template<>", found here. | |||
9461 | SourceRange RemoveRange = TemplateParams->getSourceRange(); | |||
9462 | ||||
9463 | // If we remove the template<> and the name is not a | |||
9464 | // template-id, we're actually silently creating a problem: | |||
9465 | // the friend declaration will refer to an untemplated decl, | |||
9466 | // and clearly the user wants a template specialization. So | |||
9467 | // we need to insert '<>' after the name. | |||
9468 | SourceLocation InsertLoc; | |||
9469 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | |||
9470 | InsertLoc = D.getName().getSourceRange().getEnd(); | |||
9471 | InsertLoc = getLocForEndOfToken(InsertLoc); | |||
9472 | } | |||
9473 | ||||
9474 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) | |||
9475 | << Name << RemoveRange | |||
9476 | << FixItHint::CreateRemoval(RemoveRange) | |||
9477 | << FixItHint::CreateInsertion(InsertLoc, "<>"); | |||
9478 | Invalid = true; | |||
9479 | } | |||
9480 | } | |||
9481 | } else { | |||
9482 | // Check that we can declare a template here. | |||
9483 | if (!TemplateParamLists.empty() && isMemberSpecialization && | |||
9484 | CheckTemplateDeclScope(S, TemplateParamLists.back())) | |||
9485 | NewFD->setInvalidDecl(); | |||
9486 | ||||
9487 | // All template param lists were matched against the scope specifier: | |||
9488 | // this is NOT (an explicit specialization of) a template. | |||
9489 | if (TemplateParamLists.size() > 0) | |||
9490 | // For source fidelity, store all the template param lists. | |||
9491 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | |||
9492 | } | |||
9493 | ||||
9494 | if (Invalid) { | |||
9495 | NewFD->setInvalidDecl(); | |||
9496 | if (FunctionTemplate) | |||
9497 | FunctionTemplate->setInvalidDecl(); | |||
9498 | } | |||
9499 | ||||
9500 | // C++ [dcl.fct.spec]p5: | |||
9501 | // The virtual specifier shall only be used in declarations of | |||
9502 | // nonstatic class member functions that appear within a | |||
9503 | // member-specification of a class declaration; see 10.3. | |||
9504 | // | |||
9505 | if (isVirtual && !NewFD->isInvalidDecl()) { | |||
9506 | if (!isVirtualOkay) { | |||
9507 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
9508 | diag::err_virtual_non_function); | |||
9509 | } else if (!CurContext->isRecord()) { | |||
9510 | // 'virtual' was specified outside of the class. | |||
9511 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
9512 | diag::err_virtual_out_of_class) | |||
9513 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | |||
9514 | } else if (NewFD->getDescribedFunctionTemplate()) { | |||
9515 | // C++ [temp.mem]p3: | |||
9516 | // A member function template shall not be virtual. | |||
9517 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | |||
9518 | diag::err_virtual_member_function_template) | |||
9519 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | |||
9520 | } else { | |||
9521 | // Okay: Add virtual to the method. | |||
9522 | NewFD->setVirtualAsWritten(true); | |||
9523 | } | |||
9524 | ||||
9525 | if (getLangOpts().CPlusPlus14 && | |||
9526 | NewFD->getReturnType()->isUndeducedType()) | |||
9527 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); | |||
9528 | } | |||
9529 | ||||
9530 | if (getLangOpts().CPlusPlus14 && | |||
9531 | (NewFD->isDependentContext() || | |||
9532 | (isFriend && CurContext->isDependentContext())) && | |||
9533 | NewFD->getReturnType()->isUndeducedType()) { | |||
9534 | // If the function template is referenced directly (for instance, as a | |||
9535 | // member of the current instantiation), pretend it has a dependent type. | |||
9536 | // This is not really justified by the standard, but is the only sane | |||
9537 | // thing to do. | |||
9538 | // FIXME: For a friend function, we have not marked the function as being | |||
9539 | // a friend yet, so 'isDependentContext' on the FD doesn't work. | |||
9540 | const FunctionProtoType *FPT = | |||
9541 | NewFD->getType()->castAs<FunctionProtoType>(); | |||
9542 | QualType Result = SubstAutoTypeDependent(FPT->getReturnType()); | |||
9543 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), | |||
9544 | FPT->getExtProtoInfo())); | |||
9545 | } | |||
9546 | ||||
9547 | // C++ [dcl.fct.spec]p3: | |||
9548 | // The inline specifier shall not appear on a block scope function | |||
9549 | // declaration. | |||
9550 | if (isInline && !NewFD->isInvalidDecl()) { | |||
9551 | if (CurContext->isFunctionOrMethod()) { | |||
9552 | // 'inline' is not allowed on block scope function declaration. | |||
9553 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
9554 | diag::err_inline_declaration_block_scope) << Name | |||
9555 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | |||
9556 | } | |||
9557 | } | |||
9558 | ||||
9559 | // C++ [dcl.fct.spec]p6: | |||
9560 | // The explicit specifier shall be used only in the declaration of a | |||
9561 | // constructor or conversion function within its class definition; | |||
9562 | // see 12.3.1 and 12.3.2. | |||
9563 | if (hasExplicit && !NewFD->isInvalidDecl() && | |||
9564 | !isa<CXXDeductionGuideDecl>(NewFD)) { | |||
9565 | if (!CurContext->isRecord()) { | |||
9566 | // 'explicit' was specified outside of the class. | |||
9567 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | |||
9568 | diag::err_explicit_out_of_class) | |||
9569 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | |||
9570 | } else if (!isa<CXXConstructorDecl>(NewFD) && | |||
9571 | !isa<CXXConversionDecl>(NewFD)) { | |||
9572 | // 'explicit' was specified on a function that wasn't a constructor | |||
9573 | // or conversion function. | |||
9574 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | |||
9575 | diag::err_explicit_non_ctor_or_conv_function) | |||
9576 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | |||
9577 | } | |||
9578 | } | |||
9579 | ||||
9580 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); | |||
9581 | if (ConstexprKind != ConstexprSpecKind::Unspecified) { | |||
9582 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors | |||
9583 | // are implicitly inline. | |||
9584 | NewFD->setImplicitlyInline(); | |||
9585 | ||||
9586 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to | |||
9587 | // be either constructors or to return a literal type. Therefore, | |||
9588 | // destructors cannot be declared constexpr. | |||
9589 | if (isa<CXXDestructorDecl>(NewFD) && | |||
9590 | (!getLangOpts().CPlusPlus20 || | |||
9591 | ConstexprKind == ConstexprSpecKind::Consteval)) { | |||
9592 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) | |||
9593 | << static_cast<int>(ConstexprKind); | |||
9594 | NewFD->setConstexprKind(getLangOpts().CPlusPlus20 | |||
9595 | ? ConstexprSpecKind::Unspecified | |||
9596 | : ConstexprSpecKind::Constexpr); | |||
9597 | } | |||
9598 | // C++20 [dcl.constexpr]p2: An allocation function, or a | |||
9599 | // deallocation function shall not be declared with the consteval | |||
9600 | // specifier. | |||
9601 | if (ConstexprKind == ConstexprSpecKind::Consteval && | |||
9602 | (NewFD->getOverloadedOperator() == OO_New || | |||
9603 | NewFD->getOverloadedOperator() == OO_Array_New || | |||
9604 | NewFD->getOverloadedOperator() == OO_Delete || | |||
9605 | NewFD->getOverloadedOperator() == OO_Array_Delete)) { | |||
9606 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | |||
9607 | diag::err_invalid_consteval_decl_kind) | |||
9608 | << NewFD; | |||
9609 | NewFD->setConstexprKind(ConstexprSpecKind::Constexpr); | |||
9610 | } | |||
9611 | } | |||
9612 | ||||
9613 | // If __module_private__ was specified, mark the function accordingly. | |||
9614 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
9615 | if (isFunctionTemplateSpecialization) { | |||
9616 | SourceLocation ModulePrivateLoc | |||
9617 | = D.getDeclSpec().getModulePrivateSpecLoc(); | |||
9618 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) | |||
9619 | << 0 | |||
9620 | << FixItHint::CreateRemoval(ModulePrivateLoc); | |||
9621 | } else { | |||
9622 | NewFD->setModulePrivate(); | |||
9623 | if (FunctionTemplate) | |||
9624 | FunctionTemplate->setModulePrivate(); | |||
9625 | } | |||
9626 | } | |||
9627 | ||||
9628 | if (isFriend) { | |||
9629 | if (FunctionTemplate) { | |||
9630 | FunctionTemplate->setObjectOfFriendDecl(); | |||
9631 | FunctionTemplate->setAccess(AS_public); | |||
9632 | } | |||
9633 | NewFD->setObjectOfFriendDecl(); | |||
9634 | NewFD->setAccess(AS_public); | |||
9635 | } | |||
9636 | ||||
9637 | // If a function is defined as defaulted or deleted, mark it as such now. | |||
9638 | // We'll do the relevant checks on defaulted / deleted functions later. | |||
9639 | switch (D.getFunctionDefinitionKind()) { | |||
9640 | case FunctionDefinitionKind::Declaration: | |||
9641 | case FunctionDefinitionKind::Definition: | |||
9642 | break; | |||
9643 | ||||
9644 | case FunctionDefinitionKind::Defaulted: | |||
9645 | NewFD->setDefaulted(); | |||
9646 | break; | |||
9647 | ||||
9648 | case FunctionDefinitionKind::Deleted: | |||
9649 | NewFD->setDeletedAsWritten(); | |||
9650 | break; | |||
9651 | } | |||
9652 | ||||
9653 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && | |||
9654 | D.isFunctionDefinition()) { | |||
9655 | // C++ [class.mfct]p2: | |||
9656 | // A member function may be defined (8.4) in its class definition, in | |||
9657 | // which case it is an inline member function (7.1.2) | |||
9658 | NewFD->setImplicitlyInline(); | |||
9659 | } | |||
9660 | ||||
9661 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && | |||
9662 | !CurContext->isRecord()) { | |||
9663 | // C++ [class.static]p1: | |||
9664 | // A data or function member of a class may be declared static | |||
9665 | // in a class definition, in which case it is a static member of | |||
9666 | // the class. | |||
9667 | ||||
9668 | // Complain about the 'static' specifier if it's on an out-of-line | |||
9669 | // member function definition. | |||
9670 | ||||
9671 | // MSVC permits the use of a 'static' storage specifier on an out-of-line | |||
9672 | // member function template declaration and class member template | |||
9673 | // declaration (MSVC versions before 2015), warn about this. | |||
9674 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | |||
9675 | ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | |||
9676 | cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || | |||
9677 | (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) | |||
9678 | ? diag::ext_static_out_of_line : diag::err_static_out_of_line) | |||
9679 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | |||
9680 | } | |||
9681 | ||||
9682 | // C++11 [except.spec]p15: | |||
9683 | // A deallocation function with no exception-specification is treated | |||
9684 | // as if it were specified with noexcept(true). | |||
9685 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); | |||
9686 | if ((Name.getCXXOverloadedOperator() == OO_Delete || | |||
9687 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && | |||
9688 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) | |||
9689 | NewFD->setType(Context.getFunctionType( | |||
9690 | FPT->getReturnType(), FPT->getParamTypes(), | |||
9691 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); | |||
9692 | } | |||
9693 | ||||
9694 | // Filter out previous declarations that don't match the scope. | |||
9695 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), | |||
9696 | D.getCXXScopeSpec().isNotEmpty() || | |||
9697 | isMemberSpecialization || | |||
9698 | isFunctionTemplateSpecialization); | |||
9699 | ||||
9700 | // Handle GNU asm-label extension (encoded as an attribute). | |||
9701 | if (Expr *E = (Expr*) D.getAsmLabel()) { | |||
9702 | // The parser guarantees this is a string. | |||
9703 | StringLiteral *SE = cast<StringLiteral>(E); | |||
9704 | NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), | |||
9705 | /*IsLiteralLabel=*/true, | |||
9706 | SE->getStrTokenLoc(0))); | |||
9707 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | |||
9708 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | |||
9709 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); | |||
9710 | if (I != ExtnameUndeclaredIdentifiers.end()) { | |||
9711 | if (isDeclExternC(NewFD)) { | |||
9712 | NewFD->addAttr(I->second); | |||
9713 | ExtnameUndeclaredIdentifiers.erase(I); | |||
9714 | } else | |||
9715 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) | |||
9716 | << /*Variable*/0 << NewFD; | |||
9717 | } | |||
9718 | } | |||
9719 | ||||
9720 | // Copy the parameter declarations from the declarator D to the function | |||
9721 | // declaration NewFD, if they are available. First scavenge them into Params. | |||
9722 | SmallVector<ParmVarDecl*, 16> Params; | |||
9723 | unsigned FTIIdx; | |||
9724 | if (D.isFunctionDeclarator(FTIIdx)) { | |||
9725 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; | |||
9726 | ||||
9727 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs | |||
9728 | // function that takes no arguments, not a function that takes a | |||
9729 | // single void argument. | |||
9730 | // We let through "const void" here because Sema::GetTypeForDeclarator | |||
9731 | // already checks for that case. | |||
9732 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { | |||
9733 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | |||
9734 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | |||
9735 | assert(Param->getDeclContext() != NewFD && "Was set before ?")(static_cast <bool> (Param->getDeclContext() != NewFD && "Was set before ?") ? void (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"" , "clang/lib/Sema/SemaDecl.cpp", 9735, __extension__ __PRETTY_FUNCTION__ )); | |||
9736 | Param->setDeclContext(NewFD); | |||
9737 | Params.push_back(Param); | |||
9738 | ||||
9739 | if (Param->isInvalidDecl()) | |||
9740 | NewFD->setInvalidDecl(); | |||
9741 | } | |||
9742 | } | |||
9743 | ||||
9744 | if (!getLangOpts().CPlusPlus) { | |||
9745 | // In C, find all the tag declarations from the prototype and move them | |||
9746 | // into the function DeclContext. Remove them from the surrounding tag | |||
9747 | // injection context of the function, which is typically but not always | |||
9748 | // the TU. | |||
9749 | DeclContext *PrototypeTagContext = | |||
9750 | getTagInjectionContext(NewFD->getLexicalDeclContext()); | |||
9751 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { | |||
9752 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); | |||
9753 | ||||
9754 | // We don't want to reparent enumerators. Look at their parent enum | |||
9755 | // instead. | |||
9756 | if (!TD) { | |||
9757 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) | |||
9758 | TD = cast<EnumDecl>(ECD->getDeclContext()); | |||
9759 | } | |||
9760 | if (!TD) | |||
9761 | continue; | |||
9762 | DeclContext *TagDC = TD->getLexicalDeclContext(); | |||
9763 | if (!TagDC->containsDecl(TD)) | |||
9764 | continue; | |||
9765 | TagDC->removeDecl(TD); | |||
9766 | TD->setDeclContext(NewFD); | |||
9767 | NewFD->addDecl(TD); | |||
9768 | ||||
9769 | // Preserve the lexical DeclContext if it is not the surrounding tag | |||
9770 | // injection context of the FD. In this example, the semantic context of | |||
9771 | // E will be f and the lexical context will be S, while both the | |||
9772 | // semantic and lexical contexts of S will be f: | |||
9773 | // void f(struct S { enum E { a } f; } s); | |||
9774 | if (TagDC != PrototypeTagContext) | |||
9775 | TD->setLexicalDeclContext(TagDC); | |||
9776 | } | |||
9777 | } | |||
9778 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { | |||
9779 | // When we're declaring a function with a typedef, typeof, etc as in the | |||
9780 | // following example, we'll need to synthesize (unnamed) | |||
9781 | // parameters for use in the declaration. | |||
9782 | // | |||
9783 | // @code | |||
9784 | // typedef void fn(int); | |||
9785 | // fn f; | |||
9786 | // @endcode | |||
9787 | ||||
9788 | // Synthesize a parameter for each argument type. | |||
9789 | for (const auto &AI : FT->param_types()) { | |||
9790 | ParmVarDecl *Param = | |||
9791 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); | |||
9792 | Param->setScopeInfo(0, Params.size()); | |||
9793 | Params.push_back(Param); | |||
9794 | } | |||
9795 | } else { | |||
9796 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&(static_cast <bool> (R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn" ) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "clang/lib/Sema/SemaDecl.cpp", 9797, __extension__ __PRETTY_FUNCTION__ )) | |||
9797 | "Should not need args for typedef of non-prototype fn")(static_cast <bool> (R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn" ) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "clang/lib/Sema/SemaDecl.cpp", 9797, __extension__ __PRETTY_FUNCTION__ )); | |||
9798 | } | |||
9799 | ||||
9800 | // Finally, we know we have the right number of parameters, install them. | |||
9801 | NewFD->setParams(Params); | |||
9802 | ||||
9803 | if (D.getDeclSpec().isNoreturnSpecified()) | |||
9804 | NewFD->addAttr(C11NoReturnAttr::Create(Context, | |||
9805 | D.getDeclSpec().getNoreturnSpecLoc(), | |||
9806 | AttributeCommonInfo::AS_Keyword)); | |||
9807 | ||||
9808 | // Functions returning a variably modified type violate C99 6.7.5.2p2 | |||
9809 | // because all functions have linkage. | |||
9810 | if (!NewFD->isInvalidDecl() && | |||
9811 | NewFD->getReturnType()->isVariablyModifiedType()) { | |||
9812 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); | |||
9813 | NewFD->setInvalidDecl(); | |||
9814 | } | |||
9815 | ||||
9816 | // Apply an implicit SectionAttr if '#pragma clang section text' is active | |||
9817 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && | |||
9818 | !NewFD->hasAttr<SectionAttr>()) | |||
9819 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( | |||
9820 | Context, PragmaClangTextSection.SectionName, | |||
9821 | PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); | |||
9822 | ||||
9823 | // Apply an implicit SectionAttr if #pragma code_seg is active. | |||
9824 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && | |||
9825 | !NewFD->hasAttr<SectionAttr>()) { | |||
9826 | NewFD->addAttr(SectionAttr::CreateImplicit( | |||
9827 | Context, CodeSegStack.CurrentValue->getString(), | |||
9828 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | |||
9829 | SectionAttr::Declspec_allocate)); | |||
9830 | if (UnifySection(CodeSegStack.CurrentValue->getString(), | |||
9831 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | | |||
9832 | ASTContext::PSF_Read, | |||
9833 | NewFD)) | |||
9834 | NewFD->dropAttr<SectionAttr>(); | |||
9835 | } | |||
9836 | ||||
9837 | // Apply an implicit CodeSegAttr from class declspec or | |||
9838 | // apply an implicit SectionAttr from #pragma code_seg if active. | |||
9839 | if (!NewFD->hasAttr<CodeSegAttr>()) { | |||
9840 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, | |||
9841 | D.isFunctionDefinition())) { | |||
9842 | NewFD->addAttr(SAttr); | |||
9843 | } | |||
9844 | } | |||
9845 | ||||
9846 | // Handle attributes. | |||
9847 | ProcessDeclAttributes(S, NewFD, D); | |||
9848 | ||||
9849 | if (getLangOpts().OpenCL) { | |||
9850 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return | |||
9851 | // type declaration will generate a compilation error. | |||
9852 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); | |||
9853 | if (AddressSpace != LangAS::Default) { | |||
9854 | Diag(NewFD->getLocation(), | |||
9855 | diag::err_opencl_return_value_with_address_space); | |||
9856 | NewFD->setInvalidDecl(); | |||
9857 | } | |||
9858 | } | |||
9859 | ||||
9860 | if (!getLangOpts().CPlusPlus) { | |||
9861 | // Perform semantic checking on the function declaration. | |||
9862 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | |||
9863 | CheckMain(NewFD, D.getDeclSpec()); | |||
9864 | ||||
9865 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | |||
9866 | CheckMSVCRTEntryPoint(NewFD); | |||
9867 | ||||
9868 | if (!NewFD->isInvalidDecl()) | |||
9869 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | |||
9870 | isMemberSpecialization, | |||
9871 | D.isFunctionDefinition())); | |||
9872 | else if (!Previous.empty()) | |||
9873 | // Recover gracefully from an invalid redeclaration. | |||
9874 | D.setRedeclaration(true); | |||
9875 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9877, __extension__ __PRETTY_FUNCTION__ )) | |||
9876 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9877, __extension__ __PRETTY_FUNCTION__ )) | |||
9877 | "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 9877, __extension__ __PRETTY_FUNCTION__ )); | |||
9878 | ||||
9879 | // Diagnose no-prototype function declarations with calling conventions that | |||
9880 | // don't support variadic calls. Only do this in C and do it after merging | |||
9881 | // possibly prototyped redeclarations. | |||
9882 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); | |||
9883 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { | |||
9884 | CallingConv CC = FT->getExtInfo().getCC(); | |||
9885 | if (!supportsVariadicCall(CC)) { | |||
9886 | // Windows system headers sometimes accidentally use stdcall without | |||
9887 | // (void) parameters, so we relax this to a warning. | |||
9888 | int DiagID = | |||
9889 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; | |||
9890 | Diag(NewFD->getLocation(), DiagID) | |||
9891 | << FunctionType::getNameForCallConv(CC); | |||
9892 | } | |||
9893 | } | |||
9894 | ||||
9895 | if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || | |||
9896 | NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) | |||
9897 | checkNonTrivialCUnion(NewFD->getReturnType(), | |||
9898 | NewFD->getReturnTypeSourceRange().getBegin(), | |||
9899 | NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); | |||
9900 | } else { | |||
9901 | // C++11 [replacement.functions]p3: | |||
9902 | // The program's definitions shall not be specified as inline. | |||
9903 | // | |||
9904 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. | |||
9905 | // | |||
9906 | // Suppress the diagnostic if the function is __attribute__((used)), since | |||
9907 | // that forces an external definition to be emitted. | |||
9908 | if (D.getDeclSpec().isInlineSpecified() && | |||
9909 | NewFD->isReplaceableGlobalAllocationFunction() && | |||
9910 | !NewFD->hasAttr<UsedAttr>()) | |||
9911 | Diag(D.getDeclSpec().getInlineSpecLoc(), | |||
9912 | diag::ext_operator_new_delete_declared_inline) | |||
9913 | << NewFD->getDeclName(); | |||
9914 | ||||
9915 | // If the declarator is a template-id, translate the parser's template | |||
9916 | // argument list into our AST format. | |||
9917 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | |||
9918 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; | |||
9919 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); | |||
9920 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); | |||
9921 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | |||
9922 | TemplateId->NumArgs); | |||
9923 | translateTemplateArguments(TemplateArgsPtr, | |||
9924 | TemplateArgs); | |||
9925 | ||||
9926 | HasExplicitTemplateArgs = true; | |||
9927 | ||||
9928 | if (NewFD->isInvalidDecl()) { | |||
9929 | HasExplicitTemplateArgs = false; | |||
9930 | } else if (FunctionTemplate) { | |||
9931 | // Function template with explicit template arguments. | |||
9932 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) | |||
9933 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); | |||
9934 | ||||
9935 | HasExplicitTemplateArgs = false; | |||
9936 | } else { | |||
9937 | assert((isFunctionTemplateSpecialization ||(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 9939, __extension__ __PRETTY_FUNCTION__ )) | |||
9938 | D.getDeclSpec().isFriendSpecified()) &&(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 9939, __extension__ __PRETTY_FUNCTION__ )) | |||
9939 | "should have a 'template<>' for this decl")(static_cast <bool> ((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl" ) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "clang/lib/Sema/SemaDecl.cpp", 9939, __extension__ __PRETTY_FUNCTION__ )); | |||
9940 | // "friend void foo<>(int);" is an implicit specialization decl. | |||
9941 | isFunctionTemplateSpecialization = true; | |||
9942 | } | |||
9943 | } else if (isFriend && isFunctionTemplateSpecialization) { | |||
9944 | // This combination is only possible in a recovery case; the user | |||
9945 | // wrote something like: | |||
9946 | // template <> friend void foo(int); | |||
9947 | // which we're recovering from as if the user had written: | |||
9948 | // friend void foo<>(int); | |||
9949 | // Go ahead and fake up a template id. | |||
9950 | HasExplicitTemplateArgs = true; | |||
9951 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); | |||
9952 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); | |||
9953 | } | |||
9954 | ||||
9955 | // We do not add HD attributes to specializations here because | |||
9956 | // they may have different constexpr-ness compared to their | |||
9957 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, | |||
9958 | // may end up with different effective targets. Instead, a | |||
9959 | // specialization inherits its target attributes from its template | |||
9960 | // in the CheckFunctionTemplateSpecialization() call below. | |||
9961 | if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) | |||
9962 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); | |||
9963 | ||||
9964 | // If it's a friend (and only if it's a friend), it's possible | |||
9965 | // that either the specialized function type or the specialized | |||
9966 | // template is dependent, and therefore matching will fail. In | |||
9967 | // this case, don't check the specialization yet. | |||
9968 | if (isFunctionTemplateSpecialization && isFriend && | |||
9969 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || | |||
9970 | TemplateSpecializationType::anyInstantiationDependentTemplateArguments( | |||
9971 | TemplateArgs.arguments()))) { | |||
9972 | assert(HasExplicitTemplateArgs &&(static_cast <bool> (HasExplicitTemplateArgs && "friend function specialization without template args") ? void (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "clang/lib/Sema/SemaDecl.cpp", 9973, __extension__ __PRETTY_FUNCTION__ )) | |||
9973 | "friend function specialization without template args")(static_cast <bool> (HasExplicitTemplateArgs && "friend function specialization without template args") ? void (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "clang/lib/Sema/SemaDecl.cpp", 9973, __extension__ __PRETTY_FUNCTION__ )); | |||
9974 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, | |||
9975 | Previous)) | |||
9976 | NewFD->setInvalidDecl(); | |||
9977 | } else if (isFunctionTemplateSpecialization) { | |||
9978 | if (CurContext->isDependentContext() && CurContext->isRecord() | |||
9979 | && !isFriend) { | |||
9980 | isDependentClassScopeExplicitSpecialization = true; | |||
9981 | } else if (!NewFD->isInvalidDecl() && | |||
9982 | CheckFunctionTemplateSpecialization( | |||
9983 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), | |||
9984 | Previous)) | |||
9985 | NewFD->setInvalidDecl(); | |||
9986 | ||||
9987 | // C++ [dcl.stc]p1: | |||
9988 | // A storage-class-specifier shall not be specified in an explicit | |||
9989 | // specialization (14.7.3) | |||
9990 | FunctionTemplateSpecializationInfo *Info = | |||
9991 | NewFD->getTemplateSpecializationInfo(); | |||
9992 | if (Info && SC != SC_None) { | |||
9993 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) | |||
9994 | Diag(NewFD->getLocation(), | |||
9995 | diag::err_explicit_specialization_inconsistent_storage_class) | |||
9996 | << SC | |||
9997 | << FixItHint::CreateRemoval( | |||
9998 | D.getDeclSpec().getStorageClassSpecLoc()); | |||
9999 | ||||
10000 | else | |||
10001 | Diag(NewFD->getLocation(), | |||
10002 | diag::ext_explicit_specialization_storage_class) | |||
10003 | << FixItHint::CreateRemoval( | |||
10004 | D.getDeclSpec().getStorageClassSpecLoc()); | |||
10005 | } | |||
10006 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { | |||
10007 | if (CheckMemberSpecialization(NewFD, Previous)) | |||
10008 | NewFD->setInvalidDecl(); | |||
10009 | } | |||
10010 | ||||
10011 | // Perform semantic checking on the function declaration. | |||
10012 | if (!isDependentClassScopeExplicitSpecialization) { | |||
10013 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | |||
10014 | CheckMain(NewFD, D.getDeclSpec()); | |||
10015 | ||||
10016 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | |||
10017 | CheckMSVCRTEntryPoint(NewFD); | |||
10018 | ||||
10019 | if (!NewFD->isInvalidDecl()) | |||
10020 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | |||
10021 | isMemberSpecialization, | |||
10022 | D.isFunctionDefinition())); | |||
10023 | else if (!Previous.empty()) | |||
10024 | // Recover gracefully from an invalid redeclaration. | |||
10025 | D.setRedeclaration(true); | |||
10026 | } | |||
10027 | ||||
10028 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 10030, __extension__ __PRETTY_FUNCTION__ )) | |||
10029 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 10030, __extension__ __PRETTY_FUNCTION__ )) | |||
10030 | "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration () || Previous.getResultKind() != LookupResult::FoundOverloaded ) && "previous declaration set still overloaded") ? void (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "clang/lib/Sema/SemaDecl.cpp", 10030, __extension__ __PRETTY_FUNCTION__ )); | |||
10031 | ||||
10032 | NamedDecl *PrincipalDecl = (FunctionTemplate | |||
10033 | ? cast<NamedDecl>(FunctionTemplate) | |||
10034 | : NewFD); | |||
10035 | ||||
10036 | if (isFriend && NewFD->getPreviousDecl()) { | |||
10037 | AccessSpecifier Access = AS_public; | |||
10038 | if (!NewFD->isInvalidDecl()) | |||
10039 | Access = NewFD->getPreviousDecl()->getAccess(); | |||
10040 | ||||
10041 | NewFD->setAccess(Access); | |||
10042 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); | |||
10043 | } | |||
10044 | ||||
10045 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && | |||
10046 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | |||
10047 | PrincipalDecl->setNonMemberOperator(); | |||
10048 | ||||
10049 | // If we have a function template, check the template parameter | |||
10050 | // list. This will check and merge default template arguments. | |||
10051 | if (FunctionTemplate) { | |||
10052 | FunctionTemplateDecl *PrevTemplate = | |||
10053 | FunctionTemplate->getPreviousDecl(); | |||
10054 | CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), | |||
10055 | PrevTemplate ? PrevTemplate->getTemplateParameters() | |||
10056 | : nullptr, | |||
10057 | D.getDeclSpec().isFriendSpecified() | |||
10058 | ? (D.isFunctionDefinition() | |||
10059 | ? TPC_FriendFunctionTemplateDefinition | |||
10060 | : TPC_FriendFunctionTemplate) | |||
10061 | : (D.getCXXScopeSpec().isSet() && | |||
10062 | DC && DC->isRecord() && | |||
10063 | DC->isDependentContext()) | |||
10064 | ? TPC_ClassTemplateMember | |||
10065 | : TPC_FunctionTemplate); | |||
10066 | } | |||
10067 | ||||
10068 | if (NewFD->isInvalidDecl()) { | |||
10069 | // Ignore all the rest of this. | |||
10070 | } else if (!D.isRedeclaration()) { | |||
10071 | struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, | |||
10072 | AddToScope }; | |||
10073 | // Fake up an access specifier if it's supposed to be a class member. | |||
10074 | if (isa<CXXRecordDecl>(NewFD->getDeclContext())) | |||
10075 | NewFD->setAccess(AS_public); | |||
10076 | ||||
10077 | // Qualified decls generally require a previous declaration. | |||
10078 | if (D.getCXXScopeSpec().isSet()) { | |||
10079 | // ...with the major exception of templated-scope or | |||
10080 | // dependent-scope friend declarations. | |||
10081 | ||||
10082 | // TODO: we currently also suppress this check in dependent | |||
10083 | // contexts because (1) the parameter depth will be off when | |||
10084 | // matching friend templates and (2) we might actually be | |||
10085 | // selecting a friend based on a dependent factor. But there | |||
10086 | // are situations where these conditions don't apply and we | |||
10087 | // can actually do this check immediately. | |||
10088 | // | |||
10089 | // Unless the scope is dependent, it's always an error if qualified | |||
10090 | // redeclaration lookup found nothing at all. Diagnose that now; | |||
10091 | // nothing will diagnose that error later. | |||
10092 | if (isFriend && | |||
10093 | (D.getCXXScopeSpec().getScopeRep()->isDependent() || | |||
10094 | (!Previous.empty() && CurContext->isDependentContext()))) { | |||
10095 | // ignore these | |||
10096 | } else if (NewFD->isCPUDispatchMultiVersion() || | |||
10097 | NewFD->isCPUSpecificMultiVersion()) { | |||
10098 | // ignore this, we allow the redeclaration behavior here to create new | |||
10099 | // versions of the function. | |||
10100 | } else { | |||
10101 | // The user tried to provide an out-of-line definition for a | |||
10102 | // function that is a member of a class or namespace, but there | |||
10103 | // was no such member function declared (C++ [class.mfct]p2, | |||
10104 | // C++ [namespace.memdef]p2). For example: | |||
10105 | // | |||
10106 | // class X { | |||
10107 | // void f() const; | |||
10108 | // }; | |||
10109 | // | |||
10110 | // void X::f() { } // ill-formed | |||
10111 | // | |||
10112 | // Complain about this problem, and attempt to suggest close | |||
10113 | // matches (e.g., those that differ only in cv-qualifiers and | |||
10114 | // whether the parameter types are references). | |||
10115 | ||||
10116 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | |||
10117 | *this, Previous, NewFD, ExtraArgs, false, nullptr)) { | |||
10118 | AddToScope = ExtraArgs.AddToScope; | |||
10119 | return Result; | |||
10120 | } | |||
10121 | } | |||
10122 | ||||
10123 | // Unqualified local friend declarations are required to resolve | |||
10124 | // to something. | |||
10125 | } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { | |||
10126 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | |||
10127 | *this, Previous, NewFD, ExtraArgs, true, S)) { | |||
10128 | AddToScope = ExtraArgs.AddToScope; | |||
10129 | return Result; | |||
10130 | } | |||
10131 | } | |||
10132 | } else if (!D.isFunctionDefinition() && | |||
10133 | isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && | |||
10134 | !isFriend && !isFunctionTemplateSpecialization && | |||
10135 | !isMemberSpecialization) { | |||
10136 | // An out-of-line member function declaration must also be a | |||
10137 | // definition (C++ [class.mfct]p2). | |||
10138 | // Note that this is not the case for explicit specializations of | |||
10139 | // function templates or member functions of class templates, per | |||
10140 | // C++ [temp.expl.spec]p2. We also allow these declarations as an | |||
10141 | // extension for compatibility with old SWIG code which likes to | |||
10142 | // generate them. | |||
10143 | Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) | |||
10144 | << D.getCXXScopeSpec().getRange(); | |||
10145 | } | |||
10146 | } | |||
10147 | ||||
10148 | // If this is the first declaration of a library builtin function, add | |||
10149 | // attributes as appropriate. | |||
10150 | if (!D.isRedeclaration()) { | |||
10151 | if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { | |||
10152 | if (unsigned BuiltinID = II->getBuiltinID()) { | |||
10153 | bool InStdNamespace = Context.BuiltinInfo.isInStdNamespace(BuiltinID); | |||
10154 | if (!InStdNamespace && | |||
10155 | NewFD->getDeclContext()->getRedeclContext()->isFileContext()) { | |||
10156 | if (NewFD->getLanguageLinkage() == CLanguageLinkage) { | |||
10157 | // Validate the type matches unless this builtin is specified as | |||
10158 | // matching regardless of its declared type. | |||
10159 | if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) { | |||
10160 | NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); | |||
10161 | } else { | |||
10162 | ASTContext::GetBuiltinTypeError Error; | |||
10163 | LookupNecessaryTypesForBuiltin(S, BuiltinID); | |||
10164 | QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); | |||
10165 | ||||
10166 | if (!Error && !BuiltinType.isNull() && | |||
10167 | Context.hasSameFunctionTypeIgnoringExceptionSpec( | |||
10168 | NewFD->getType(), BuiltinType)) | |||
10169 | NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); | |||
10170 | } | |||
10171 | } | |||
10172 | } else if (InStdNamespace && NewFD->isInStdNamespace() && | |||
10173 | isStdBuiltin(Context, NewFD, BuiltinID)) { | |||
10174 | NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); | |||
10175 | } | |||
10176 | } | |||
10177 | } | |||
10178 | } | |||
10179 | ||||
10180 | ProcessPragmaWeak(S, NewFD); | |||
10181 | checkAttributesAfterMerging(*this, *NewFD); | |||
10182 | ||||
10183 | AddKnownFunctionAttributes(NewFD); | |||
10184 | ||||
10185 | if (NewFD->hasAttr<OverloadableAttr>() && | |||
10186 | !NewFD->getType()->getAs<FunctionProtoType>()) { | |||
10187 | Diag(NewFD->getLocation(), | |||
10188 | diag::err_attribute_overloadable_no_prototype) | |||
10189 | << NewFD; | |||
10190 | ||||
10191 | // Turn this into a variadic function with no parameters. | |||
10192 | const auto *FT = NewFD->getType()->castAs<FunctionType>(); | |||
10193 | FunctionProtoType::ExtProtoInfo EPI( | |||
10194 | Context.getDefaultCallingConvention(true, false)); | |||
10195 | EPI.Variadic = true; | |||
10196 | EPI.ExtInfo = FT->getExtInfo(); | |||
10197 | ||||
10198 | QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); | |||
10199 | NewFD->setType(R); | |||
10200 | } | |||
10201 | ||||
10202 | // If there's a #pragma GCC visibility in scope, and this isn't a class | |||
10203 | // member, set the visibility of this function. | |||
10204 | if (!DC->isRecord() && NewFD->isExternallyVisible()) | |||
10205 | AddPushedVisibilityAttribute(NewFD); | |||
10206 | ||||
10207 | // If there's a #pragma clang arc_cf_code_audited in scope, consider | |||
10208 | // marking the function. | |||
10209 | AddCFAuditedAttribute(NewFD); | |||
10210 | ||||
10211 | // If this is a function definition, check if we have to apply optnone due to | |||
10212 | // a pragma. | |||
10213 | if(D.isFunctionDefinition()) | |||
10214 | AddRangeBasedOptnone(NewFD); | |||
10215 | ||||
10216 | // If this is the first declaration of an extern C variable, update | |||
10217 | // the map of such variables. | |||
10218 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && | |||
10219 | isIncompleteDeclExternC(*this, NewFD)) | |||
10220 | RegisterLocallyScopedExternCDecl(NewFD, S); | |||
10221 | ||||
10222 | // Set this FunctionDecl's range up to the right paren. | |||
10223 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); | |||
10224 | ||||
10225 | if (D.isRedeclaration() && !Previous.empty()) { | |||
10226 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | |||
10227 | checkDLLAttributeRedeclaration(*this, Prev, NewFD, | |||
10228 | isMemberSpecialization || | |||
10229 | isFunctionTemplateSpecialization, | |||
10230 | D.isFunctionDefinition()); | |||
10231 | } | |||
10232 | ||||
10233 | if (getLangOpts().CUDA) { | |||
10234 | IdentifierInfo *II = NewFD->getIdentifier(); | |||
10235 | if (II && II->isStr(getCudaConfigureFuncName()) && | |||
10236 | !NewFD->isInvalidDecl() && | |||
10237 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | |||
10238 | if (!R->castAs<FunctionType>()->getReturnType()->isScalarType()) | |||
10239 | Diag(NewFD->getLocation(), diag::err_config_scalar_return) | |||
10240 | << getCudaConfigureFuncName(); | |||
10241 | Context.setcudaConfigureCallDecl(NewFD); | |||
10242 | } | |||
10243 | ||||
10244 | // Variadic functions, other than a *declaration* of printf, are not allowed | |||
10245 | // in device-side CUDA code, unless someone passed | |||
10246 | // -fcuda-allow-variadic-functions. | |||
10247 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && | |||
10248 | (NewFD->hasAttr<CUDADeviceAttr>() || | |||
10249 | NewFD->hasAttr<CUDAGlobalAttr>()) && | |||
10250 | !(II && II->isStr("printf") && NewFD->isExternC() && | |||
10251 | !D.isFunctionDefinition())) { | |||
10252 | Diag(NewFD->getLocation(), diag::err_variadic_device_fn); | |||
10253 | } | |||
10254 | } | |||
10255 | ||||
10256 | MarkUnusedFileScopedDecl(NewFD); | |||
10257 | ||||
10258 | ||||
10259 | ||||
10260 | if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { | |||
10261 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. | |||
10262 | if (SC == SC_Static) { | |||
10263 | Diag(D.getIdentifierLoc(), diag::err_static_kernel); | |||
10264 | D.setInvalidType(); | |||
10265 | } | |||
10266 | ||||
10267 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. | |||
10268 | if (!NewFD->getReturnType()->isVoidType()) { | |||
10269 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); | |||
10270 | Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) | |||
10271 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") | |||
10272 | : FixItHint()); | |||
10273 | D.setInvalidType(); | |||
10274 | } | |||
10275 | ||||
10276 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; | |||
10277 | for (auto Param : NewFD->parameters()) | |||
10278 | checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); | |||
10279 | ||||
10280 | if (getLangOpts().OpenCLCPlusPlus) { | |||
10281 | if (DC->isRecord()) { | |||
10282 | Diag(D.getIdentifierLoc(), diag::err_method_kernel); | |||
10283 | D.setInvalidType(); | |||
10284 | } | |||
10285 | if (FunctionTemplate) { | |||
10286 | Diag(D.getIdentifierLoc(), diag::err_template_kernel); | |||
10287 | D.setInvalidType(); | |||
10288 | } | |||
10289 | } | |||
10290 | } | |||
10291 | ||||
10292 | if (getLangOpts().CPlusPlus) { | |||
10293 | if (FunctionTemplate) { | |||
10294 | if (NewFD->isInvalidDecl()) | |||
10295 | FunctionTemplate->setInvalidDecl(); | |||
10296 | return FunctionTemplate; | |||
10297 | } | |||
10298 | ||||
10299 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) | |||
10300 | CompleteMemberSpecialization(NewFD, Previous); | |||
10301 | } | |||
10302 | ||||
10303 | for (const ParmVarDecl *Param : NewFD->parameters()) { | |||
10304 | QualType PT = Param->getType(); | |||
10305 | ||||
10306 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value | |||
10307 | // types. | |||
10308 | if (getLangOpts().getOpenCLCompatibleVersion() >= 200) { | |||
10309 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { | |||
10310 | QualType ElemTy = PipeTy->getElementType(); | |||
10311 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { | |||
10312 | Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); | |||
10313 | D.setInvalidType(); | |||
10314 | } | |||
10315 | } | |||
10316 | } | |||
10317 | } | |||
10318 | ||||
10319 | // Here we have an function template explicit specialization at class scope. | |||
10320 | // The actual specialization will be postponed to template instatiation | |||
10321 | // time via the ClassScopeFunctionSpecializationDecl node. | |||
10322 | if (isDependentClassScopeExplicitSpecialization) { | |||
10323 | ClassScopeFunctionSpecializationDecl *NewSpec = | |||
10324 | ClassScopeFunctionSpecializationDecl::Create( | |||
10325 | Context, CurContext, NewFD->getLocation(), | |||
10326 | cast<CXXMethodDecl>(NewFD), | |||
10327 | HasExplicitTemplateArgs, TemplateArgs); | |||
10328 | CurContext->addDecl(NewSpec); | |||
10329 | AddToScope = false; | |||
10330 | } | |||
10331 | ||||
10332 | // Diagnose availability attributes. Availability cannot be used on functions | |||
10333 | // that are run during load/unload. | |||
10334 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { | |||
10335 | if (NewFD->hasAttr<ConstructorAttr>()) { | |||
10336 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | |||
10337 | << 1; | |||
10338 | NewFD->dropAttr<AvailabilityAttr>(); | |||
10339 | } | |||
10340 | if (NewFD->hasAttr<DestructorAttr>()) { | |||
10341 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | |||
10342 | << 2; | |||
10343 | NewFD->dropAttr<AvailabilityAttr>(); | |||
10344 | } | |||
10345 | } | |||
10346 | ||||
10347 | // Diagnose no_builtin attribute on function declaration that are not a | |||
10348 | // definition. | |||
10349 | // FIXME: We should really be doing this in | |||
10350 | // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to | |||
10351 | // the FunctionDecl and at this point of the code | |||
10352 | // FunctionDecl::isThisDeclarationADefinition() which always returns `false` | |||
10353 | // because Sema::ActOnStartOfFunctionDef has not been called yet. | |||
10354 | if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) | |||
10355 | switch (D.getFunctionDefinitionKind()) { | |||
10356 | case FunctionDefinitionKind::Defaulted: | |||
10357 | case FunctionDefinitionKind::Deleted: | |||
10358 | Diag(NBA->getLocation(), | |||
10359 | diag::err_attribute_no_builtin_on_defaulted_deleted_function) | |||
10360 | << NBA->getSpelling(); | |||
10361 | break; | |||
10362 | case FunctionDefinitionKind::Declaration: | |||
10363 | Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) | |||
10364 | << NBA->getSpelling(); | |||
10365 | break; | |||
10366 | case FunctionDefinitionKind::Definition: | |||
10367 | break; | |||
10368 | } | |||
10369 | ||||
10370 | return NewFD; | |||
10371 | } | |||
10372 | ||||
10373 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say | |||
10374 | /// when __declspec(code_seg) "is applied to a class, all member functions of | |||
10375 | /// the class and nested classes -- this includes compiler-generated special | |||
10376 | /// member functions -- are put in the specified segment." | |||
10377 | /// The actual behavior is a little more complicated. The Microsoft compiler | |||
10378 | /// won't check outer classes if there is an active value from #pragma code_seg. | |||
10379 | /// The CodeSeg is always applied from the direct parent but only from outer | |||
10380 | /// classes when the #pragma code_seg stack is empty. See: | |||
10381 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer | |||
10382 | /// available since MS has removed the page. | |||
10383 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { | |||
10384 | const auto *Method = dyn_cast<CXXMethodDecl>(FD); | |||
10385 | if (!Method) | |||
10386 | return nullptr; | |||
10387 | const CXXRecordDecl *Parent = Method->getParent(); | |||
10388 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | |||
10389 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | |||
10390 | NewAttr->setImplicit(true); | |||
10391 | return NewAttr; | |||
10392 | } | |||
10393 | ||||
10394 | // The Microsoft compiler won't check outer classes for the CodeSeg | |||
10395 | // when the #pragma code_seg stack is active. | |||
10396 | if (S.CodeSegStack.CurrentValue) | |||
10397 | return nullptr; | |||
10398 | ||||
10399 | while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { | |||
10400 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | |||
10401 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | |||
10402 | NewAttr->setImplicit(true); | |||
10403 | return NewAttr; | |||
10404 | } | |||
10405 | } | |||
10406 | return nullptr; | |||
10407 | } | |||
10408 | ||||
10409 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a | |||
10410 | /// containing class. Otherwise it will return implicit SectionAttr if the | |||
10411 | /// function is a definition and there is an active value on CodeSegStack | |||
10412 | /// (from the current #pragma code-seg value). | |||
10413 | /// | |||
10414 | /// \param FD Function being declared. | |||
10415 | /// \param IsDefinition Whether it is a definition or just a declarartion. | |||
10416 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or | |||
10417 | /// nullptr if no attribute should be added. | |||
10418 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, | |||
10419 | bool IsDefinition) { | |||
10420 | if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) | |||
10421 | return A; | |||
10422 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && | |||
10423 | CodeSegStack.CurrentValue) | |||
10424 | return SectionAttr::CreateImplicit( | |||
10425 | getASTContext(), CodeSegStack.CurrentValue->getString(), | |||
10426 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | |||
10427 | SectionAttr::Declspec_allocate); | |||
10428 | return nullptr; | |||
10429 | } | |||
10430 | ||||
10431 | /// Determines if we can perform a correct type check for \p D as a | |||
10432 | /// redeclaration of \p PrevDecl. If not, we can generally still perform a | |||
10433 | /// best-effort check. | |||
10434 | /// | |||
10435 | /// \param NewD The new declaration. | |||
10436 | /// \param OldD The old declaration. | |||
10437 | /// \param NewT The portion of the type of the new declaration to check. | |||
10438 | /// \param OldT The portion of the type of the old declaration to check. | |||
10439 | bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, | |||
10440 | QualType NewT, QualType OldT) { | |||
10441 | if (!NewD->getLexicalDeclContext()->isDependentContext()) | |||
10442 | return true; | |||
10443 | ||||
10444 | // For dependently-typed local extern declarations and friends, we can't | |||
10445 | // perform a correct type check in general until instantiation: | |||
10446 | // | |||
10447 | // int f(); | |||
10448 | // template<typename T> void g() { T f(); } | |||
10449 | // | |||
10450 | // (valid if g() is only instantiated with T = int). | |||
10451 | if (NewT->isDependentType() && | |||
10452 | (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) | |||
10453 | return false; | |||
10454 | ||||
10455 | // Similarly, if the previous declaration was a dependent local extern | |||
10456 | // declaration, we don't really know its type yet. | |||
10457 | if (OldT->isDependentType() && OldD->isLocalExternDecl()) | |||
10458 | return false; | |||
10459 | ||||
10460 | return true; | |||
10461 | } | |||
10462 | ||||
10463 | /// Checks if the new declaration declared in dependent context must be | |||
10464 | /// put in the same redeclaration chain as the specified declaration. | |||
10465 | /// | |||
10466 | /// \param D Declaration that is checked. | |||
10467 | /// \param PrevDecl Previous declaration found with proper lookup method for the | |||
10468 | /// same declaration name. | |||
10469 | /// \returns True if D must be added to the redeclaration chain which PrevDecl | |||
10470 | /// belongs to. | |||
10471 | /// | |||
10472 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { | |||
10473 | if (!D->getLexicalDeclContext()->isDependentContext()) | |||
10474 | return true; | |||
10475 | ||||
10476 | // Don't chain dependent friend function definitions until instantiation, to | |||
10477 | // permit cases like | |||
10478 | // | |||
10479 | // void func(); | |||
10480 | // template<typename T> class C1 { friend void func() {} }; | |||
10481 | // template<typename T> class C2 { friend void func() {} }; | |||
10482 | // | |||
10483 | // ... which is valid if only one of C1 and C2 is ever instantiated. | |||
10484 | // | |||
10485 | // FIXME: This need only apply to function definitions. For now, we proxy | |||
10486 | // this by checking for a file-scope function. We do not want this to apply | |||
10487 | // to friend declarations nominating member functions, because that gets in | |||
10488 | // the way of access checks. | |||
10489 | if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) | |||
10490 | return false; | |||
10491 | ||||
10492 | auto *VD = dyn_cast<ValueDecl>(D); | |||
10493 | auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); | |||
10494 | return !VD || !PrevVD || | |||
10495 | canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), | |||
10496 | PrevVD->getType()); | |||
10497 | } | |||
10498 | ||||
10499 | /// Check the target attribute of the function for MultiVersion | |||
10500 | /// validity. | |||
10501 | /// | |||
10502 | /// Returns true if there was an error, false otherwise. | |||
10503 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { | |||
10504 | const auto *TA = FD->getAttr<TargetAttr>(); | |||
10505 | assert(TA && "MultiVersion Candidate requires a target attribute")(static_cast <bool> (TA && "MultiVersion Candidate requires a target attribute" ) ? void (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\"" , "clang/lib/Sema/SemaDecl.cpp", 10505, __extension__ __PRETTY_FUNCTION__ )); | |||
10506 | ParsedTargetAttr ParseInfo = TA->parse(); | |||
10507 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); | |||
10508 | enum ErrType { Feature = 0, Architecture = 1 }; | |||
10509 | ||||
10510 | if (!ParseInfo.Architecture.empty() && | |||
10511 | !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { | |||
10512 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
10513 | << Architecture << ParseInfo.Architecture; | |||
10514 | return true; | |||
10515 | } | |||
10516 | ||||
10517 | for (const auto &Feat : ParseInfo.Features) { | |||
10518 | auto BareFeat = StringRef{Feat}.substr(1); | |||
10519 | if (Feat[0] == '-') { | |||
10520 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
10521 | << Feature << ("no-" + BareFeat).str(); | |||
10522 | return true; | |||
10523 | } | |||
10524 | ||||
10525 | if (!TargetInfo.validateCpuSupports(BareFeat) || | |||
10526 | !TargetInfo.isValidFeatureName(BareFeat)) { | |||
10527 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | |||
10528 | << Feature << BareFeat; | |||
10529 | return true; | |||
10530 | } | |||
10531 | } | |||
10532 | return false; | |||
10533 | } | |||
10534 | ||||
10535 | // Provide a white-list of attributes that are allowed to be combined with | |||
10536 | // multiversion functions. | |||
10537 | static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, | |||
10538 | MultiVersionKind MVKind) { | |||
10539 | // Note: this list/diagnosis must match the list in | |||
10540 | // checkMultiversionAttributesAllSame. | |||
10541 | switch (Kind) { | |||
10542 | default: | |||
10543 | return false; | |||
10544 | case attr::Used: | |||
10545 | return MVKind == MultiVersionKind::Target; | |||
10546 | case attr::NonNull: | |||
10547 | case attr::NoThrow: | |||
10548 | return true; | |||
10549 | } | |||
10550 | } | |||
10551 | ||||
10552 | static bool checkNonMultiVersionCompatAttributes(Sema &S, | |||
10553 | const FunctionDecl *FD, | |||
10554 | const FunctionDecl *CausedFD, | |||
10555 | MultiVersionKind MVKind) { | |||
10556 | const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) { | |||
10557 | S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) | |||
10558 | << static_cast<unsigned>(MVKind) << A; | |||
10559 | if (CausedFD) | |||
10560 | S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); | |||
10561 | return true; | |||
10562 | }; | |||
10563 | ||||
10564 | for (const Attr *A : FD->attrs()) { | |||
10565 | switch (A->getKind()) { | |||
10566 | case attr::CPUDispatch: | |||
10567 | case attr::CPUSpecific: | |||
10568 | if (MVKind != MultiVersionKind::CPUDispatch && | |||
10569 | MVKind != MultiVersionKind::CPUSpecific) | |||
10570 | return Diagnose(S, A); | |||
10571 | break; | |||
10572 | case attr::Target: | |||
10573 | if (MVKind != MultiVersionKind::Target) | |||
10574 | return Diagnose(S, A); | |||
10575 | break; | |||
10576 | case attr::TargetClones: | |||
10577 | if (MVKind != MultiVersionKind::TargetClones) | |||
10578 | return Diagnose(S, A); | |||
10579 | break; | |||
10580 | default: | |||
10581 | if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind)) | |||
10582 | return Diagnose(S, A); | |||
10583 | break; | |||
10584 | } | |||
10585 | } | |||
10586 | return false; | |||
10587 | } | |||
10588 | ||||
10589 | bool Sema::areMultiversionVariantFunctionsCompatible( | |||
10590 | const FunctionDecl *OldFD, const FunctionDecl *NewFD, | |||
10591 | const PartialDiagnostic &NoProtoDiagID, | |||
10592 | const PartialDiagnosticAt &NoteCausedDiagIDAt, | |||
10593 | const PartialDiagnosticAt &NoSupportDiagIDAt, | |||
10594 | const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, | |||
10595 | bool ConstexprSupported, bool CLinkageMayDiffer) { | |||
10596 | enum DoesntSupport { | |||
10597 | FuncTemplates = 0, | |||
10598 | VirtFuncs = 1, | |||
10599 | DeducedReturn = 2, | |||
10600 | Constructors = 3, | |||
10601 | Destructors = 4, | |||
10602 | DeletedFuncs = 5, | |||
10603 | DefaultedFuncs = 6, | |||
10604 | ConstexprFuncs = 7, | |||
10605 | ConstevalFuncs = 8, | |||
10606 | Lambda = 9, | |||
10607 | }; | |||
10608 | enum Different { | |||
10609 | CallingConv = 0, | |||
10610 | ReturnType = 1, | |||
10611 | ConstexprSpec = 2, | |||
10612 | InlineSpec = 3, | |||
10613 | Linkage = 4, | |||
10614 | LanguageLinkage = 5, | |||
10615 | }; | |||
10616 | ||||
10617 | if (NoProtoDiagID.getDiagID() != 0 && OldFD && | |||
10618 | !OldFD->getType()->getAs<FunctionProtoType>()) { | |||
10619 | Diag(OldFD->getLocation(), NoProtoDiagID); | |||
10620 | Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); | |||
10621 | return true; | |||
10622 | } | |||
10623 | ||||
10624 | if (NoProtoDiagID.getDiagID() != 0 && | |||
10625 | !NewFD->getType()->getAs<FunctionProtoType>()) | |||
10626 | return Diag(NewFD->getLocation(), NoProtoDiagID); | |||
10627 | ||||
10628 | if (!TemplatesSupported && | |||
10629 | NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) | |||
10630 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | |||
10631 | << FuncTemplates; | |||
10632 | ||||
10633 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { | |||
10634 | if (NewCXXFD->isVirtual()) | |||
10635 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | |||
10636 | << VirtFuncs; | |||
10637 | ||||
10638 | if (isa<CXXConstructorDecl>(NewCXXFD)) | |||
10639 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | |||
10640 | << Constructors; | |||
10641 | ||||
10642 | if (isa<CXXDestructorDecl>(NewCXXFD)) | |||
10643 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | |||
10644 | << Destructors; | |||
10645 | } | |||
10646 | ||||
10647 | if (NewFD->isDeleted()) | |||
10648 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | |||
10649 | << DeletedFuncs; | |||
10650 | ||||
10651 | if (NewFD->isDefaulted()) | |||
10652 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | |||
10653 | << DefaultedFuncs; | |||
10654 | ||||
10655 | if (!ConstexprSupported && NewFD->isConstexpr()) | |||
10656 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | |||
10657 | << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); | |||
10658 | ||||
10659 | QualType NewQType = Context.getCanonicalType(NewFD->getType()); | |||
10660 | const auto *NewType = cast<FunctionType>(NewQType); | |||
10661 | QualType NewReturnType = NewType->getReturnType(); | |||
10662 | ||||
10663 | if (NewReturnType->isUndeducedType()) | |||
10664 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | |||
10665 | << DeducedReturn; | |||
10666 | ||||
10667 | // Ensure the return type is identical. | |||
10668 | if (OldFD) { | |||
10669 | QualType OldQType = Context.getCanonicalType(OldFD->getType()); | |||
10670 | const auto *OldType = cast<FunctionType>(OldQType); | |||
10671 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | |||
10672 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | |||
10673 | ||||
10674 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) | |||
10675 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; | |||
10676 | ||||
10677 | QualType OldReturnType = OldType->getReturnType(); | |||
10678 | ||||
10679 | if (OldReturnType != NewReturnType) | |||
10680 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; | |||
10681 | ||||
10682 | if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) | |||
10683 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; | |||
10684 | ||||
10685 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) | |||
10686 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; | |||
10687 | ||||
10688 | if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage()) | |||
10689 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; | |||
10690 | ||||
10691 | if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) | |||
10692 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage; | |||
10693 | ||||
10694 | if (CheckEquivalentExceptionSpec( | |||
10695 | OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), | |||
10696 | NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) | |||
10697 | return true; | |||
10698 | } | |||
10699 | return false; | |||
10700 | } | |||
10701 | ||||
10702 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, | |||
10703 | const FunctionDecl *NewFD, | |||
10704 | bool CausesMV, | |||
10705 | MultiVersionKind MVKind) { | |||
10706 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | |||
10707 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | |||
10708 | if (OldFD) | |||
10709 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
10710 | return true; | |||
10711 | } | |||
10712 | ||||
10713 | bool IsCPUSpecificCPUDispatchMVKind = | |||
10714 | MVKind == MultiVersionKind::CPUDispatch || | |||
10715 | MVKind == MultiVersionKind::CPUSpecific; | |||
10716 | ||||
10717 | if (CausesMV && OldFD && | |||
10718 | checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind)) | |||
10719 | return true; | |||
10720 | ||||
10721 | if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind)) | |||
10722 | return true; | |||
10723 | ||||
10724 | // Only allow transition to MultiVersion if it hasn't been used. | |||
10725 | if (OldFD && CausesMV && OldFD->isUsed(false)) | |||
10726 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); | |||
10727 | ||||
10728 | return S.areMultiversionVariantFunctionsCompatible( | |||
10729 | OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), | |||
10730 | PartialDiagnosticAt(NewFD->getLocation(), | |||
10731 | S.PDiag(diag::note_multiversioning_caused_here)), | |||
10732 | PartialDiagnosticAt(NewFD->getLocation(), | |||
10733 | S.PDiag(diag::err_multiversion_doesnt_support) | |||
10734 | << static_cast<unsigned>(MVKind)), | |||
10735 | PartialDiagnosticAt(NewFD->getLocation(), | |||
10736 | S.PDiag(diag::err_multiversion_diff)), | |||
10737 | /*TemplatesSupported=*/false, | |||
10738 | /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind, | |||
10739 | /*CLinkageMayDiffer=*/false); | |||
10740 | } | |||
10741 | ||||
10742 | /// Check the validity of a multiversion function declaration that is the | |||
10743 | /// first of its kind. Also sets the multiversion'ness' of the function itself. | |||
10744 | /// | |||
10745 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
10746 | /// | |||
10747 | /// Returns true if there was an error, false otherwise. | |||
10748 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, | |||
10749 | MultiVersionKind MVKind, | |||
10750 | const TargetAttr *TA) { | |||
10751 | assert(MVKind != MultiVersionKind::None &&(static_cast <bool> (MVKind != MultiVersionKind::None && "Function lacks multiversion attribute") ? void (0) : __assert_fail ("MVKind != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "clang/lib/Sema/SemaDecl.cpp", 10752, __extension__ __PRETTY_FUNCTION__ )) | |||
10752 | "Function lacks multiversion attribute")(static_cast <bool> (MVKind != MultiVersionKind::None && "Function lacks multiversion attribute") ? void (0) : __assert_fail ("MVKind != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "clang/lib/Sema/SemaDecl.cpp", 10752, __extension__ __PRETTY_FUNCTION__ )); | |||
10753 | ||||
10754 | // Target only causes MV if it is default, otherwise this is a normal | |||
10755 | // function. | |||
10756 | if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion()) | |||
10757 | return false; | |||
10758 | ||||
10759 | if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { | |||
10760 | FD->setInvalidDecl(); | |||
10761 | return true; | |||
10762 | } | |||
10763 | ||||
10764 | if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) { | |||
10765 | FD->setInvalidDecl(); | |||
10766 | return true; | |||
10767 | } | |||
10768 | ||||
10769 | FD->setIsMultiVersion(); | |||
10770 | return false; | |||
10771 | } | |||
10772 | ||||
10773 | static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { | |||
10774 | for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { | |||
10775 | if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) | |||
10776 | return true; | |||
10777 | } | |||
10778 | ||||
10779 | return false; | |||
10780 | } | |||
10781 | ||||
10782 | static bool CheckTargetCausesMultiVersioning( | |||
10783 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, | |||
10784 | bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) { | |||
10785 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); | |||
10786 | ParsedTargetAttr NewParsed = NewTA->parse(); | |||
10787 | // Sort order doesn't matter, it just needs to be consistent. | |||
10788 | llvm::sort(NewParsed.Features); | |||
10789 | ||||
10790 | // If the old decl is NOT MultiVersioned yet, and we don't cause that | |||
10791 | // to change, this is a simple redeclaration. | |||
10792 | if (!NewTA->isDefaultVersion() && | |||
10793 | (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) | |||
10794 | return false; | |||
10795 | ||||
10796 | // Otherwise, this decl causes MultiVersioning. | |||
10797 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, | |||
10798 | MultiVersionKind::Target)) { | |||
10799 | NewFD->setInvalidDecl(); | |||
10800 | return true; | |||
10801 | } | |||
10802 | ||||
10803 | if (CheckMultiVersionValue(S, NewFD)) { | |||
10804 | NewFD->setInvalidDecl(); | |||
10805 | return true; | |||
10806 | } | |||
10807 | ||||
10808 | // If this is 'default', permit the forward declaration. | |||
10809 | if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { | |||
10810 | Redeclaration = true; | |||
10811 | OldDecl = OldFD; | |||
10812 | OldFD->setIsMultiVersion(); | |||
10813 | NewFD->setIsMultiVersion(); | |||
10814 | return false; | |||
10815 | } | |||
10816 | ||||
10817 | if (CheckMultiVersionValue(S, OldFD)) { | |||
10818 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
10819 | NewFD->setInvalidDecl(); | |||
10820 | return true; | |||
10821 | } | |||
10822 | ||||
10823 | ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); | |||
10824 | ||||
10825 | if (OldParsed == NewParsed) { | |||
10826 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | |||
10827 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
10828 | NewFD->setInvalidDecl(); | |||
10829 | return true; | |||
10830 | } | |||
10831 | ||||
10832 | for (const auto *FD : OldFD->redecls()) { | |||
10833 | const auto *CurTA = FD->getAttr<TargetAttr>(); | |||
10834 | // We allow forward declarations before ANY multiversioning attributes, but | |||
10835 | // nothing after the fact. | |||
10836 | if (PreviousDeclsHaveMultiVersionAttribute(FD) && | |||
10837 | (!CurTA || CurTA->isInherited())) { | |||
10838 | S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) | |||
10839 | << 0; | |||
10840 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | |||
10841 | NewFD->setInvalidDecl(); | |||
10842 | return true; | |||
10843 | } | |||
10844 | } | |||
10845 | ||||
10846 | OldFD->setIsMultiVersion(); | |||
10847 | NewFD->setIsMultiVersion(); | |||
10848 | Redeclaration = false; | |||
10849 | OldDecl = nullptr; | |||
10850 | Previous.clear(); | |||
10851 | return false; | |||
10852 | } | |||
10853 | ||||
10854 | static bool MultiVersionTypesCompatible(MultiVersionKind Old, | |||
10855 | MultiVersionKind New) { | |||
10856 | if (Old == New || Old == MultiVersionKind::None || | |||
10857 | New == MultiVersionKind::None) | |||
10858 | return true; | |||
10859 | ||||
10860 | return (Old == MultiVersionKind::CPUDispatch && | |||
10861 | New == MultiVersionKind::CPUSpecific) || | |||
10862 | (Old == MultiVersionKind::CPUSpecific && | |||
10863 | New == MultiVersionKind::CPUDispatch); | |||
10864 | } | |||
10865 | ||||
10866 | /// Check the validity of a new function declaration being added to an existing | |||
10867 | /// multiversioned declaration collection. | |||
10868 | static bool CheckMultiVersionAdditionalDecl( | |||
10869 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, | |||
10870 | MultiVersionKind NewMVKind, const TargetAttr *NewTA, | |||
10871 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, | |||
10872 | const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, | |||
10873 | LookupResult &Previous) { | |||
10874 | ||||
10875 | MultiVersionKind OldMVKind = OldFD->getMultiVersionKind(); | |||
10876 | // Disallow mixing of multiversioning types. | |||
10877 | if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) { | |||
10878 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | |||
10879 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | |||
10880 | NewFD->setInvalidDecl(); | |||
10881 | return true; | |||
10882 | } | |||
10883 | ||||
10884 | ParsedTargetAttr NewParsed; | |||
10885 | if (NewTA) { | |||
10886 | NewParsed = NewTA->parse(); | |||
10887 | llvm::sort(NewParsed.Features); | |||
10888 | } | |||
10889 | ||||
10890 | bool UseMemberUsingDeclRules = | |||
10891 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); | |||
10892 | ||||
10893 | bool MayNeedOverloadableChecks = | |||
10894 | AllowOverloadingOfFunction(Previous, S.Context, NewFD); | |||
10895 | ||||
10896 | // Next, check ALL non-overloads to see if this is a redeclaration of a | |||
10897 | // previous member of the MultiVersion set. | |||
10898 | for (NamedDecl *ND : Previous) { | |||
10899 | FunctionDecl *CurFD = ND->getAsFunction(); | |||
10900 | if (!CurFD) | |||
10901 | continue; | |||
10902 | if (MayNeedOverloadableChecks && | |||
10903 | S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) | |||
10904 | continue; | |||
10905 | ||||
10906 | switch (NewMVKind) { | |||
10907 | case MultiVersionKind::None: | |||
10908 | assert(OldMVKind == MultiVersionKind::TargetClones &&(static_cast <bool> (OldMVKind == MultiVersionKind::TargetClones && "Only target_clones can be omitted in subsequent declarations" ) ? void (0) : __assert_fail ("OldMVKind == MultiVersionKind::TargetClones && \"Only target_clones can be omitted in subsequent declarations\"" , "clang/lib/Sema/SemaDecl.cpp", 10909, __extension__ __PRETTY_FUNCTION__ )) | |||
10909 | "Only target_clones can be omitted in subsequent declarations")(static_cast <bool> (OldMVKind == MultiVersionKind::TargetClones && "Only target_clones can be omitted in subsequent declarations" ) ? void (0) : __assert_fail ("OldMVKind == MultiVersionKind::TargetClones && \"Only target_clones can be omitted in subsequent declarations\"" , "clang/lib/Sema/SemaDecl.cpp", 10909, __extension__ __PRETTY_FUNCTION__ )); | |||
10910 | break; | |||
10911 | case MultiVersionKind::Target: { | |||
10912 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); | |||
10913 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { | |||
10914 | NewFD->setIsMultiVersion(); | |||
10915 | Redeclaration = true; | |||
10916 | OldDecl = ND; | |||
10917 | return false; | |||
10918 | } | |||
10919 | ||||
10920 | ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); | |||
10921 | if (CurParsed == NewParsed) { | |||
10922 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | |||
10923 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
10924 | NewFD->setInvalidDecl(); | |||
10925 | return true; | |||
10926 | } | |||
10927 | break; | |||
10928 | } | |||
10929 | case MultiVersionKind::TargetClones: { | |||
10930 | const auto *CurClones = CurFD->getAttr<TargetClonesAttr>(); | |||
10931 | Redeclaration = true; | |||
10932 | OldDecl = CurFD; | |||
10933 | NewFD->setIsMultiVersion(); | |||
10934 | ||||
10935 | if (CurClones && NewClones && | |||
10936 | (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() || | |||
10937 | !std::equal(CurClones->featuresStrs_begin(), | |||
10938 | CurClones->featuresStrs_end(), | |||
10939 | NewClones->featuresStrs_begin()))) { | |||
10940 | S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match); | |||
10941 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
10942 | NewFD->setInvalidDecl(); | |||
10943 | return true; | |||
10944 | } | |||
10945 | ||||
10946 | return false; | |||
10947 | } | |||
10948 | case MultiVersionKind::CPUSpecific: | |||
10949 | case MultiVersionKind::CPUDispatch: { | |||
10950 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); | |||
10951 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); | |||
10952 | // Handle CPUDispatch/CPUSpecific versions. | |||
10953 | // Only 1 CPUDispatch function is allowed, this will make it go through | |||
10954 | // the redeclaration errors. | |||
10955 | if (NewMVKind == MultiVersionKind::CPUDispatch && | |||
10956 | CurFD->hasAttr<CPUDispatchAttr>()) { | |||
10957 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && | |||
10958 | std::equal( | |||
10959 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), | |||
10960 | NewCPUDisp->cpus_begin(), | |||
10961 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | |||
10962 | return Cur->getName() == New->getName(); | |||
10963 | })) { | |||
10964 | NewFD->setIsMultiVersion(); | |||
10965 | Redeclaration = true; | |||
10966 | OldDecl = ND; | |||
10967 | return false; | |||
10968 | } | |||
10969 | ||||
10970 | // If the declarations don't match, this is an error condition. | |||
10971 | S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); | |||
10972 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
10973 | NewFD->setInvalidDecl(); | |||
10974 | return true; | |||
10975 | } | |||
10976 | if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) { | |||
10977 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && | |||
10978 | std::equal( | |||
10979 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), | |||
10980 | NewCPUSpec->cpus_begin(), | |||
10981 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | |||
10982 | return Cur->getName() == New->getName(); | |||
10983 | })) { | |||
10984 | NewFD->setIsMultiVersion(); | |||
10985 | Redeclaration = true; | |||
10986 | OldDecl = ND; | |||
10987 | return false; | |||
10988 | } | |||
10989 | ||||
10990 | // Only 1 version of CPUSpecific is allowed for each CPU. | |||
10991 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { | |||
10992 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { | |||
10993 | if (CurII == NewII) { | |||
10994 | S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) | |||
10995 | << NewII; | |||
10996 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | |||
10997 | NewFD->setInvalidDecl(); | |||
10998 | return true; | |||
10999 | } | |||
11000 | } | |||
11001 | } | |||
11002 | } | |||
11003 | break; | |||
11004 | } | |||
11005 | } | |||
11006 | } | |||
11007 | ||||
11008 | // Else, this is simply a non-redecl case. Checking the 'value' is only | |||
11009 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are | |||
11010 | // handled in the attribute adding step. | |||
11011 | if (NewMVKind == MultiVersionKind::Target && | |||
11012 | CheckMultiVersionValue(S, NewFD)) { | |||
11013 | NewFD->setInvalidDecl(); | |||
11014 | return true; | |||
11015 | } | |||
11016 | ||||
11017 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, | |||
11018 | !OldFD->isMultiVersion(), NewMVKind)) { | |||
11019 | NewFD->setInvalidDecl(); | |||
11020 | return true; | |||
11021 | } | |||
11022 | ||||
11023 | // Permit forward declarations in the case where these two are compatible. | |||
11024 | if (!OldFD->isMultiVersion()) { | |||
11025 | OldFD->setIsMultiVersion(); | |||
11026 | NewFD->setIsMultiVersion(); | |||
11027 | Redeclaration = true; | |||
11028 | OldDecl = OldFD; | |||
11029 | return false; | |||
11030 | } | |||
11031 | ||||
11032 | NewFD->setIsMultiVersion(); | |||
11033 | Redeclaration = false; | |||
11034 | OldDecl = nullptr; | |||
11035 | Previous.clear(); | |||
11036 | return false; | |||
11037 | } | |||
11038 | ||||
11039 | /// Check the validity of a mulitversion function declaration. | |||
11040 | /// Also sets the multiversion'ness' of the function itself. | |||
11041 | /// | |||
11042 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
11043 | /// | |||
11044 | /// Returns true if there was an error, false otherwise. | |||
11045 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, | |||
11046 | bool &Redeclaration, NamedDecl *&OldDecl, | |||
11047 | LookupResult &Previous) { | |||
11048 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); | |||
11049 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); | |||
11050 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); | |||
11051 | const auto *NewClones = NewFD->getAttr<TargetClonesAttr>(); | |||
11052 | MultiVersionKind MVKind = NewFD->getMultiVersionKind(); | |||
11053 | ||||
11054 | // Main isn't allowed to become a multiversion function, however it IS | |||
11055 | // permitted to have 'main' be marked with the 'target' optimization hint. | |||
11056 | if (NewFD->isMain()) { | |||
11057 | if (MVKind != MultiVersionKind::None && | |||
11058 | !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) { | |||
11059 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); | |||
11060 | NewFD->setInvalidDecl(); | |||
11061 | return true; | |||
11062 | } | |||
11063 | return false; | |||
11064 | } | |||
11065 | ||||
11066 | if (!OldDecl || !OldDecl->getAsFunction() || | |||
11067 | OldDecl->getDeclContext()->getRedeclContext() != | |||
11068 | NewFD->getDeclContext()->getRedeclContext()) { | |||
11069 | // If there's no previous declaration, AND this isn't attempting to cause | |||
11070 | // multiversioning, this isn't an error condition. | |||
11071 | if (MVKind == MultiVersionKind::None) | |||
11072 | return false; | |||
11073 | return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA); | |||
11074 | } | |||
11075 | ||||
11076 | FunctionDecl *OldFD = OldDecl->getAsFunction(); | |||
11077 | ||||
11078 | if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None) | |||
11079 | return false; | |||
11080 | ||||
11081 | // Multiversioned redeclarations aren't allowed to omit the attribute, except | |||
11082 | // for target_clones. | |||
11083 | if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None && | |||
11084 | OldFD->getMultiVersionKind() != MultiVersionKind::TargetClones) { | |||
11085 | S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) | |||
11086 | << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); | |||
11087 | NewFD->setInvalidDecl(); | |||
11088 | return true; | |||
11089 | } | |||
11090 | ||||
11091 | if (!OldFD->isMultiVersion()) { | |||
11092 | switch (MVKind) { | |||
11093 | case MultiVersionKind::Target: | |||
11094 | return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, | |||
11095 | Redeclaration, OldDecl, Previous); | |||
11096 | case MultiVersionKind::TargetClones: | |||
11097 | if (OldFD->isUsed(false)) { | |||
11098 | NewFD->setInvalidDecl(); | |||
11099 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); | |||
11100 | } | |||
11101 | OldFD->setIsMultiVersion(); | |||
11102 | break; | |||
11103 | case MultiVersionKind::CPUDispatch: | |||
11104 | case MultiVersionKind::CPUSpecific: | |||
11105 | case MultiVersionKind::None: | |||
11106 | break; | |||
11107 | } | |||
11108 | } | |||
11109 | ||||
11110 | // At this point, we have a multiversion function decl (in OldFD) AND an | |||
11111 | // appropriate attribute in the current function decl. Resolve that these are | |||
11112 | // still compatible with previous declarations. | |||
11113 | return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA, | |||
11114 | NewCPUDisp, NewCPUSpec, NewClones, | |||
11115 | Redeclaration, OldDecl, Previous); | |||
11116 | } | |||
11117 | ||||
11118 | /// Perform semantic checking of a new function declaration. | |||
11119 | /// | |||
11120 | /// Performs semantic analysis of the new function declaration | |||
11121 | /// NewFD. This routine performs all semantic checking that does not | |||
11122 | /// require the actual declarator involved in the declaration, and is | |||
11123 | /// used both for the declaration of functions as they are parsed | |||
11124 | /// (called via ActOnDeclarator) and for the declaration of functions | |||
11125 | /// that have been instantiated via C++ template instantiation (called | |||
11126 | /// via InstantiateDecl). | |||
11127 | /// | |||
11128 | /// \param IsMemberSpecialization whether this new function declaration is | |||
11129 | /// a member specialization (that replaces any definition provided by the | |||
11130 | /// previous declaration). | |||
11131 | /// | |||
11132 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | |||
11133 | /// | |||
11134 | /// \returns true if the function declaration is a redeclaration. | |||
11135 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, | |||
11136 | LookupResult &Previous, | |||
11137 | bool IsMemberSpecialization, | |||
11138 | bool DeclIsDefn) { | |||
11139 | assert(!NewFD->getReturnType()->isVariablyModifiedType() &&(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType () && "Variably modified return types are not handled here" ) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "clang/lib/Sema/SemaDecl.cpp", 11140, __extension__ __PRETTY_FUNCTION__ )) | |||
11140 | "Variably modified return types are not handled here")(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType () && "Variably modified return types are not handled here" ) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "clang/lib/Sema/SemaDecl.cpp", 11140, __extension__ __PRETTY_FUNCTION__ )); | |||
11141 | ||||
11142 | // Determine whether the type of this function should be merged with | |||
11143 | // a previous visible declaration. This never happens for functions in C++, | |||
11144 | // and always happens in C if the previous declaration was visible. | |||
11145 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && | |||
11146 | !Previous.isShadowed(); | |||
11147 | ||||
11148 | bool Redeclaration = false; | |||
11149 | NamedDecl *OldDecl = nullptr; | |||
11150 | bool MayNeedOverloadableChecks = false; | |||
11151 | ||||
11152 | // Merge or overload the declaration with an existing declaration of | |||
11153 | // the same name, if appropriate. | |||
11154 | if (!Previous.empty()) { | |||
11155 | // Determine whether NewFD is an overload of PrevDecl or | |||
11156 | // a declaration that requires merging. If it's an overload, | |||
11157 | // there's no more work to do here; we'll just add the new | |||
11158 | // function to the scope. | |||
11159 | if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { | |||
11160 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); | |||
11161 | if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { | |||
11162 | Redeclaration = true; | |||
11163 | OldDecl = Candidate; | |||
11164 | } | |||
11165 | } else { | |||
11166 | MayNeedOverloadableChecks = true; | |||
11167 | switch (CheckOverload(S, NewFD, Previous, OldDecl, | |||
11168 | /*NewIsUsingDecl*/ false)) { | |||
11169 | case Ovl_Match: | |||
11170 | Redeclaration = true; | |||
11171 | break; | |||
11172 | ||||
11173 | case Ovl_NonFunction: | |||
11174 | Redeclaration = true; | |||
11175 | break; | |||
11176 | ||||
11177 | case Ovl_Overload: | |||
11178 | Redeclaration = false; | |||
11179 | break; | |||
11180 | } | |||
11181 | } | |||
11182 | } | |||
11183 | ||||
11184 | // Check for a previous extern "C" declaration with this name. | |||
11185 | if (!Redeclaration && | |||
11186 | checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { | |||
11187 | if (!Previous.empty()) { | |||
11188 | // This is an extern "C" declaration with the same name as a previous | |||
11189 | // declaration, and thus redeclares that entity... | |||
11190 | Redeclaration = true; | |||
11191 | OldDecl = Previous.getFoundDecl(); | |||
11192 | MergeTypeWithPrevious = false; | |||
11193 | ||||
11194 | // ... except in the presence of __attribute__((overloadable)). | |||
11195 | if (OldDecl->hasAttr<OverloadableAttr>() || | |||
11196 | NewFD->hasAttr<OverloadableAttr>()) { | |||
11197 | if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { | |||
11198 | MayNeedOverloadableChecks = true; | |||
11199 | Redeclaration = false; | |||
11200 | OldDecl = nullptr; | |||
11201 | } | |||
11202 | } | |||
11203 | } | |||
11204 | } | |||
11205 | ||||
11206 | if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous)) | |||
11207 | return Redeclaration; | |||
11208 | ||||
11209 | // PPC MMA non-pointer types are not allowed as function return types. | |||
11210 | if (Context.getTargetInfo().getTriple().isPPC64() && | |||
11211 | CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) { | |||
11212 | NewFD->setInvalidDecl(); | |||
11213 | } | |||
11214 | ||||
11215 | // C++11 [dcl.constexpr]p8: | |||
11216 | // A constexpr specifier for a non-static member function that is not | |||
11217 | // a constructor declares that member function to be const. | |||
11218 | // | |||
11219 | // This needs to be delayed until we know whether this is an out-of-line | |||
11220 | // definition of a static member function. | |||
11221 | // | |||
11222 | // This rule is not present in C++1y, so we produce a backwards | |||
11223 | // compatibility warning whenever it happens in C++11. | |||
11224 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | |||
11225 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && | |||
11226 | !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && | |||
11227 | !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { | |||
11228 | CXXMethodDecl *OldMD = nullptr; | |||
11229 | if (OldDecl) | |||
11230 | OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); | |||
11231 | if (!OldMD || !OldMD->isStatic()) { | |||
11232 | const FunctionProtoType *FPT = | |||
11233 | MD->getType()->castAs<FunctionProtoType>(); | |||
11234 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | |||
11235 | EPI.TypeQuals.addConst(); | |||
11236 | MD->setType(Context.getFunctionType(FPT->getReturnType(), | |||
11237 | FPT->getParamTypes(), EPI)); | |||
11238 | ||||
11239 | // Warn that we did this, if we're not performing template instantiation. | |||
11240 | // In that case, we'll have warned already when the template was defined. | |||
11241 | if (!inTemplateInstantiation()) { | |||
11242 | SourceLocation AddConstLoc; | |||
11243 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() | |||
11244 | .IgnoreParens().getAs<FunctionTypeLoc>()) | |||
11245 | AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); | |||
11246 | ||||
11247 | Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) | |||
11248 | << FixItHint::CreateInsertion(AddConstLoc, " const"); | |||
11249 | } | |||
11250 | } | |||
11251 | } | |||
11252 | ||||
11253 | if (Redeclaration) { | |||
11254 | // NewFD and OldDecl represent declarations that need to be | |||
11255 | // merged. | |||
11256 | if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious, | |||
11257 | DeclIsDefn)) { | |||
11258 | NewFD->setInvalidDecl(); | |||
11259 | return Redeclaration; | |||
11260 | } | |||
11261 | ||||
11262 | Previous.clear(); | |||
11263 | Previous.addDecl(OldDecl); | |||
11264 | ||||
11265 | if (FunctionTemplateDecl *OldTemplateDecl = | |||
11266 | dyn_cast<FunctionTemplateDecl>(OldDecl)) { | |||
11267 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); | |||
11268 | FunctionTemplateDecl *NewTemplateDecl | |||
11269 | = NewFD->getDescribedFunctionTemplate(); | |||
11270 | assert(NewTemplateDecl && "Template/non-template mismatch")(static_cast <bool> (NewTemplateDecl && "Template/non-template mismatch" ) ? void (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\"" , "clang/lib/Sema/SemaDecl.cpp", 11270, __extension__ __PRETTY_FUNCTION__ )); | |||
11271 | ||||
11272 | // The call to MergeFunctionDecl above may have created some state in | |||
11273 | // NewTemplateDecl that needs to be merged with OldTemplateDecl before we | |||
11274 | // can add it as a redeclaration. | |||
11275 | NewTemplateDecl->mergePrevDecl(OldTemplateDecl); | |||
11276 | ||||
11277 | NewFD->setPreviousDeclaration(OldFD); | |||
11278 | if (NewFD->isCXXClassMember()) { | |||
11279 | NewFD->setAccess(OldTemplateDecl->getAccess()); | |||
11280 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); | |||
11281 | } | |||
11282 | ||||
11283 | // If this is an explicit specialization of a member that is a function | |||
11284 | // template, mark it as a member specialization. | |||
11285 | if (IsMemberSpecialization && | |||
11286 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { | |||
11287 | NewTemplateDecl->setMemberSpecialization(); | |||
11288 | assert(OldTemplateDecl->isMemberSpecialization())(static_cast <bool> (OldTemplateDecl->isMemberSpecialization ()) ? void (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()" , "clang/lib/Sema/SemaDecl.cpp", 11288, __extension__ __PRETTY_FUNCTION__ )); | |||
11289 | // Explicit specializations of a member template do not inherit deleted | |||
11290 | // status from the parent member template that they are specializing. | |||
11291 | if (OldFD->isDeleted()) { | |||
11292 | // FIXME: This assert will not hold in the presence of modules. | |||
11293 | assert(OldFD->getCanonicalDecl() == OldFD)(static_cast <bool> (OldFD->getCanonicalDecl() == OldFD ) ? void (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD" , "clang/lib/Sema/SemaDecl.cpp", 11293, __extension__ __PRETTY_FUNCTION__ )); | |||
11294 | // FIXME: We need an update record for this AST mutation. | |||
11295 | OldFD->setDeletedAsWritten(false); | |||
11296 | } | |||
11297 | } | |||
11298 | ||||
11299 | } else { | |||
11300 | if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { | |||
11301 | auto *OldFD = cast<FunctionDecl>(OldDecl); | |||
11302 | // This needs to happen first so that 'inline' propagates. | |||
11303 | NewFD->setPreviousDeclaration(OldFD); | |||
11304 | if (NewFD->isCXXClassMember()) | |||
11305 | NewFD->setAccess(OldFD->getAccess()); | |||
11306 | } | |||
11307 | } | |||
11308 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && | |||
11309 | !NewFD->getAttr<OverloadableAttr>()) { | |||
11310 | assert((Previous.empty() ||(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? 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\"" , "clang/lib/Sema/SemaDecl.cpp", 11315, __extension__ __PRETTY_FUNCTION__ )) | |||
11311 | llvm::any_of(Previous,(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? 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\"" , "clang/lib/Sema/SemaDecl.cpp", 11315, __extension__ __PRETTY_FUNCTION__ )) | |||
11312 | [](const NamedDecl *ND) {(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? 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\"" , "clang/lib/Sema/SemaDecl.cpp", 11315, __extension__ __PRETTY_FUNCTION__ )) | |||
11313 | return ND->hasAttr<OverloadableAttr>();(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? 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\"" , "clang/lib/Sema/SemaDecl.cpp", 11315, __extension__ __PRETTY_FUNCTION__ )) | |||
11314 | })) &&(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? 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\"" , "clang/lib/Sema/SemaDecl.cpp", 11315, __extension__ __PRETTY_FUNCTION__ )) | |||
11315 | "Non-redecls shouldn't happen without overloadable present")(static_cast <bool> ((Previous.empty() || llvm::any_of( Previous, [](const NamedDecl *ND) { return ND->hasAttr< OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present" ) ? 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\"" , "clang/lib/Sema/SemaDecl.cpp", 11315, __extension__ __PRETTY_FUNCTION__ )); | |||
11316 | ||||
11317 | auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { | |||
11318 | const auto *FD = dyn_cast<FunctionDecl>(ND); | |||
11319 | return FD && !FD->hasAttr<OverloadableAttr>(); | |||
11320 | }); | |||
11321 | ||||
11322 | if (OtherUnmarkedIter != Previous.end()) { | |||
11323 | Diag(NewFD->getLocation(), | |||
11324 | diag::err_attribute_overloadable_multiple_unmarked_overloads); | |||
11325 | Diag((*OtherUnmarkedIter)->getLocation(), | |||
11326 | diag::note_attribute_overloadable_prev_overload) | |||
11327 | << false; | |||
11328 | ||||
11329 | NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); | |||
11330 | } | |||
11331 | } | |||
11332 | ||||
11333 | if (LangOpts.OpenMP) | |||
11334 | ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD); | |||
11335 | ||||
11336 | // Semantic checking for this function declaration (in isolation). | |||
11337 | ||||
11338 | if (getLangOpts().CPlusPlus) { | |||
11339 | // C++-specific checks. | |||
11340 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { | |||
11341 | CheckConstructor(Constructor); | |||
11342 | } else if (CXXDestructorDecl *Destructor = | |||
11343 | dyn_cast<CXXDestructorDecl>(NewFD)) { | |||
11344 | CXXRecordDecl *Record = Destructor->getParent(); | |||
11345 | QualType ClassType = Context.getTypeDeclType(Record); | |||
11346 | ||||
11347 | // FIXME: Shouldn't we be able to perform this check even when the class | |||
11348 | // type is dependent? Both gcc and edg can handle that. | |||
11349 | if (!ClassType->isDependentType()) { | |||
11350 | DeclarationName Name | |||
11351 | = Context.DeclarationNames.getCXXDestructorName( | |||
11352 | Context.getCanonicalType(ClassType)); | |||
11353 | if (NewFD->getDeclName() != Name) { | |||
11354 | Diag(NewFD->getLocation(), diag::err_destructor_name); | |||
11355 | NewFD->setInvalidDecl(); | |||
11356 | return Redeclaration; | |||
11357 | } | |||
11358 | } | |||
11359 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { | |||
11360 | if (auto *TD = Guide->getDescribedFunctionTemplate()) | |||
11361 | CheckDeductionGuideTemplate(TD); | |||
11362 | ||||
11363 | // A deduction guide is not on the list of entities that can be | |||
11364 | // explicitly specialized. | |||
11365 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) | |||
11366 | Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) | |||
11367 | << /*explicit specialization*/ 1; | |||
11368 | } | |||
11369 | ||||
11370 | // Find any virtual functions that this function overrides. | |||
11371 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { | |||
11372 | if (!Method->isFunctionTemplateSpecialization() && | |||
11373 | !Method->getDescribedFunctionTemplate() && | |||
11374 | Method->isCanonicalDecl()) { | |||
11375 | AddOverriddenMethods(Method->getParent(), Method); | |||
11376 | } | |||
11377 | if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) | |||
11378 | // C++2a [class.virtual]p6 | |||
11379 | // A virtual method shall not have a requires-clause. | |||
11380 | Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), | |||
11381 | diag::err_constrained_virtual_method); | |||
11382 | ||||
11383 | if (Method->isStatic()) | |||
11384 | checkThisInStaticMemberFunctionType(Method); | |||
11385 | } | |||
11386 | ||||
11387 | if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) | |||
11388 | ActOnConversionDeclarator(Conversion); | |||
11389 | ||||
11390 | // Extra checking for C++ overloaded operators (C++ [over.oper]). | |||
11391 | if (NewFD->isOverloadedOperator() && | |||
11392 | CheckOverloadedOperatorDeclaration(NewFD)) { | |||
11393 | NewFD->setInvalidDecl(); | |||
11394 | return Redeclaration; | |||
11395 | } | |||
11396 | ||||
11397 | // Extra checking for C++0x literal operators (C++0x [over.literal]). | |||
11398 | if (NewFD->getLiteralIdentifier() && | |||
11399 | CheckLiteralOperatorDeclaration(NewFD)) { | |||
11400 | NewFD->setInvalidDecl(); | |||
11401 | return Redeclaration; | |||
11402 | } | |||
11403 | ||||
11404 | // In C++, check default arguments now that we have merged decls. Unless | |||
11405 | // the lexical context is the class, because in this case this is done | |||
11406 | // during delayed parsing anyway. | |||
11407 | if (!CurContext->isRecord()) | |||
11408 | CheckCXXDefaultArguments(NewFD); | |||
11409 | ||||
11410 | // If this function is declared as being extern "C", then check to see if | |||
11411 | // the function returns a UDT (class, struct, or union type) that is not C | |||
11412 | // compatible, and if it does, warn the user. | |||
11413 | // But, issue any diagnostic on the first declaration only. | |||
11414 | if (Previous.empty() && NewFD->isExternC()) { | |||
11415 | QualType R = NewFD->getReturnType(); | |||
11416 | if (R->isIncompleteType() && !R->isVoidType()) | |||
11417 | Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) | |||
11418 | << NewFD << R; | |||
11419 | else if (!R.isPODType(Context) && !R->isVoidType() && | |||
11420 | !R->isObjCObjectPointerType()) | |||
11421 | Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; | |||
11422 | } | |||
11423 | ||||
11424 | // C++1z [dcl.fct]p6: | |||
11425 | // [...] whether the function has a non-throwing exception-specification | |||
11426 | // [is] part of the function type | |||
11427 | // | |||
11428 | // This results in an ABI break between C++14 and C++17 for functions whose | |||
11429 | // declared type includes an exception-specification in a parameter or | |||
11430 | // return type. (Exception specifications on the function itself are OK in | |||
11431 | // most cases, and exception specifications are not permitted in most other | |||
11432 | // contexts where they could make it into a mangling.) | |||
11433 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { | |||
11434 | auto HasNoexcept = [&](QualType T) -> bool { | |||
11435 | // Strip off declarator chunks that could be between us and a function | |||
11436 | // type. We don't need to look far, exception specifications are very | |||
11437 | // restricted prior to C++17. | |||
11438 | if (auto *RT = T->getAs<ReferenceType>()) | |||
11439 | T = RT->getPointeeType(); | |||
11440 | else if (T->isAnyPointerType()) | |||
11441 | T = T->getPointeeType(); | |||
11442 | else if (auto *MPT = T->getAs<MemberPointerType>()) | |||
11443 | T = MPT->getPointeeType(); | |||
11444 | if (auto *FPT = T->getAs<FunctionProtoType>()) | |||
11445 | if (FPT->isNothrow()) | |||
11446 | return true; | |||
11447 | return false; | |||
11448 | }; | |||
11449 | ||||
11450 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); | |||
11451 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); | |||
11452 | for (QualType T : FPT->param_types()) | |||
11453 | AnyNoexcept |= HasNoexcept(T); | |||
11454 | if (AnyNoexcept) | |||
11455 | Diag(NewFD->getLocation(), | |||
11456 | diag::warn_cxx17_compat_exception_spec_in_signature) | |||
11457 | << NewFD; | |||
11458 | } | |||
11459 | ||||
11460 | if (!Redeclaration && LangOpts.CUDA) | |||
11461 | checkCUDATargetOverload(NewFD, Previous); | |||
11462 | } | |||
11463 | return Redeclaration; | |||
11464 | } | |||
11465 | ||||
11466 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { | |||
11467 | // C++11 [basic.start.main]p3: | |||
11468 | // A program that [...] declares main to be inline, static or | |||
11469 | // constexpr is ill-formed. | |||
11470 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall | |||
11471 | // appear in a declaration of main. | |||
11472 | // static main is not an error under C99, but we should warn about it. | |||
11473 | // We accept _Noreturn main as an extension. | |||
11474 | if (FD->getStorageClass() == SC_Static) | |||
11475 | Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus | |||
11476 | ? diag::err_static_main : diag::warn_static_main) | |||
11477 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
11478 | if (FD->isInlineSpecified()) | |||
11479 | Diag(DS.getInlineSpecLoc(), diag::err_inline_main) | |||
11480 | << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); | |||
11481 | if (DS.isNoreturnSpecified()) { | |||
11482 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); | |||
11483 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); | |||
11484 | Diag(NoreturnLoc, diag::ext_noreturn_main); | |||
11485 | Diag(NoreturnLoc, diag::note_main_remove_noreturn) | |||
11486 | << FixItHint::CreateRemoval(NoreturnRange); | |||
11487 | } | |||
11488 | if (FD->isConstexpr()) { | |||
11489 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) | |||
11490 | << FD->isConsteval() | |||
11491 | << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); | |||
11492 | FD->setConstexprKind(ConstexprSpecKind::Unspecified); | |||
11493 | } | |||
11494 | ||||
11495 | if (getLangOpts().OpenCL) { | |||
11496 | Diag(FD->getLocation(), diag::err_opencl_no_main) | |||
11497 | << FD->hasAttr<OpenCLKernelAttr>(); | |||
11498 | FD->setInvalidDecl(); | |||
11499 | return; | |||
11500 | } | |||
11501 | ||||
11502 | // Functions named main in hlsl are default entries, but don't have specific | |||
11503 | // signatures they are required to conform to. | |||
11504 | if (getLangOpts().HLSL) | |||
11505 | return; | |||
11506 | ||||
11507 | QualType T = FD->getType(); | |||
11508 | assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "clang/lib/Sema/SemaDecl.cpp", 11508, __extension__ __PRETTY_FUNCTION__ )); | |||
11509 | const FunctionType* FT = T->castAs<FunctionType>(); | |||
11510 | ||||
11511 | // Set default calling convention for main() | |||
11512 | if (FT->getCallConv() != CC_C) { | |||
11513 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); | |||
11514 | FD->setType(QualType(FT, 0)); | |||
11515 | T = Context.getCanonicalType(FD->getType()); | |||
11516 | } | |||
11517 | ||||
11518 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { | |||
11519 | // In C with GNU extensions we allow main() to have non-integer return | |||
11520 | // type, but we should warn about the extension, and we disable the | |||
11521 | // implicit-return-zero rule. | |||
11522 | ||||
11523 | // GCC in C mode accepts qualified 'int'. | |||
11524 | if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) | |||
11525 | FD->setHasImplicitReturnZero(true); | |||
11526 | else { | |||
11527 | Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); | |||
11528 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | |||
11529 | if (RTRange.isValid()) | |||
11530 | Diag(RTRange.getBegin(), diag::note_main_change_return_type) | |||
11531 | << FixItHint::CreateReplacement(RTRange, "int"); | |||
11532 | } | |||
11533 | } else { | |||
11534 | // In C and C++, main magically returns 0 if you fall off the end; | |||
11535 | // set the flag which tells us that. | |||
11536 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. | |||
11537 | ||||
11538 | // All the standards say that main() should return 'int'. | |||
11539 | if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) | |||
11540 | FD->setHasImplicitReturnZero(true); | |||
11541 | else { | |||
11542 | // Otherwise, this is just a flat-out error. | |||
11543 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | |||
11544 | Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) | |||
11545 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") | |||
11546 | : FixItHint()); | |||
11547 | FD->setInvalidDecl(true); | |||
11548 | } | |||
11549 | } | |||
11550 | ||||
11551 | // Treat protoless main() as nullary. | |||
11552 | if (isa<FunctionNoProtoType>(FT)) return; | |||
11553 | ||||
11554 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); | |||
11555 | unsigned nparams = FTP->getNumParams(); | |||
11556 | assert(FD->getNumParams() == nparams)(static_cast <bool> (FD->getNumParams() == nparams) ? void (0) : __assert_fail ("FD->getNumParams() == nparams" , "clang/lib/Sema/SemaDecl.cpp", 11556, __extension__ __PRETTY_FUNCTION__ )); | |||
11557 | ||||
11558 | bool HasExtraParameters = (nparams > 3); | |||
11559 | ||||
11560 | if (FTP->isVariadic()) { | |||
11561 | Diag(FD->getLocation(), diag::ext_variadic_main); | |||
11562 | // FIXME: if we had information about the location of the ellipsis, we | |||
11563 | // could add a FixIt hint to remove it as a parameter. | |||
11564 | } | |||
11565 | ||||
11566 | // Darwin passes an undocumented fourth argument of type char**. If | |||
11567 | // other platforms start sprouting these, the logic below will start | |||
11568 | // getting shifty. | |||
11569 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) | |||
11570 | HasExtraParameters = false; | |||
11571 | ||||
11572 | if (HasExtraParameters) { | |||
11573 | Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; | |||
11574 | FD->setInvalidDecl(true); | |||
11575 | nparams = 3; | |||
11576 | } | |||
11577 | ||||
11578 | // FIXME: a lot of the following diagnostics would be improved | |||
11579 | // if we had some location information about types. | |||
11580 | ||||
11581 | QualType CharPP = | |||
11582 | Context.getPointerType(Context.getPointerType(Context.CharTy)); | |||
11583 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; | |||
11584 | ||||
11585 | for (unsigned i = 0; i < nparams; ++i) { | |||
11586 | QualType AT = FTP->getParamType(i); | |||
11587 | ||||
11588 | bool mismatch = true; | |||
11589 | ||||
11590 | if (Context.hasSameUnqualifiedType(AT, Expected[i])) | |||
11591 | mismatch = false; | |||
11592 | else if (Expected[i] == CharPP) { | |||
11593 | // As an extension, the following forms are okay: | |||
11594 | // char const ** | |||
11595 | // char const * const * | |||
11596 | // char * const * | |||
11597 | ||||
11598 | QualifierCollector qs; | |||
11599 | const PointerType* PT; | |||
11600 | if ((PT = qs.strip(AT)->getAs<PointerType>()) && | |||
11601 | (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && | |||
11602 | Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), | |||
11603 | Context.CharTy)) { | |||
11604 | qs.removeConst(); | |||
11605 | mismatch = !qs.empty(); | |||
11606 | } | |||
11607 | } | |||
11608 | ||||
11609 | if (mismatch) { | |||
11610 | Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; | |||
11611 | // TODO: suggest replacing given type with expected type | |||
11612 | FD->setInvalidDecl(true); | |||
11613 | } | |||
11614 | } | |||
11615 | ||||
11616 | if (nparams == 1 && !FD->isInvalidDecl()) { | |||
11617 | Diag(FD->getLocation(), diag::warn_main_one_arg); | |||
11618 | } | |||
11619 | ||||
11620 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | |||
11621 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | |||
11622 | FD->setInvalidDecl(); | |||
11623 | } | |||
11624 | } | |||
11625 | ||||
11626 | static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) { | |||
11627 | ||||
11628 | // Default calling convention for main and wmain is __cdecl | |||
11629 | if (FD->getName() == "main" || FD->getName() == "wmain") | |||
11630 | return false; | |||
11631 | ||||
11632 | // Default calling convention for MinGW is __cdecl | |||
11633 | const llvm::Triple &T = S.Context.getTargetInfo().getTriple(); | |||
11634 | if (T.isWindowsGNUEnvironment()) | |||
11635 | return false; | |||
11636 | ||||
11637 | // Default calling convention for WinMain, wWinMain and DllMain | |||
11638 | // is __stdcall on 32 bit Windows | |||
11639 | if (T.isOSWindows() && T.getArch() == llvm::Triple::x86) | |||
11640 | return true; | |||
11641 | ||||
11642 | return false; | |||
11643 | } | |||
11644 | ||||
11645 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { | |||
11646 | QualType T = FD->getType(); | |||
11647 | assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type" ) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "clang/lib/Sema/SemaDecl.cpp", 11647, __extension__ __PRETTY_FUNCTION__ )); | |||
11648 | const FunctionType *FT = T->castAs<FunctionType>(); | |||
11649 | ||||
11650 | // Set an implicit return of 'zero' if the function can return some integral, | |||
11651 | // enumeration, pointer or nullptr type. | |||
11652 | if (FT->getReturnType()->isIntegralOrEnumerationType() || | |||
11653 | FT->getReturnType()->isAnyPointerType() || | |||
11654 | FT->getReturnType()->isNullPtrType()) | |||
11655 | // DllMain is exempt because a return value of zero means it failed. | |||
11656 | if (FD->getName() != "DllMain") | |||
11657 | FD->setHasImplicitReturnZero(true); | |||
11658 | ||||
11659 | // Explicity specified calling conventions are applied to MSVC entry points | |||
11660 | if (!hasExplicitCallingConv(T)) { | |||
11661 | if (isDefaultStdCall(FD, *this)) { | |||
11662 | if (FT->getCallConv() != CC_X86StdCall) { | |||
11663 | FT = Context.adjustFunctionType( | |||
11664 | FT, FT->getExtInfo().withCallingConv(CC_X86StdCall)); | |||
11665 | FD->setType(QualType(FT, 0)); | |||
11666 | } | |||
11667 | } else if (FT->getCallConv() != CC_C) { | |||
11668 | FT = Context.adjustFunctionType(FT, | |||
11669 | FT->getExtInfo().withCallingConv(CC_C)); | |||
11670 | FD->setType(QualType(FT, 0)); | |||
11671 | } | |||
11672 | } | |||
11673 | ||||
11674 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | |||
11675 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | |||
11676 | FD->setInvalidDecl(); | |||
11677 | } | |||
11678 | } | |||
11679 | ||||
11680 | bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { | |||
11681 | // FIXME: Need strict checking. In C89, we need to check for | |||
11682 | // any assignment, increment, decrement, function-calls, or | |||
11683 | // commas outside of a sizeof. In C99, it's the same list, | |||
11684 | // except that the aforementioned are allowed in unevaluated | |||
11685 | // expressions. Everything else falls under the | |||
11686 | // "may accept other forms of constant expressions" exception. | |||
11687 | // | |||
11688 | // Regular C++ code will not end up here (exceptions: language extensions, | |||
11689 | // OpenCL C++ etc), so the constant expression rules there don't matter. | |||
11690 | if (Init->isValueDependent()) { | |||
11691 | assert(Init->containsErrors() &&(static_cast <bool> (Init->containsErrors() && "Dependent code should only occur in error-recovery path.") ? void (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaDecl.cpp", 11692, __extension__ __PRETTY_FUNCTION__ )) | |||
11692 | "Dependent code should only occur in error-recovery path.")(static_cast <bool> (Init->containsErrors() && "Dependent code should only occur in error-recovery path.") ? void (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\"" , "clang/lib/Sema/SemaDecl.cpp", 11692, __extension__ __PRETTY_FUNCTION__ )); | |||
11693 | return true; | |||
11694 | } | |||
11695 | const Expr *Culprit; | |||
11696 | if (Init->isConstantInitializer(Context, false, &Culprit)) | |||
11697 | return false; | |||
11698 | Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) | |||
11699 | << Culprit->getSourceRange(); | |||
11700 | return true; | |||
11701 | } | |||
11702 | ||||
11703 | namespace { | |||
11704 | // Visits an initialization expression to see if OrigDecl is evaluated in | |||
11705 | // its own initialization and throws a warning if it does. | |||
11706 | class SelfReferenceChecker | |||
11707 | : public EvaluatedExprVisitor<SelfReferenceChecker> { | |||
11708 | Sema &S; | |||
11709 | Decl *OrigDecl; | |||
11710 | bool isRecordType; | |||
11711 | bool isPODType; | |||
11712 | bool isReferenceType; | |||
11713 | ||||
11714 | bool isInitList; | |||
11715 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | |||
11716 | ||||
11717 | public: | |||
11718 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; | |||
11719 | ||||
11720 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), | |||
11721 | S(S), OrigDecl(OrigDecl) { | |||
11722 | isPODType = false; | |||
11723 | isRecordType = false; | |||
11724 | isReferenceType = false; | |||
11725 | isInitList = false; | |||
11726 | if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { | |||
11727 | isPODType = VD->getType().isPODType(S.Context); | |||
11728 | isRecordType = VD->getType()->isRecordType(); | |||
11729 | isReferenceType = VD->getType()->isReferenceType(); | |||
11730 | } | |||
11731 | } | |||
11732 | ||||
11733 | // For most expressions, just call the visitor. For initializer lists, | |||
11734 | // track the index of the field being initialized since fields are | |||
11735 | // initialized in order allowing use of previously initialized fields. | |||
11736 | void CheckExpr(Expr *E) { | |||
11737 | InitListExpr *InitList = dyn_cast<InitListExpr>(E); | |||
11738 | if (!InitList) { | |||
11739 | Visit(E); | |||
11740 | return; | |||
11741 | } | |||
11742 | ||||
11743 | // Track and increment the index here. | |||
11744 | isInitList = true; | |||
11745 | InitFieldIndex.push_back(0); | |||
11746 | for (auto Child : InitList->children()) { | |||
11747 | CheckExpr(cast<Expr>(Child)); | |||
11748 | ++InitFieldIndex.back(); | |||
11749 | } | |||
11750 | InitFieldIndex.pop_back(); | |||
11751 | } | |||
11752 | ||||
11753 | // Returns true if MemberExpr is checked and no further checking is needed. | |||
11754 | // Returns false if additional checking is required. | |||
11755 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { | |||
11756 | llvm::SmallVector<FieldDecl*, 4> Fields; | |||
11757 | Expr *Base = E; | |||
11758 | bool ReferenceField = false; | |||
11759 | ||||
11760 | // Get the field members used. | |||
11761 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
11762 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | |||
11763 | if (!FD) | |||
11764 | return false; | |||
11765 | Fields.push_back(FD); | |||
11766 | if (FD->getType()->isReferenceType()) | |||
11767 | ReferenceField = true; | |||
11768 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
11769 | } | |||
11770 | ||||
11771 | // Keep checking only if the base Decl is the same. | |||
11772 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); | |||
11773 | if (!DRE || DRE->getDecl() != OrigDecl) | |||
11774 | return false; | |||
11775 | ||||
11776 | // A reference field can be bound to an unininitialized field. | |||
11777 | if (CheckReference && !ReferenceField) | |||
11778 | return true; | |||
11779 | ||||
11780 | // Convert FieldDecls to their index number. | |||
11781 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | |||
11782 | for (const FieldDecl *I : llvm::reverse(Fields)) | |||
11783 | UsedFieldIndex.push_back(I->getFieldIndex()); | |||
11784 | ||||
11785 | // See if a warning is needed by checking the first difference in index | |||
11786 | // numbers. If field being used has index less than the field being | |||
11787 | // initialized, then the use is safe. | |||
11788 | for (auto UsedIter = UsedFieldIndex.begin(), | |||
11789 | UsedEnd = UsedFieldIndex.end(), | |||
11790 | OrigIter = InitFieldIndex.begin(), | |||
11791 | OrigEnd = InitFieldIndex.end(); | |||
11792 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | |||
11793 | if (*UsedIter < *OrigIter) | |||
11794 | return true; | |||
11795 | if (*UsedIter > *OrigIter) | |||
11796 | break; | |||
11797 | } | |||
11798 | ||||
11799 | // TODO: Add a different warning which will print the field names. | |||
11800 | HandleDeclRefExpr(DRE); | |||
11801 | return true; | |||
11802 | } | |||
11803 | ||||
11804 | // For most expressions, the cast is directly above the DeclRefExpr. | |||
11805 | // For conditional operators, the cast can be outside the conditional | |||
11806 | // operator if both expressions are DeclRefExpr's. | |||
11807 | void HandleValue(Expr *E) { | |||
11808 | E = E->IgnoreParens(); | |||
11809 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { | |||
11810 | HandleDeclRefExpr(DRE); | |||
11811 | return; | |||
11812 | } | |||
11813 | ||||
11814 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | |||
11815 | Visit(CO->getCond()); | |||
11816 | HandleValue(CO->getTrueExpr()); | |||
11817 | HandleValue(CO->getFalseExpr()); | |||
11818 | return; | |||
11819 | } | |||
11820 | ||||
11821 | if (BinaryConditionalOperator *BCO = | |||
11822 | dyn_cast<BinaryConditionalOperator>(E)) { | |||
11823 | Visit(BCO->getCond()); | |||
11824 | HandleValue(BCO->getFalseExpr()); | |||
11825 | return; | |||
11826 | } | |||
11827 | ||||
11828 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | |||
11829 | HandleValue(OVE->getSourceExpr()); | |||
11830 | return; | |||
11831 | } | |||
11832 | ||||
11833 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | |||
11834 | if (BO->getOpcode() == BO_Comma) { | |||
11835 | Visit(BO->getLHS()); | |||
11836 | HandleValue(BO->getRHS()); | |||
11837 | return; | |||
11838 | } | |||
11839 | } | |||
11840 | ||||
11841 | if (isa<MemberExpr>(E)) { | |||
11842 | if (isInitList) { | |||
11843 | if (CheckInitListMemberExpr(cast<MemberExpr>(E), | |||
11844 | false /*CheckReference*/)) | |||
11845 | return; | |||
11846 | } | |||
11847 | ||||
11848 | Expr *Base = E->IgnoreParenImpCasts(); | |||
11849 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
11850 | // Check for static member variables and don't warn on them. | |||
11851 | if (!isa<FieldDecl>(ME->getMemberDecl())) | |||
11852 | return; | |||
11853 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
11854 | } | |||
11855 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) | |||
11856 | HandleDeclRefExpr(DRE); | |||
11857 | return; | |||
11858 | } | |||
11859 | ||||
11860 | Visit(E); | |||
11861 | } | |||
11862 | ||||
11863 | // Reference types not handled in HandleValue are handled here since all | |||
11864 | // uses of references are bad, not just r-value uses. | |||
11865 | void VisitDeclRefExpr(DeclRefExpr *E) { | |||
11866 | if (isReferenceType) | |||
11867 | HandleDeclRefExpr(E); | |||
11868 | } | |||
11869 | ||||
11870 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | |||
11871 | if (E->getCastKind() == CK_LValueToRValue) { | |||
11872 | HandleValue(E->getSubExpr()); | |||
11873 | return; | |||
11874 | } | |||
11875 | ||||
11876 | Inherited::VisitImplicitCastExpr(E); | |||
11877 | } | |||
11878 | ||||
11879 | void VisitMemberExpr(MemberExpr *E) { | |||
11880 | if (isInitList) { | |||
11881 | if (CheckInitListMemberExpr(E, true /*CheckReference*/)) | |||
11882 | return; | |||
11883 | } | |||
11884 | ||||
11885 | // Don't warn on arrays since they can be treated as pointers. | |||
11886 | if (E->getType()->canDecayToPointerType()) return; | |||
11887 | ||||
11888 | // Warn when a non-static method call is followed by non-static member | |||
11889 | // field accesses, which is followed by a DeclRefExpr. | |||
11890 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); | |||
11891 | bool Warn = (MD && !MD->isStatic()); | |||
11892 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); | |||
11893 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | |||
11894 | if (!isa<FieldDecl>(ME->getMemberDecl())) | |||
11895 | Warn = false; | |||
11896 | Base = ME->getBase()->IgnoreParenImpCasts(); | |||
11897 | } | |||
11898 | ||||
11899 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { | |||
11900 | if (Warn) | |||
11901 | HandleDeclRefExpr(DRE); | |||
11902 | return; | |||
11903 | } | |||
11904 | ||||
11905 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. | |||
11906 | // Visit that expression. | |||
11907 | Visit(Base); | |||
11908 | } | |||
11909 | ||||
11910 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | |||
11911 | Expr *Callee = E->getCallee(); | |||
11912 | ||||
11913 | if (isa<UnresolvedLookupExpr>(Callee)) | |||
11914 | return Inherited::VisitCXXOperatorCallExpr(E); | |||
11915 | ||||
11916 | Visit(Callee); | |||
11917 | for (auto Arg: E->arguments()) | |||
11918 | HandleValue(Arg->IgnoreParenImpCasts()); | |||
11919 | } | |||
11920 | ||||
11921 | void VisitUnaryOperator(UnaryOperator *E) { | |||
11922 | // For POD record types, addresses of its own members are well-defined. | |||
11923 | if (E->getOpcode() == UO_AddrOf && isRecordType && | |||
11924 | isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { | |||
11925 | if (!isPODType) | |||
11926 | HandleValue(E->getSubExpr()); | |||
11927 | return; | |||
11928 | } | |||
11929 | ||||
11930 | if (E->isIncrementDecrementOp()) { | |||
11931 | HandleValue(E->getSubExpr()); | |||
11932 | return; | |||
11933 | } | |||
11934 | ||||
11935 | Inherited::VisitUnaryOperator(E); | |||
11936 | } | |||
11937 | ||||
11938 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} | |||
11939 | ||||
11940 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | |||
11941 | if (E->getConstructor()->isCopyConstructor()) { | |||
11942 | Expr *ArgExpr = E->getArg(0); | |||
11943 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | |||
11944 | if (ILE->getNumInits() == 1) | |||
11945 | ArgExpr = ILE->getInit(0); | |||
11946 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | |||
11947 | if (ICE->getCastKind() == CK_NoOp) | |||
11948 | ArgExpr = ICE->getSubExpr(); | |||
11949 | HandleValue(ArgExpr); | |||
11950 | return; | |||
11951 | } | |||
11952 | Inherited::VisitCXXConstructExpr(E); | |||
11953 | } | |||
11954 | ||||
11955 | void VisitCallExpr(CallExpr *E) { | |||
11956 | // Treat std::move as a use. | |||
11957 | if (E->isCallToStdMove()) { | |||
11958 | HandleValue(E->getArg(0)); | |||
11959 | return; | |||
11960 | } | |||
11961 | ||||
11962 | Inherited::VisitCallExpr(E); | |||
11963 | } | |||
11964 | ||||
11965 | void VisitBinaryOperator(BinaryOperator *E) { | |||
11966 | if (E->isCompoundAssignmentOp()) { | |||
11967 | HandleValue(E->getLHS()); | |||
11968 | Visit(E->getRHS()); | |||
11969 | return; | |||
11970 | } | |||
11971 | ||||
11972 | Inherited::VisitBinaryOperator(E); | |||
11973 | } | |||
11974 | ||||
11975 | // A custom visitor for BinaryConditionalOperator is needed because the | |||
11976 | // regular visitor would check the condition and true expression separately | |||
11977 | // but both point to the same place giving duplicate diagnostics. | |||
11978 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { | |||
11979 | Visit(E->getCond()); | |||
11980 | Visit(E->getFalseExpr()); | |||
11981 | } | |||
11982 | ||||
11983 | void HandleDeclRefExpr(DeclRefExpr *DRE) { | |||
11984 | Decl* ReferenceDecl = DRE->getDecl(); | |||
11985 | if (OrigDecl != ReferenceDecl) return; | |||
11986 | unsigned diag; | |||
11987 | if (isReferenceType) { | |||
11988 | diag = diag::warn_uninit_self_reference_in_reference_init; | |||
11989 | } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { | |||
11990 | diag = diag::warn_static_self_reference_in_init; | |||
11991 | } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || | |||
11992 | isa<NamespaceDecl>(OrigDecl->getDeclContext()) || | |||
11993 | DRE->getDecl()->getType()->isRecordType()) { | |||
11994 | diag = diag::warn_uninit_self_reference_in_init; | |||
11995 | } else { | |||
11996 | // Local variables will be handled by the CFG analysis. | |||
11997 | return; | |||
11998 | } | |||
11999 | ||||
12000 | S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, | |||
12001 | S.PDiag(diag) | |||
12002 | << DRE->getDecl() << OrigDecl->getLocation() | |||
12003 | << DRE->getSourceRange()); | |||
12004 | } | |||
12005 | }; | |||
12006 | ||||
12007 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. | |||
12008 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, | |||
12009 | bool DirectInit) { | |||
12010 | // Parameters arguments are occassionially constructed with itself, | |||
12011 | // for instance, in recursive functions. Skip them. | |||
12012 | if (isa<ParmVarDecl>(OrigDecl)) | |||
12013 | return; | |||
12014 | ||||
12015 | E = E->IgnoreParens(); | |||
12016 | ||||
12017 | // Skip checking T a = a where T is not a record or reference type. | |||
12018 | // Doing so is a way to silence uninitialized warnings. | |||
12019 | if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) | |||
12020 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) | |||
12021 | if (ICE->getCastKind() == CK_LValueToRValue) | |||
12022 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) | |||
12023 | if (DRE->getDecl() == OrigDecl) | |||
12024 | return; | |||
12025 | ||||
12026 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); | |||
12027 | } | |||
12028 | } // end anonymous namespace | |||
12029 | ||||
12030 | namespace { | |||
12031 | // Simple wrapper to add the name of a variable or (if no variable is | |||
12032 | // available) a DeclarationName into a diagnostic. | |||
12033 | struct VarDeclOrName { | |||
12034 | VarDecl *VDecl; | |||
12035 | DeclarationName Name; | |||
12036 | ||||
12037 | friend const Sema::SemaDiagnosticBuilder & | |||
12038 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { | |||
12039 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; | |||
12040 | } | |||
12041 | }; | |||
12042 | } // end anonymous namespace | |||
12043 | ||||
12044 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, | |||
12045 | DeclarationName Name, QualType Type, | |||
12046 | TypeSourceInfo *TSI, | |||
12047 | SourceRange Range, bool DirectInit, | |||
12048 | Expr *Init) { | |||
12049 | bool IsInitCapture = !VDecl; | |||
12050 | assert((!VDecl || !VDecl->isInitCapture()) &&(static_cast <bool> ((!VDecl || !VDecl->isInitCapture ()) && "init captures are expected to be deduced prior to initialization" ) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "clang/lib/Sema/SemaDecl.cpp", 12051, __extension__ __PRETTY_FUNCTION__ )) | |||
12051 | "init captures are expected to be deduced prior to initialization")(static_cast <bool> ((!VDecl || !VDecl->isInitCapture ()) && "init captures are expected to be deduced prior to initialization" ) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "clang/lib/Sema/SemaDecl.cpp", 12051, __extension__ __PRETTY_FUNCTION__ )); | |||
12052 | ||||
12053 | VarDeclOrName VN{VDecl, Name}; | |||
12054 | ||||
12055 | DeducedType *Deduced = Type->getContainedDeducedType(); | |||
12056 | assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")(static_cast <bool> (Deduced && "deduceVarTypeFromInitializer for non-deduced type" ) ? void (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\"" , "clang/lib/Sema/SemaDecl.cpp", 12056, __extension__ __PRETTY_FUNCTION__ )); | |||
12057 | ||||
12058 | // C++11 [dcl.spec.auto]p3 | |||
12059 | if (!Init) { | |||
12060 | assert(VDecl && "no init for init capture deduction?")(static_cast <bool> (VDecl && "no init for init capture deduction?" ) ? void (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\"" , "clang/lib/Sema/SemaDecl.cpp", 12060, __extension__ __PRETTY_FUNCTION__ )); | |||
12061 | ||||
12062 | // Except for class argument deduction, and then for an initializing | |||
12063 | // declaration only, i.e. no static at class scope or extern. | |||
12064 | if (!isa<DeducedTemplateSpecializationType>(Deduced) || | |||
12065 | VDecl->hasExternalStorage() || | |||
12066 | VDecl->isStaticDataMember()) { | |||
12067 | Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) | |||
12068 | << VDecl->getDeclName() << Type; | |||
12069 | return QualType(); | |||
12070 | } | |||
12071 | } | |||
12072 | ||||
12073 | ArrayRef<Expr*> DeduceInits; | |||
12074 | if (Init) | |||
12075 | DeduceInits = Init; | |||
12076 | ||||
12077 | if (DirectInit) { | |||
12078 | if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) | |||
12079 | DeduceInits = PL->exprs(); | |||
12080 | } | |||
12081 | ||||
12082 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | |||
12083 | assert(VDecl && "non-auto type for init capture deduction?")(static_cast <bool> (VDecl && "non-auto type for init capture deduction?" ) ? void (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\"" , "clang/lib/Sema/SemaDecl.cpp", 12083, __extension__ __PRETTY_FUNCTION__ )); | |||
12084 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | |||
12085 | InitializationKind Kind = InitializationKind::CreateForInit( | |||
12086 | VDecl->getLocation(), DirectInit, Init); | |||
12087 | // FIXME: Initialization should not be taking a mutable list of inits. | |||
12088 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); | |||
12089 | return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, | |||
12090 | InitsCopy); | |||
12091 | } | |||
12092 | ||||
12093 | if (DirectInit) { | |||
12094 | if (auto *IL = dyn_cast<InitListExpr>(Init)) | |||
12095 | DeduceInits = IL->inits(); | |||
12096 | } | |||
12097 | ||||
12098 | // Deduction only works if we have exactly one source expression. | |||
12099 | if (DeduceInits.empty()) { | |||
12100 | // It isn't possible to write this directly, but it is possible to | |||
12101 | // end up in this situation with "auto x(some_pack...);" | |||
12102 | Diag(Init->getBeginLoc(), IsInitCapture | |||
12103 | ? diag::err_init_capture_no_expression | |||
12104 | : diag::err_auto_var_init_no_expression) | |||
12105 | << VN << Type << Range; | |||
12106 | return QualType(); | |||
12107 | } | |||
12108 | ||||
12109 | if (DeduceInits.size() > 1) { | |||
12110 | Diag(DeduceInits[1]->getBeginLoc(), | |||
12111 | IsInitCapture ? diag::err_init_capture_multiple_expressions | |||
12112 | : diag::err_auto_var_init_multiple_expressions) | |||
12113 | << VN << Type << Range; | |||
12114 | return QualType(); | |||
12115 | } | |||
12116 | ||||
12117 | Expr *DeduceInit = DeduceInits[0]; | |||
12118 | if (DirectInit && isa<InitListExpr>(DeduceInit)) { | |||
12119 | Diag(Init->getBeginLoc(), IsInitCapture | |||
12120 | ? diag::err_init_capture_paren_braces | |||
12121 | : diag::err_auto_var_init_paren_braces) | |||
12122 | << isa<InitListExpr>(Init) << VN << Type << Range; | |||
12123 | return QualType(); | |||
12124 | } | |||
12125 | ||||
12126 | // Expressions default to 'id' when we're in a debugger. | |||
12127 | bool DefaultedAnyToId = false; | |||
12128 | if (getLangOpts().DebuggerCastResultToId && | |||
12129 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { | |||
12130 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | |||
12131 | if (Result.isInvalid()) { | |||
12132 | return QualType(); | |||
12133 | } | |||
12134 | Init = Result.get(); | |||
12135 | DefaultedAnyToId = true; | |||
12136 | } | |||
12137 | ||||
12138 | // C++ [dcl.decomp]p1: | |||
12139 | // If the assignment-expression [...] has array type A and no ref-qualifier | |||
12140 | // is present, e has type cv A | |||
12141 | if (VDecl && isa<DecompositionDecl>(VDecl) && | |||
12142 | Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && | |||
12143 | DeduceInit->getType()->isConstantArrayType()) | |||
12144 | return Context.getQualifiedType(DeduceInit->getType(), | |||
12145 | Type.getQualifiers()); | |||
12146 | ||||
12147 | QualType DeducedType; | |||
12148 | if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { | |||
12149 | if (!IsInitCapture) | |||
12150 | DiagnoseAutoDeductionFailure(VDecl, DeduceInit); | |||
12151 | else if (isa<InitListExpr>(Init)) | |||
12152 | Diag(Range.getBegin(), | |||
12153 | diag::err_init_capture_deduction_failure_from_init_list) | |||
12154 | << VN | |||
12155 | << (DeduceInit->getType().isNull() ? TSI->getType() | |||
12156 | : DeduceInit->getType()) | |||
12157 | << DeduceInit->getSourceRange(); | |||
12158 | else | |||
12159 | Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) | |||
12160 | << VN << TSI->getType() | |||
12161 | << (DeduceInit->getType().isNull() ? TSI->getType() | |||
12162 | : DeduceInit->getType()) | |||
12163 | << DeduceInit->getSourceRange(); | |||
12164 | } | |||
12165 | ||||
12166 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using | |||
12167 | // 'id' instead of a specific object type prevents most of our usual | |||
12168 | // checks. | |||
12169 | // We only want to warn outside of template instantiations, though: | |||
12170 | // inside a template, the 'id' could have come from a parameter. | |||
12171 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && | |||
12172 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { | |||
12173 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); | |||
12174 | Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; | |||
12175 | } | |||
12176 | ||||
12177 | return DeducedType; | |||
12178 | } | |||
12179 | ||||
12180 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, | |||
12181 | Expr *Init) { | |||
12182 | assert(!Init || !Init->containsErrors())(static_cast <bool> (!Init || !Init->containsErrors( )) ? void (0) : __assert_fail ("!Init || !Init->containsErrors()" , "clang/lib/Sema/SemaDecl.cpp", 12182, __extension__ __PRETTY_FUNCTION__ )); | |||
12183 | QualType DeducedType = deduceVarTypeFromInitializer( | |||
12184 | VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), | |||
12185 | VDecl->getSourceRange(), DirectInit, Init); | |||
12186 | if (DeducedType.isNull()) { | |||
12187 | VDecl->setInvalidDecl(); | |||
12188 | return true; | |||
12189 | } | |||
12190 | ||||
12191 | VDecl->setType(DeducedType); | |||
12192 | assert(VDecl->isLinkageValid())(static_cast <bool> (VDecl->isLinkageValid()) ? void (0) : __assert_fail ("VDecl->isLinkageValid()", "clang/lib/Sema/SemaDecl.cpp" , 12192, __extension__ __PRETTY_FUNCTION__)); | |||
12193 | ||||
12194 | // In ARC, infer lifetime. | |||
12195 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) | |||
12196 | VDecl->setInvalidDecl(); | |||
12197 | ||||
12198 | if (getLangOpts().OpenCL) | |||
12199 | deduceOpenCLAddressSpace(VDecl); | |||
12200 | ||||
12201 | // If this is a redeclaration, check that the type we just deduced matches | |||
12202 | // the previously declared type. | |||
12203 | if (VarDecl *Old = VDecl->getPreviousDecl()) { | |||
12204 | // We never need to merge the type, because we cannot form an incomplete | |||
12205 | // array of auto, nor deduce such a type. | |||
12206 | MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); | |||
12207 | } | |||
12208 | ||||
12209 | // Check the deduced type is valid for a variable declaration. | |||
12210 | CheckVariableDeclarationType(VDecl); | |||
12211 | return VDecl->isInvalidDecl(); | |||
12212 | } | |||
12213 | ||||
12214 | void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, | |||
12215 | SourceLocation Loc) { | |||
12216 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) | |||
12217 | Init = EWC->getSubExpr(); | |||
12218 | ||||
12219 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | |||
12220 | Init = CE->getSubExpr(); | |||
12221 | ||||
12222 | QualType InitType = Init->getType(); | |||
12223 | assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion () || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "clang/lib/Sema/SemaDecl.cpp", 12225, __extension__ __PRETTY_FUNCTION__ )) | |||
12224 | InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion () || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "clang/lib/Sema/SemaDecl.cpp", 12225, __extension__ __PRETTY_FUNCTION__ )) | |||
12225 | "shouldn't be called if type doesn't have a non-trivial C struct")(static_cast <bool> ((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion () || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? void (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "clang/lib/Sema/SemaDecl.cpp", 12225, __extension__ __PRETTY_FUNCTION__ )); | |||
12226 | if (auto *ILE = dyn_cast<InitListExpr>(Init)) { | |||
12227 | for (auto I : ILE->inits()) { | |||
12228 | if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && | |||
12229 | !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) | |||
12230 | continue; | |||
12231 | SourceLocation SL = I->getExprLoc(); | |||
12232 | checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); | |||
12233 | } | |||
12234 | return; | |||
12235 | } | |||
12236 | ||||
12237 | if (isa<ImplicitValueInitExpr>(Init)) { | |||
12238 | if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | |||
12239 | checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, | |||
12240 | NTCUK_Init); | |||
12241 | } else { | |||
12242 | // Assume all other explicit initializers involving copying some existing | |||
12243 | // object. | |||
12244 | // TODO: ignore any explicit initializers where we can guarantee | |||
12245 | // copy-elision. | |||
12246 | if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) | |||
12247 | checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); | |||
12248 | } | |||
12249 | } | |||
12250 | ||||
12251 | namespace { | |||
12252 | ||||
12253 | bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { | |||
12254 | // Ignore unavailable fields. A field can be marked as unavailable explicitly | |||
12255 | // in the source code or implicitly by the compiler if it is in a union | |||
12256 | // defined in a system header and has non-trivial ObjC ownership | |||
12257 | // qualifications. We don't want those fields to participate in determining | |||
12258 | // whether the containing union is non-trivial. | |||
12259 | return FD->hasAttr<UnavailableAttr>(); | |||
12260 | } | |||
12261 | ||||
12262 | struct DiagNonTrivalCUnionDefaultInitializeVisitor | |||
12263 | : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | |||
12264 | void> { | |||
12265 | using Super = | |||
12266 | DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | |||
12267 | void>; | |||
12268 | ||||
12269 | DiagNonTrivalCUnionDefaultInitializeVisitor( | |||
12270 | QualType OrigTy, SourceLocation OrigLoc, | |||
12271 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | |||
12272 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | |||
12273 | ||||
12274 | void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, | |||
12275 | const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12276 | if (const auto *AT = S.Context.getAsArrayType(QT)) | |||
12277 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | |||
12278 | InNonTrivialUnion); | |||
12279 | return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); | |||
12280 | } | |||
12281 | ||||
12282 | void visitARCStrong(QualType QT, const FieldDecl *FD, | |||
12283 | bool InNonTrivialUnion) { | |||
12284 | if (InNonTrivialUnion) | |||
12285 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | |||
12286 | << 1 << 0 << QT << FD->getName(); | |||
12287 | } | |||
12288 | ||||
12289 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12290 | if (InNonTrivialUnion) | |||
12291 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | |||
12292 | << 1 << 0 << QT << FD->getName(); | |||
12293 | } | |||
12294 | ||||
12295 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12296 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | |||
12297 | if (RD->isUnion()) { | |||
12298 | if (OrigLoc.isValid()) { | |||
12299 | bool IsUnion = false; | |||
12300 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | |||
12301 | IsUnion = OrigRD->isUnion(); | |||
12302 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | |||
12303 | << 0 << OrigTy << IsUnion << UseContext; | |||
12304 | // Reset OrigLoc so that this diagnostic is emitted only once. | |||
12305 | OrigLoc = SourceLocation(); | |||
12306 | } | |||
12307 | InNonTrivialUnion = true; | |||
12308 | } | |||
12309 | ||||
12310 | if (InNonTrivialUnion) | |||
12311 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | |||
12312 | << 0 << 0 << QT.getUnqualifiedType() << ""; | |||
12313 | ||||
12314 | for (const FieldDecl *FD : RD->fields()) | |||
12315 | if (!shouldIgnoreForRecordTriviality(FD)) | |||
12316 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | |||
12317 | } | |||
12318 | ||||
12319 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | |||
12320 | ||||
12321 | // The non-trivial C union type or the struct/union type that contains a | |||
12322 | // non-trivial C union. | |||
12323 | QualType OrigTy; | |||
12324 | SourceLocation OrigLoc; | |||
12325 | Sema::NonTrivialCUnionContext UseContext; | |||
12326 | Sema &S; | |||
12327 | }; | |||
12328 | ||||
12329 | struct DiagNonTrivalCUnionDestructedTypeVisitor | |||
12330 | : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { | |||
12331 | using Super = | |||
12332 | DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; | |||
12333 | ||||
12334 | DiagNonTrivalCUnionDestructedTypeVisitor( | |||
12335 | QualType OrigTy, SourceLocation OrigLoc, | |||
12336 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | |||
12337 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | |||
12338 | ||||
12339 | void visitWithKind(QualType::DestructionKind DK, QualType QT, | |||
12340 | const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12341 | if (const auto *AT = S.Context.getAsArrayType(QT)) | |||
12342 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | |||
12343 | InNonTrivialUnion); | |||
12344 | return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); | |||
12345 | } | |||
12346 | ||||
12347 | void visitARCStrong(QualType QT, const FieldDecl *FD, | |||
12348 | bool InNonTrivialUnion) { | |||
12349 | if (InNonTrivialUnion) | |||
12350 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | |||
12351 | << 1 << 1 << QT << FD->getName(); | |||
12352 | } | |||
12353 | ||||
12354 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12355 | if (InNonTrivialUnion) | |||
12356 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | |||
12357 | << 1 << 1 << QT << FD->getName(); | |||
12358 | } | |||
12359 | ||||
12360 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12361 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | |||
12362 | if (RD->isUnion()) { | |||
12363 | if (OrigLoc.isValid()) { | |||
12364 | bool IsUnion = false; | |||
12365 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | |||
12366 | IsUnion = OrigRD->isUnion(); | |||
12367 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | |||
12368 | << 1 << OrigTy << IsUnion << UseContext; | |||
12369 | // Reset OrigLoc so that this diagnostic is emitted only once. | |||
12370 | OrigLoc = SourceLocation(); | |||
12371 | } | |||
12372 | InNonTrivialUnion = true; | |||
12373 | } | |||
12374 | ||||
12375 | if (InNonTrivialUnion) | |||
12376 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | |||
12377 | << 0 << 1 << QT.getUnqualifiedType() << ""; | |||
12378 | ||||
12379 | for (const FieldDecl *FD : RD->fields()) | |||
12380 | if (!shouldIgnoreForRecordTriviality(FD)) | |||
12381 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | |||
12382 | } | |||
12383 | ||||
12384 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | |||
12385 | void visitCXXDestructor(QualType QT, const FieldDecl *FD, | |||
12386 | bool InNonTrivialUnion) {} | |||
12387 | ||||
12388 | // The non-trivial C union type or the struct/union type that contains a | |||
12389 | // non-trivial C union. | |||
12390 | QualType OrigTy; | |||
12391 | SourceLocation OrigLoc; | |||
12392 | Sema::NonTrivialCUnionContext UseContext; | |||
12393 | Sema &S; | |||
12394 | }; | |||
12395 | ||||
12396 | struct DiagNonTrivalCUnionCopyVisitor | |||
12397 | : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { | |||
12398 | using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; | |||
12399 | ||||
12400 | DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, | |||
12401 | Sema::NonTrivialCUnionContext UseContext, | |||
12402 | Sema &S) | |||
12403 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | |||
12404 | ||||
12405 | void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, | |||
12406 | const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12407 | if (const auto *AT = S.Context.getAsArrayType(QT)) | |||
12408 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | |||
12409 | InNonTrivialUnion); | |||
12410 | return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); | |||
12411 | } | |||
12412 | ||||
12413 | void visitARCStrong(QualType QT, const FieldDecl *FD, | |||
12414 | bool InNonTrivialUnion) { | |||
12415 | if (InNonTrivialUnion) | |||
12416 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | |||
12417 | << 1 << 2 << QT << FD->getName(); | |||
12418 | } | |||
12419 | ||||
12420 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12421 | if (InNonTrivialUnion) | |||
12422 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | |||
12423 | << 1 << 2 << QT << FD->getName(); | |||
12424 | } | |||
12425 | ||||
12426 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | |||
12427 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | |||
12428 | if (RD->isUnion()) { | |||
12429 | if (OrigLoc.isValid()) { | |||
12430 | bool IsUnion = false; | |||
12431 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | |||
12432 | IsUnion = OrigRD->isUnion(); | |||
12433 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | |||
12434 | << 2 << OrigTy << IsUnion << UseContext; | |||
12435 | // Reset OrigLoc so that this diagnostic is emitted only once. | |||
12436 | OrigLoc = SourceLocation(); | |||
12437 | } | |||
12438 | InNonTrivialUnion = true; | |||
12439 | } | |||
12440 | ||||
12441 | if (InNonTrivialUnion) | |||
12442 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | |||
12443 | << 0 << 2 << QT.getUnqualifiedType() << ""; | |||
12444 | ||||
12445 | for (const FieldDecl *FD : RD->fields()) | |||
12446 | if (!shouldIgnoreForRecordTriviality(FD)) | |||
12447 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | |||
12448 | } | |||
12449 | ||||
12450 | void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, | |||
12451 | const FieldDecl *FD, bool InNonTrivialUnion) {} | |||
12452 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | |||
12453 | void visitVolatileTrivial(QualType QT, const FieldDecl *FD, | |||
12454 | bool InNonTrivialUnion) {} | |||
12455 | ||||
12456 | // The non-trivial C union type or the struct/union type that contains a | |||
12457 | // non-trivial C union. | |||
12458 | QualType OrigTy; | |||
12459 | SourceLocation OrigLoc; | |||
12460 | Sema::NonTrivialCUnionContext UseContext; | |||
12461 | Sema &S; | |||
12462 | }; | |||
12463 | ||||
12464 | } // namespace | |||
12465 | ||||
12466 | void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, | |||
12467 | NonTrivialCUnionContext UseContext, | |||
12468 | unsigned NonTrivialKind) { | |||
12469 | assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion () || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "clang/lib/Sema/SemaDecl.cpp", 12472, __extension__ __PRETTY_FUNCTION__ )) | |||
12470 | QT.hasNonTrivialToPrimitiveDestructCUnion() ||(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion () || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "clang/lib/Sema/SemaDecl.cpp", 12472, __extension__ __PRETTY_FUNCTION__ )) | |||
12471 | QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion () || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "clang/lib/Sema/SemaDecl.cpp", 12472, __extension__ __PRETTY_FUNCTION__ )) | |||
12472 | "shouldn't be called if type doesn't have a non-trivial C union")(static_cast <bool> ((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion () || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? void (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "clang/lib/Sema/SemaDecl.cpp", 12472, __extension__ __PRETTY_FUNCTION__ )); | |||
12473 | ||||
12474 | if ((NonTrivialKind & NTCUK_Init) && | |||
12475 | QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | |||
12476 | DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) | |||
12477 | .visit(QT, nullptr, false); | |||
12478 | if ((NonTrivialKind & NTCUK_Destruct) && | |||
12479 | QT.hasNonTrivialToPrimitiveDestructCUnion()) | |||
12480 | DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) | |||
12481 | .visit(QT, nullptr, false); | |||
12482 | if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) | |||
12483 | DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) | |||
12484 | .visit(QT, nullptr, false); | |||
12485 | } | |||
12486 | ||||
12487 | /// AddInitializerToDecl - Adds the initializer Init to the | |||
12488 | /// declaration dcl. If DirectInit is true, this is C++ direct | |||
12489 | /// initialization rather than copy initialization. | |||
12490 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { | |||
12491 | // If there is no declaration, there was an error parsing it. Just ignore | |||
12492 | // the initializer. | |||
12493 | if (!RealDecl || RealDecl->isInvalidDecl()) { | |||
12494 | CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); | |||
12495 | return; | |||
12496 | } | |||
12497 | ||||
12498 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { | |||
12499 | // Pure-specifiers are handled in ActOnPureSpecifier. | |||
12500 | Diag(Method->getLocation(), diag::err_member_function_initialization) | |||
12501 | << Method->getDeclName() << Init->getSourceRange(); | |||
12502 | Method->setInvalidDecl(); | |||
12503 | return; | |||
12504 | } | |||
12505 | ||||
12506 | VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); | |||
12507 | if (!VDecl) { | |||
12508 | assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")(static_cast <bool> (!isa<FieldDecl>(RealDecl) && "field init shouldn't get here") ? void (0) : __assert_fail ( "!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\"" , "clang/lib/Sema/SemaDecl.cpp", 12508, __extension__ __PRETTY_FUNCTION__ )); | |||
12509 | Diag(RealDecl->getLocation(), diag::err_illegal_initializer); | |||
12510 | RealDecl->setInvalidDecl(); | |||
12511 | return; | |||
12512 | } | |||
12513 | ||||
12514 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. | |||
12515 | if (VDecl->getType()->isUndeducedType()) { | |||
12516 | // Attempt typo correction early so that the type of the init expression can | |||
12517 | // be deduced based on the chosen correction if the original init contains a | |||
12518 | // TypoExpr. | |||
12519 | ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); | |||
12520 | if (!Res.isUsable()) { | |||
12521 | // There are unresolved typos in Init, just drop them. | |||
12522 | // FIXME: improve the recovery strategy to preserve the Init. | |||
12523 | RealDecl->setInvalidDecl(); | |||
12524 | return; | |||
12525 | } | |||
12526 | if (Res.get()->containsErrors()) { | |||
12527 | // Invalidate the decl as we don't know the type for recovery-expr yet. | |||
12528 | RealDecl->setInvalidDecl(); | |||
12529 | VDecl->setInit(Res.get()); | |||
12530 | return; | |||
12531 | } | |||
12532 | Init = Res.get(); | |||
12533 | ||||
12534 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) | |||
12535 | return; | |||
12536 | } | |||
12537 | ||||
12538 | // dllimport cannot be used on variable definitions. | |||
12539 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { | |||
12540 | Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); | |||
12541 | VDecl->setInvalidDecl(); | |||
12542 | return; | |||
12543 | } | |||
12544 | ||||
12545 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { | |||
12546 | // C99 6.7.8p5. C++ has no such restriction, but that is a defect. | |||
12547 | Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); | |||
12548 | VDecl->setInvalidDecl(); | |||
12549 | return; | |||
12550 | } | |||
12551 | ||||
12552 | if (!VDecl->getType()->isDependentType()) { | |||
12553 | // A definition must end up with a complete type, which means it must be | |||
12554 | // complete with the restriction that an array type might be completed by | |||
12555 | // the initializer; note that later code assumes this restriction. | |||
12556 | QualType BaseDeclType = VDecl->getType(); | |||
12557 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) | |||
12558 | BaseDeclType = Array->getElementType(); | |||
12559 | if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, | |||
12560 | diag::err_typecheck_decl_incomplete_type)) { | |||
12561 | RealDecl->setInvalidDecl(); | |||
12562 | return; | |||
12563 | } | |||
12564 | ||||
12565 | // The variable can not have an abstract class type. | |||
12566 | if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), | |||
12567 | diag::err_abstract_type_in_decl, | |||
12568 | AbstractVariableType)) | |||
12569 | VDecl->setInvalidDecl(); | |||
12570 | } | |||
12571 | ||||
12572 | // If adding the initializer will turn this declaration into a definition, | |||
12573 | // and we already have a definition for this variable, diagnose or otherwise | |||
12574 | // handle the situation. | |||
12575 | if (VarDecl *Def = VDecl->getDefinition()) | |||
12576 | if (Def != VDecl && | |||
12577 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && | |||
12578 | !VDecl->isThisDeclarationADemotedDefinition() && | |||
12579 | checkVarDeclRedefinition(Def, VDecl)) | |||
12580 | return; | |||
12581 | ||||
12582 | if (getLangOpts().CPlusPlus) { | |||
12583 | // C++ [class.static.data]p4 | |||
12584 | // If a static data member is of const integral or const | |||
12585 | // enumeration type, its declaration in the class definition can | |||
12586 | // specify a constant-initializer which shall be an integral | |||
12587 | // constant expression (5.19). In that case, the member can appear | |||
12588 | // in integral constant expressions. The member shall still be | |||
12589 | // defined in a namespace scope if it is used in the program and the | |||
12590 | // namespace scope definition shall not contain an initializer. | |||
12591 | // | |||
12592 | // We already performed a redefinition check above, but for static | |||
12593 | // data members we also need to check whether there was an in-class | |||
12594 | // declaration with an initializer. | |||
12595 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { | |||
12596 | Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) | |||
12597 | << VDecl->getDeclName(); | |||
12598 | Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), | |||
12599 | diag::note_previous_initializer) | |||
12600 | << 0; | |||
12601 | return; | |||
12602 | } | |||
12603 | ||||
12604 | if (VDecl->hasLocalStorage()) | |||
12605 | setFunctionHasBranchProtectedScope(); | |||
12606 | ||||
12607 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { | |||
12608 | VDecl->setInvalidDecl(); | |||
12609 | return; | |||
12610 | } | |||
12611 | } | |||
12612 | ||||
12613 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside | |||
12614 | // a kernel function cannot be initialized." | |||
12615 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { | |||
12616 | Diag(VDecl->getLocation(), diag::err_local_cant_init); | |||
12617 | VDecl->setInvalidDecl(); | |||
12618 | return; | |||
12619 | } | |||
12620 | ||||
12621 | // The LoaderUninitialized attribute acts as a definition (of undef). | |||
12622 | if (VDecl->hasAttr<LoaderUninitializedAttr>()) { | |||
12623 | Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); | |||
12624 | VDecl->setInvalidDecl(); | |||
12625 | return; | |||
12626 | } | |||
12627 | ||||
12628 | // Get the decls type and save a reference for later, since | |||
12629 | // CheckInitializerTypes may change it. | |||
12630 | QualType DclT = VDecl->getType(), SavT = DclT; | |||
12631 | ||||
12632 | // Expressions default to 'id' when we're in a debugger | |||
12633 | // and we are assigning it to a variable of Objective-C pointer type. | |||
12634 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && | |||
12635 | Init->getType() == Context.UnknownAnyTy) { | |||
12636 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | |||
12637 | if (Result.isInvalid()) { | |||
12638 | VDecl->setInvalidDecl(); | |||
12639 | return; | |||
12640 | } | |||
12641 | Init = Result.get(); | |||
12642 | } | |||
12643 | ||||
12644 | // Perform the initialization. | |||
12645 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); | |||
12646 | if (!VDecl->isInvalidDecl()) { | |||
12647 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | |||
12648 | InitializationKind Kind = InitializationKind::CreateForInit( | |||
12649 | VDecl->getLocation(), DirectInit, Init); | |||
12650 | ||||
12651 | MultiExprArg Args = Init; | |||
12652 | if (CXXDirectInit) | |||
12653 | Args = MultiExprArg(CXXDirectInit->getExprs(), | |||
12654 | CXXDirectInit->getNumExprs()); | |||
12655 | ||||
12656 | // Try to correct any TypoExprs in the initialization arguments. | |||
12657 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { | |||
12658 | ExprResult Res = CorrectDelayedTyposInExpr( | |||
12659 | Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, | |||
12660 | [this, Entity, Kind](Expr *E) { | |||
12661 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); | |||
12662 | return Init.Failed() ? ExprError() : E; | |||
12663 | }); | |||
12664 | if (Res.isInvalid()) { | |||
12665 | VDecl->setInvalidDecl(); | |||
12666 | } else if (Res.get() != Args[Idx]) { | |||
12667 | Args[Idx] = Res.get(); | |||
12668 | } | |||
12669 | } | |||
12670 | if (VDecl->isInvalidDecl()) | |||
12671 | return; | |||
12672 | ||||
12673 | InitializationSequence InitSeq(*this, Entity, Kind, Args, | |||
12674 | /*TopLevelOfInitList=*/false, | |||
12675 | /*TreatUnavailableAsInvalid=*/false); | |||
12676 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); | |||
12677 | if (Result.isInvalid()) { | |||
12678 | // If the provided initializer fails to initialize the var decl, | |||
12679 | // we attach a recovery expr for better recovery. | |||
12680 | auto RecoveryExpr = | |||
12681 | CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); | |||
12682 | if (RecoveryExpr.get()) | |||
12683 | VDecl->setInit(RecoveryExpr.get()); | |||
12684 | return; | |||
12685 | } | |||
12686 | ||||
12687 | Init = Result.getAs<Expr>(); | |||
12688 | } | |||
12689 | ||||
12690 | // Check for self-references within variable initializers. | |||
12691 | // Variables declared within a function/method body (except for references) | |||
12692 | // are handled by a dataflow analysis. | |||
12693 | // This is undefined behavior in C++, but valid in C. | |||
12694 | if (getLangOpts().CPlusPlus) | |||
12695 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || | |||
12696 | VDecl->getType()->isReferenceType()) | |||
12697 | CheckSelfReference(*this, RealDecl, Init, DirectInit); | |||
12698 | ||||
12699 | // If the type changed, it means we had an incomplete type that was | |||
12700 | // completed by the initializer. For example: | |||
12701 | // int ary[] = { 1, 3, 5 }; | |||
12702 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. | |||
12703 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) | |||
12704 | VDecl->setType(DclT); | |||
12705 | ||||
12706 | if (!VDecl->isInvalidDecl()) { | |||
12707 | checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); | |||
12708 | ||||
12709 | if (VDecl->hasAttr<BlocksAttr>()) | |||
12710 | checkRetainCycles(VDecl, Init); | |||
12711 | ||||
12712 | // It is safe to assign a weak reference into a strong variable. | |||
12713 | // Although this code can still have problems: | |||
12714 | // id x = self.weakProp; | |||
12715 | // id y = self.weakProp; | |||
12716 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | |||
12717 | // paths through the function. This should be revisited if | |||
12718 | // -Wrepeated-use-of-weak is made flow-sensitive. | |||
12719 | if (FunctionScopeInfo *FSI = getCurFunction()) | |||
12720 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || | |||
12721 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && | |||
12722 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | |||
12723 | Init->getBeginLoc())) | |||
12724 | FSI->markSafeWeakUse(Init); | |||
12725 | } | |||
12726 | ||||
12727 | // The initialization is usually a full-expression. | |||
12728 | // | |||
12729 | // FIXME: If this is a braced initialization of an aggregate, it is not | |||
12730 | // an expression, and each individual field initializer is a separate | |||
12731 | // full-expression. For instance, in: | |||
12732 | // | |||
12733 | // struct Temp { ~Temp(); }; | |||
12734 | // struct S { S(Temp); }; | |||
12735 | // struct T { S a, b; } t = { Temp(), Temp() } | |||
12736 | // | |||
12737 | // we should destroy the first Temp before constructing the second. | |||
12738 | ExprResult Result = | |||
12739 | ActOnFinishFullExpr(Init, VDecl->getLocation(), | |||
12740 | /*DiscardedValue*/ false, VDecl->isConstexpr()); | |||
12741 | if (Result.isInvalid()) { | |||
12742 | VDecl->setInvalidDecl(); | |||
12743 | return; | |||
12744 | } | |||
12745 | Init = Result.get(); | |||
12746 | ||||
12747 | // Attach the initializer to the decl. | |||
12748 | VDecl->setInit(Init); | |||
12749 | ||||
12750 | if (VDecl->isLocalVarDecl()) { | |||
12751 | // Don't check the initializer if the declaration is malformed. | |||
12752 | if (VDecl->isInvalidDecl()) { | |||
12753 | // do nothing | |||
12754 | ||||
12755 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. | |||
12756 | // This is true even in C++ for OpenCL. | |||
12757 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { | |||
12758 | CheckForConstantInitializer(Init, DclT); | |||
12759 | ||||
12760 | // Otherwise, C++ does not restrict the initializer. | |||
12761 | } else if (getLangOpts().CPlusPlus) { | |||
12762 | // do nothing | |||
12763 | ||||
12764 | // C99 6.7.8p4: All the expressions in an initializer for an object that has | |||
12765 | // static storage duration shall be constant expressions or string literals. | |||
12766 | } else if (VDecl->getStorageClass() == SC_Static) { | |||
12767 | CheckForConstantInitializer(Init, DclT); | |||
12768 | ||||
12769 | // C89 is stricter than C99 for aggregate initializers. | |||
12770 | // C89 6.5.7p3: All the expressions [...] in an initializer list | |||
12771 | // for an object that has aggregate or union type shall be | |||
12772 | // constant expressions. | |||
12773 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && | |||
12774 | isa<InitListExpr>(Init)) { | |||
12775 | const Expr *Culprit; | |||
12776 | if (!Init->isConstantInitializer(Context, false, &Culprit)) { | |||
12777 | Diag(Culprit->getExprLoc(), | |||
12778 | diag::ext_aggregate_init_not_constant) | |||
12779 | << Culprit->getSourceRange(); | |||
12780 | } | |||
12781 | } | |||
12782 | ||||
12783 | if (auto *E = dyn_cast<ExprWithCleanups>(Init)) | |||
12784 | if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) | |||
12785 | if (VDecl->hasLocalStorage()) | |||
12786 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | |||
12787 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && | |||
12788 | VDecl->getLexicalDeclContext()->isRecord()) { | |||
12789 | // This is an in-class initialization for a static data member, e.g., | |||
12790 | // | |||
12791 | // struct S { | |||
12792 | // static const int value = 17; | |||
12793 | // }; | |||
12794 | ||||
12795 | // C++ [class.mem]p4: | |||
12796 | // A member-declarator can contain a constant-initializer only | |||
12797 | // if it declares a static member (9.4) of const integral or | |||
12798 | // const enumeration type, see 9.4.2. | |||
12799 | // | |||
12800 | // C++11 [class.static.data]p3: | |||
12801 | // If a non-volatile non-inline const static data member is of integral | |||
12802 | // or enumeration type, its declaration in the class definition can | |||
12803 | // specify a brace-or-equal-initializer in which every initializer-clause | |||
12804 | // that is an assignment-expression is a constant expression. A static | |||
12805 | // data member of literal type can be declared in the class definition | |||
12806 | // with the constexpr specifier; if so, its declaration shall specify a | |||
12807 | // brace-or-equal-initializer in which every initializer-clause that is | |||
12808 | // an assignment-expression is a constant expression. | |||
12809 | ||||
12810 | // Do nothing on dependent types. | |||
12811 | if (DclT->isDependentType()) { | |||
12812 | ||||
12813 | // Allow any 'static constexpr' members, whether or not they are of literal | |||
12814 | // type. We separately check that every constexpr variable is of literal | |||
12815 | // type. | |||
12816 | } else if (VDecl->isConstexpr()) { | |||
12817 | ||||
12818 | // Require constness. | |||
12819 | } else if (!DclT.isConstQualified()) { | |||
12820 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) | |||
12821 | << Init->getSourceRange(); | |||
12822 | VDecl->setInvalidDecl(); | |||
12823 | ||||
12824 | // We allow integer constant expressions in all cases. | |||
12825 | } else if (DclT->isIntegralOrEnumerationType()) { | |||
12826 | // Check whether the expression is a constant expression. | |||
12827 | SourceLocation Loc; | |||
12828 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) | |||
12829 | // In C++11, a non-constexpr const static data member with an | |||
12830 | // in-class initializer cannot be volatile. | |||
12831 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); | |||
12832 | else if (Init->isValueDependent()) | |||
12833 | ; // Nothing to check. | |||
12834 | else if (Init->isIntegerConstantExpr(Context, &Loc)) | |||
12835 | ; // Ok, it's an ICE! | |||
12836 | else if (Init->getType()->isScopedEnumeralType() && | |||
12837 | Init->isCXX11ConstantExpr(Context)) | |||
12838 | ; // Ok, it is a scoped-enum constant expression. | |||
12839 | else if (Init->isEvaluatable(Context)) { | |||
12840 | // If we can constant fold the initializer through heroics, accept it, | |||
12841 | // but report this as a use of an extension for -pedantic. | |||
12842 | Diag(Loc, diag::ext_in_class_initializer_non_constant) | |||
12843 | << Init->getSourceRange(); | |||
12844 | } else { | |||
12845 | // Otherwise, this is some crazy unknown case. Report the issue at the | |||
12846 | // location provided by the isIntegerConstantExpr failed check. | |||
12847 | Diag(Loc, diag::err_in_class_initializer_non_constant) | |||
12848 | << Init->getSourceRange(); | |||
12849 | VDecl->setInvalidDecl(); | |||
12850 | } | |||
12851 | ||||
12852 | // We allow foldable floating-point constants as an extension. | |||
12853 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok | |||
12854 | // In C++98, this is a GNU extension. In C++11, it is not, but we support | |||
12855 | // it anyway and provide a fixit to add the 'constexpr'. | |||
12856 | if (getLangOpts().CPlusPlus11) { | |||
12857 | Diag(VDecl->getLocation(), | |||
12858 | diag::ext_in_class_initializer_float_type_cxx11) | |||
12859 | << DclT << Init->getSourceRange(); | |||
12860 | Diag(VDecl->getBeginLoc(), | |||
12861 | diag::note_in_class_initializer_float_type_cxx11) | |||
12862 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | |||
12863 | } else { | |||
12864 | Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) | |||
12865 | << DclT << Init->getSourceRange(); | |||
12866 | ||||
12867 | if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { | |||
12868 | Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) | |||
12869 | << Init->getSourceRange(); | |||
12870 | VDecl->setInvalidDecl(); | |||
12871 | } | |||
12872 | } | |||
12873 | ||||
12874 | // Suggest adding 'constexpr' in C++11 for literal types. | |||
12875 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { | |||
12876 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) | |||
12877 | << DclT << Init->getSourceRange() | |||
12878 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | |||
12879 | VDecl->setConstexpr(true); | |||
12880 | ||||
12881 | } else { | |||
12882 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) | |||
12883 | << DclT << Init->getSourceRange(); | |||
12884 | VDecl->setInvalidDecl(); | |||
12885 | } | |||
12886 | } else if (VDecl->isFileVarDecl()) { | |||
12887 | // In C, extern is typically used to avoid tentative definitions when | |||
12888 | // declaring variables in headers, but adding an intializer makes it a | |||
12889 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. | |||
12890 | // In C++, extern is often used to give implictly static const variables | |||
12891 | // external linkage, so don't warn in that case. If selectany is present, | |||
12892 | // this might be header code intended for C and C++ inclusion, so apply the | |||
12893 | // C++ rules. | |||
12894 | if (VDecl->getStorageClass() == SC_Extern && | |||
12895 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || | |||
12896 | !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && | |||
12897 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && | |||
12898 | !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) | |||
12899 | Diag(VDecl->getLocation(), diag::warn_extern_init); | |||
12900 | ||||
12901 | // In Microsoft C++ mode, a const variable defined in namespace scope has | |||
12902 | // external linkage by default if the variable is declared with | |||
12903 | // __declspec(dllexport). | |||
12904 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | |||
12905 | getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && | |||
12906 | VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) | |||
12907 | VDecl->setStorageClass(SC_Extern); | |||
12908 | ||||
12909 | // C99 6.7.8p4. All file scoped initializers need to be constant. | |||
12910 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) | |||
12911 | CheckForConstantInitializer(Init, DclT); | |||
12912 | } | |||
12913 | ||||
12914 | QualType InitType = Init->getType(); | |||
12915 | if (!InitType.isNull() && | |||
12916 | (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | |||
12917 | InitType.hasNonTrivialToPrimitiveCopyCUnion())) | |||
12918 | checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); | |||
12919 | ||||
12920 | // We will represent direct-initialization similarly to copy-initialization: | |||
12921 | // int x(1); -as-> int x = 1; | |||
12922 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); | |||
12923 | // | |||
12924 | // Clients that want to distinguish between the two forms, can check for | |||
12925 | // direct initializer using VarDecl::getInitStyle(). | |||
12926 | // A major benefit is that clients that don't particularly care about which | |||
12927 | // exactly form was it (like the CodeGen) can handle both cases without | |||
12928 | // special case code. | |||
12929 | ||||
12930 | // C++ 8.5p11: | |||
12931 | // The form of initialization (using parentheses or '=') is generally | |||
12932 | // insignificant, but does matter when the entity being initialized has a | |||
12933 | // class type. | |||
12934 | if (CXXDirectInit) { | |||
12935 | assert(DirectInit && "Call-style initializer must be direct init.")(static_cast <bool> (DirectInit && "Call-style initializer must be direct init." ) ? void (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\"" , "clang/lib/Sema/SemaDecl.cpp", 12935, __extension__ __PRETTY_FUNCTION__ )); | |||
12936 | VDecl->setInitStyle(VarDecl::CallInit); | |||
12937 | } else if (DirectInit) { | |||
12938 | // This must be list-initialization. No other way is direct-initialization. | |||
12939 | VDecl->setInitStyle(VarDecl::ListInit); | |||
12940 | } | |||
12941 | ||||
12942 | if (LangOpts.OpenMP && | |||
12943 | (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) && | |||
12944 | VDecl->isFileVarDecl()) | |||
12945 | DeclsToCheckForDeferredDiags.insert(VDecl); | |||
12946 | CheckCompleteVariableDeclaration(VDecl); | |||
12947 | } | |||
12948 | ||||
12949 | /// ActOnInitializerError - Given that there was an error parsing an | |||
12950 | /// initializer for the given declaration, try to at least re-establish | |||
12951 | /// invariants such as whether a variable's type is either dependent or | |||
12952 | /// complete. | |||
12953 | void Sema::ActOnInitializerError(Decl *D) { | |||
12954 | // Our main concern here is re-establishing invariants like "a | |||
12955 | // variable's type is either dependent or complete". | |||
12956 | if (!D || D->isInvalidDecl()) return; | |||
12957 | ||||
12958 | VarDecl *VD = dyn_cast<VarDecl>(D); | |||
12959 | if (!VD) return; | |||
12960 | ||||
12961 | // Bindings are not usable if we can't make sense of the initializer. | |||
12962 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) | |||
12963 | for (auto *BD : DD->bindings()) | |||
12964 | BD->setInvalidDecl(); | |||
12965 | ||||
12966 | // Auto types are meaningless if we can't make sense of the initializer. | |||
12967 | if (VD->getType()->isUndeducedType()) { | |||
12968 | D->setInvalidDecl(); | |||
12969 | return; | |||
12970 | } | |||
12971 | ||||
12972 | QualType Ty = VD->getType(); | |||
12973 | if (Ty->isDependentType()) return; | |||
12974 | ||||
12975 | // Require a complete type. | |||
12976 | if (RequireCompleteType(VD->getLocation(), | |||
12977 | Context.getBaseElementType(Ty), | |||
12978 | diag::err_typecheck_decl_incomplete_type)) { | |||
12979 | VD->setInvalidDecl(); | |||
12980 | return; | |||
12981 | } | |||
12982 | ||||
12983 | // Require a non-abstract type. | |||
12984 | if (RequireNonAbstractType(VD->getLocation(), Ty, | |||
12985 | diag::err_abstract_type_in_decl, | |||
12986 | AbstractVariableType)) { | |||
12987 | VD->setInvalidDecl(); | |||
12988 | return; | |||
12989 | } | |||
12990 | ||||
12991 | // Don't bother complaining about constructors or destructors, | |||
12992 | // though. | |||
12993 | } | |||
12994 | ||||
12995 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { | |||
12996 | // If there is no declaration, there was an error parsing it. Just ignore it. | |||
12997 | if (!RealDecl) | |||
12998 | return; | |||
12999 | ||||
13000 | if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { | |||
13001 | QualType Type = Var->getType(); | |||
13002 | ||||
13003 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. | |||
13004 | if (isa<DecompositionDecl>(RealDecl)) { | |||
13005 | Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; | |||
13006 | Var->setInvalidDecl(); | |||
13007 | return; | |||
13008 | } | |||
13009 | ||||
13010 | if (Type->isUndeducedType() && | |||
13011 | DeduceVariableDeclarationType(Var, false, nullptr)) | |||
13012 | return; | |||
13013 | ||||
13014 | // C++11 [class.static.data]p3: A static data member can be declared with | |||
13015 | // the constexpr specifier; if so, its declaration shall specify | |||
13016 | // a brace-or-equal-initializer. | |||
13017 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to | |||
13018 | // the definition of a variable [...] or the declaration of a static data | |||
13019 | // member. | |||
13020 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && | |||
13021 | !Var->isThisDeclarationADemotedDefinition()) { | |||
13022 | if (Var->isStaticDataMember()) { | |||
13023 | // C++1z removes the relevant rule; the in-class declaration is always | |||
13024 | // a definition there. | |||
13025 | if (!getLangOpts().CPlusPlus17 && | |||
13026 | !Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
13027 | Diag(Var->getLocation(), | |||
13028 | diag::err_constexpr_static_mem_var_requires_init) | |||
13029 | << Var; | |||
13030 | Var->setInvalidDecl(); | |||
13031 | return; | |||
13032 | } | |||
13033 | } else { | |||
13034 | Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); | |||
13035 | Var->setInvalidDecl(); | |||
13036 | return; | |||
13037 | } | |||
13038 | } | |||
13039 | ||||
13040 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must | |||
13041 | // be initialized. | |||
13042 | if (!Var->isInvalidDecl() && | |||
13043 | Var->getType().getAddressSpace() == LangAS::opencl_constant && | |||
13044 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { | |||
13045 | bool HasConstExprDefaultConstructor = false; | |||
13046 | if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { | |||
13047 | for (auto *Ctor : RD->ctors()) { | |||
13048 | if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 && | |||
13049 | Ctor->getMethodQualifiers().getAddressSpace() == | |||
13050 | LangAS::opencl_constant) { | |||
13051 | HasConstExprDefaultConstructor = true; | |||
13052 | } | |||
13053 | } | |||
13054 | } | |||
13055 | if (!HasConstExprDefaultConstructor) { | |||
13056 | Diag(Var->getLocation(), diag::err_opencl_constant_no_init); | |||
13057 | Var->setInvalidDecl(); | |||
13058 | return; | |||
13059 | } | |||
13060 | } | |||
13061 | ||||
13062 | if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { | |||
13063 | if (Var->getStorageClass() == SC_Extern) { | |||
13064 | Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) | |||
13065 | << Var; | |||
13066 | Var->setInvalidDecl(); | |||
13067 | return; | |||
13068 | } | |||
13069 | if (RequireCompleteType(Var->getLocation(), Var->getType(), | |||
13070 | diag::err_typecheck_decl_incomplete_type)) { | |||
13071 | Var->setInvalidDecl(); | |||
13072 | return; | |||
13073 | } | |||
13074 | if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { | |||
13075 | if (!RD->hasTrivialDefaultConstructor()) { | |||
13076 | Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); | |||
13077 | Var->setInvalidDecl(); | |||
13078 | return; | |||
13079 | } | |||
13080 | } | |||
13081 | // The declaration is unitialized, no need for further checks. | |||
13082 | return; | |||
13083 | } | |||
13084 | ||||
13085 | VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); | |||
13086 | if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && | |||
13087 | Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | |||
13088 | checkNonTrivialCUnion(Var->getType(), Var->getLocation(), | |||
13089 | NTCUC_DefaultInitializedObject, NTCUK_Init); | |||
13090 | ||||
13091 | ||||
13092 | switch (DefKind) { | |||
13093 | case VarDecl::Definition: | |||
13094 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) | |||
13095 | break; | |||
13096 | ||||
13097 | // We have an out-of-line definition of a static data member | |||
13098 | // that has an in-class initializer, so we type-check this like | |||
13099 | // a declaration. | |||
13100 | // | |||
13101 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | |||
13102 | ||||
13103 | case VarDecl::DeclarationOnly: | |||
13104 | // It's only a declaration. | |||
13105 | ||||
13106 | // Block scope. C99 6.7p7: If an identifier for an object is | |||
13107 | // declared with no linkage (C99 6.2.2p6), the type for the | |||
13108 | // object shall be complete. | |||
13109 | if (!Type->isDependentType() && Var->isLocalVarDecl() && | |||
13110 | !Var->hasLinkage() && !Var->isInvalidDecl() && | |||
13111 | RequireCompleteType(Var->getLocation(), Type, | |||
13112 | diag::err_typecheck_decl_incomplete_type)) | |||
13113 | Var->setInvalidDecl(); | |||
13114 | ||||
13115 | // Make sure that the type is not abstract. | |||
13116 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | |||
13117 | RequireNonAbstractType(Var->getLocation(), Type, | |||
13118 | diag::err_abstract_type_in_decl, | |||
13119 | AbstractVariableType)) | |||
13120 | Var->setInvalidDecl(); | |||
13121 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | |||
13122 | Var->getStorageClass() == SC_PrivateExtern) { | |||
13123 | Diag(Var->getLocation(), diag::warn_private_extern); | |||
13124 | Diag(Var->getLocation(), diag::note_private_extern); | |||
13125 | } | |||
13126 | ||||
13127 | if (Context.getTargetInfo().allowDebugInfoForExternalRef() && | |||
13128 | !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) | |||
13129 | ExternalDeclarations.push_back(Var); | |||
13130 | ||||
13131 | return; | |||
13132 | ||||
13133 | case VarDecl::TentativeDefinition: | |||
13134 | // File scope. C99 6.9.2p2: A declaration of an identifier for an | |||
13135 | // object that has file scope without an initializer, and without a | |||
13136 | // storage-class specifier or with the storage-class specifier "static", | |||
13137 | // constitutes a tentative definition. Note: A tentative definition with | |||
13138 | // external linkage is valid (C99 6.2.2p5). | |||
13139 | if (!Var->isInvalidDecl()) { | |||
13140 | if (const IncompleteArrayType *ArrayT | |||
13141 | = Context.getAsIncompleteArrayType(Type)) { | |||
13142 | if (RequireCompleteSizedType( | |||
13143 | Var->getLocation(), ArrayT->getElementType(), | |||
13144 | diag::err_array_incomplete_or_sizeless_type)) | |||
13145 | Var->setInvalidDecl(); | |||
13146 | } else if (Var->getStorageClass() == SC_Static) { | |||
13147 | // C99 6.9.2p3: If the declaration of an identifier for an object is | |||
13148 | // a tentative definition and has internal linkage (C99 6.2.2p3), the | |||
13149 | // declared type shall not be an incomplete type. | |||
13150 | // NOTE: code such as the following | |||
13151 | // static struct s; | |||
13152 | // struct s { int a; }; | |||
13153 | // is accepted by gcc. Hence here we issue a warning instead of | |||
13154 | // an error and we do not invalidate the static declaration. | |||
13155 | // NOTE: to avoid multiple warnings, only check the first declaration. | |||
13156 | if (Var->isFirstDecl()) | |||
13157 | RequireCompleteType(Var->getLocation(), Type, | |||
13158 | diag::ext_typecheck_decl_incomplete_type); | |||
13159 | } | |||
13160 | } | |||
13161 | ||||
13162 | // Record the tentative definition; we're done. | |||
13163 | if (!Var->isInvalidDecl()) | |||
13164 | TentativeDefinitions.push_back(Var); | |||
13165 | return; | |||
13166 | } | |||
13167 | ||||
13168 | // Provide a specific diagnostic for uninitialized variable | |||
13169 | // definitions with incomplete array type. | |||
13170 | if (Type->isIncompleteArrayType()) { | |||
13171 | Diag(Var->getLocation(), | |||
13172 | diag::err_typecheck_incomplete_array_needs_initializer); | |||
13173 | Var->setInvalidDecl(); | |||
13174 | return; | |||
13175 | } | |||
13176 | ||||
13177 | // Provide a specific diagnostic for uninitialized variable | |||
13178 | // definitions with reference type. | |||
13179 | if (Type->isReferenceType()) { | |||
13180 | Diag(Var->getLocation(), diag::err_reference_var_requires_init) | |||
13181 | << Var << SourceRange(Var->getLocation(), Var->getLocation()); | |||
13182 | Var->setInvalidDecl(); | |||
13183 | return; | |||
13184 | } | |||
13185 | ||||
13186 | // Do not attempt to type-check the default initializer for a | |||
13187 | // variable with dependent type. | |||
13188 | if (Type->isDependentType()) | |||
13189 | return; | |||
13190 | ||||
13191 | if (Var->isInvalidDecl()) | |||
13192 | return; | |||
13193 | ||||
13194 | if (!Var->hasAttr<AliasAttr>()) { | |||
13195 | if (RequireCompleteType(Var->getLocation(), | |||
13196 | Context.getBaseElementType(Type), | |||
13197 | diag::err_typecheck_decl_incomplete_type)) { | |||
13198 | Var->setInvalidDecl(); | |||
13199 | return; | |||
13200 | } | |||
13201 | } else { | |||
13202 | return; | |||
13203 | } | |||
13204 | ||||
13205 | // The variable can not have an abstract class type. | |||
13206 | if (RequireNonAbstractType(Var->getLocation(), Type, | |||
13207 | diag::err_abstract_type_in_decl, | |||
13208 | AbstractVariableType)) { | |||
13209 | Var->setInvalidDecl(); | |||
13210 | return; | |||
13211 | } | |||
13212 | ||||
13213 | // Check for jumps past the implicit initializer. C++0x | |||
13214 | // clarifies that this applies to a "variable with automatic | |||
13215 | // storage duration", not a "local variable". | |||
13216 | // C++11 [stmt.dcl]p3 | |||
13217 | // A program that jumps from a point where a variable with automatic | |||
13218 | // storage duration is not in scope to a point where it is in scope is | |||
13219 | // ill-formed unless the variable has scalar type, class type with a | |||
13220 | // trivial default constructor and a trivial destructor, a cv-qualified | |||
13221 | // version of one of these types, or an array of one of the preceding | |||
13222 | // types and is declared without an initializer. | |||
13223 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { | |||
13224 | if (const RecordType *Record | |||
13225 | = Context.getBaseElementType(Type)->getAs<RecordType>()) { | |||
13226 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); | |||
13227 | // Mark the function (if we're in one) for further checking even if the | |||
13228 | // looser rules of C++11 do not require such checks, so that we can | |||
13229 | // diagnose incompatibilities with C++98. | |||
13230 | if (!CXXRecord->isPOD()) | |||
13231 | setFunctionHasBranchProtectedScope(); | |||
13232 | } | |||
13233 | } | |||
13234 | // In OpenCL, we can't initialize objects in the __local address space, | |||
13235 | // even implicitly, so don't synthesize an implicit initializer. | |||
13236 | if (getLangOpts().OpenCL && | |||
13237 | Var->getType().getAddressSpace() == LangAS::opencl_local) | |||
13238 | return; | |||
13239 | // C++03 [dcl.init]p9: | |||
13240 | // If no initializer is specified for an object, and the | |||
13241 | // object is of (possibly cv-qualified) non-POD class type (or | |||
13242 | // array thereof), the object shall be default-initialized; if | |||
13243 | // the object is of const-qualified type, the underlying class | |||
13244 | // type shall have a user-declared default | |||
13245 | // constructor. Otherwise, if no initializer is specified for | |||
13246 | // a non- static object, the object and its subobjects, if | |||
13247 | // any, have an indeterminate initial value); if the object | |||
13248 | // or any of its subobjects are of const-qualified type, the | |||
13249 | // program is ill-formed. | |||
13250 | // C++0x [dcl.init]p11: | |||
13251 | // If no initializer is specified for an object, the object is | |||
13252 | // default-initialized; [...]. | |||
13253 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); | |||
13254 | InitializationKind Kind | |||
13255 | = InitializationKind::CreateDefault(Var->getLocation()); | |||
13256 | ||||
13257 | InitializationSequence InitSeq(*this, Entity, Kind, None); | |||
13258 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); | |||
13259 | ||||
13260 | if (Init.get()) { | |||
13261 | Var->setInit(MaybeCreateExprWithCleanups(Init.get())); | |||
13262 | // This is important for template substitution. | |||
13263 | Var->setInitStyle(VarDecl::CallInit); | |||
13264 | } else if (Init.isInvalid()) { | |||
13265 | // If default-init fails, attach a recovery-expr initializer to track | |||
13266 | // that initialization was attempted and failed. | |||
13267 | auto RecoveryExpr = | |||
13268 | CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); | |||
13269 | if (RecoveryExpr.get()) | |||
13270 | Var->setInit(RecoveryExpr.get()); | |||
13271 | } | |||
13272 | ||||
13273 | CheckCompleteVariableDeclaration(Var); | |||
13274 | } | |||
13275 | } | |||
13276 | ||||
13277 | void Sema::ActOnCXXForRangeDecl(Decl *D) { | |||
13278 | // If there is no declaration, there was an error parsing it. Ignore it. | |||
13279 | if (!D) | |||
13280 | return; | |||
13281 | ||||
13282 | VarDecl *VD = dyn_cast<VarDecl>(D); | |||
13283 | if (!VD) { | |||
13284 | Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); | |||
13285 | D->setInvalidDecl(); | |||
13286 | return; | |||
13287 | } | |||
13288 | ||||
13289 | VD->setCXXForRangeDecl(true); | |||
13290 | ||||
13291 | // for-range-declaration cannot be given a storage class specifier. | |||
13292 | int Error = -1; | |||
13293 | switch (VD->getStorageClass()) { | |||
13294 | case SC_None: | |||
13295 | break; | |||
13296 | case SC_Extern: | |||
13297 | Error = 0; | |||
13298 | break; | |||
13299 | case SC_Static: | |||
13300 | Error = 1; | |||
13301 | break; | |||
13302 | case SC_PrivateExtern: | |||
13303 | Error = 2; | |||
13304 | break; | |||
13305 | case SC_Auto: | |||
13306 | Error = 3; | |||
13307 | break; | |||
13308 | case SC_Register: | |||
13309 | Error = 4; | |||
13310 | break; | |||
13311 | } | |||
13312 | ||||
13313 | // for-range-declaration cannot be given a storage class specifier con't. | |||
13314 | switch (VD->getTSCSpec()) { | |||
13315 | case TSCS_thread_local: | |||
13316 | Error = 6; | |||
13317 | break; | |||
13318 | case TSCS___thread: | |||
13319 | case TSCS__Thread_local: | |||
13320 | case TSCS_unspecified: | |||
13321 | break; | |||
13322 | } | |||
13323 | ||||
13324 | if (Error != -1) { | |||
13325 | Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) | |||
13326 | << VD << Error; | |||
13327 | D->setInvalidDecl(); | |||
13328 | } | |||
13329 | } | |||
13330 | ||||
13331 | StmtResult Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, | |||
13332 | IdentifierInfo *Ident, | |||
13333 | ParsedAttributes &Attrs) { | |||
13334 | // C++1y [stmt.iter]p1: | |||
13335 | // A range-based for statement of the form | |||
13336 | // for ( for-range-identifier : for-range-initializer ) statement | |||
13337 | // is equivalent to | |||
13338 | // for ( auto&& for-range-identifier : for-range-initializer ) statement | |||
13339 | DeclSpec DS(Attrs.getPool().getFactory()); | |||
13340 | ||||
13341 | const char *PrevSpec; | |||
13342 | unsigned DiagID; | |||
13343 | DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, | |||
13344 | getPrintingPolicy()); | |||
13345 | ||||
13346 | Declarator D(DS, DeclaratorContext::ForInit); | |||
13347 | D.SetIdentifier(Ident, IdentLoc); | |||
13348 | D.takeAttributes(Attrs); | |||
13349 | ||||
13350 | D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), | |||
13351 | IdentLoc); | |||
13352 | Decl *Var = ActOnDeclarator(S, D); | |||
13353 | cast<VarDecl>(Var)->setCXXForRangeDecl(true); | |||
13354 | FinalizeDeclaration(Var); | |||
13355 | return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, | |||
13356 | Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd() | |||
13357 | : IdentLoc); | |||
13358 | } | |||
13359 | ||||
13360 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { | |||
13361 | if (var->isInvalidDecl()) return; | |||
13362 | ||||
13363 | MaybeAddCUDAConstantAttr(var); | |||
13364 | ||||
13365 | if (getLangOpts().OpenCL) { | |||
13366 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an | |||
13367 | // initialiser | |||
13368 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && | |||
13369 | !var->hasInit()) { | |||
13370 | Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) | |||
13371 | << 1 /*Init*/; | |||
13372 | var->setInvalidDecl(); | |||
13373 | return; | |||
13374 | } | |||
13375 | } | |||
13376 | ||||
13377 | // In Objective-C, don't allow jumps past the implicit initialization of a | |||
13378 | // local retaining variable. | |||
13379 | if (getLangOpts().ObjC && | |||
13380 | var->hasLocalStorage()) { | |||
13381 | switch (var->getType().getObjCLifetime()) { | |||
13382 | case Qualifiers::OCL_None: | |||
13383 | case Qualifiers::OCL_ExplicitNone: | |||
13384 | case Qualifiers::OCL_Autoreleasing: | |||
13385 | break; | |||
13386 | ||||
13387 | case Qualifiers::OCL_Weak: | |||
13388 | case Qualifiers::OCL_Strong: | |||
13389 | setFunctionHasBranchProtectedScope(); | |||
13390 | break; | |||
13391 | } | |||
13392 | } | |||
13393 | ||||
13394 | if (var->hasLocalStorage() && | |||
13395 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | |||
13396 | setFunctionHasBranchProtectedScope(); | |||
13397 | ||||
13398 | // Warn about externally-visible variables being defined without a | |||
13399 | // prior declaration. We only want to do this for global | |||
13400 | // declarations, but we also specifically need to avoid doing it for | |||
13401 | // class members because the linkage of an anonymous class can | |||
13402 | // change if it's later given a typedef name. | |||
13403 | if (var->isThisDeclarationADefinition() && | |||
13404 | var->getDeclContext()->getRedeclContext()->isFileContext() && | |||
13405 | var->isExternallyVisible() && var->hasLinkage() && | |||
13406 | !var->isInline() && !var->getDescribedVarTemplate() && | |||
13407 | !isa<VarTemplatePartialSpecializationDecl>(var) && | |||
13408 | !isTemplateInstantiation(var->getTemplateSpecializationKind()) && | |||
13409 | !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, | |||
13410 | var->getLocation())) { | |||
13411 | // Find a previous declaration that's not a definition. | |||
13412 | VarDecl *prev = var->getPreviousDecl(); | |||
13413 | while (prev && prev->isThisDeclarationADefinition()) | |||
13414 | prev = prev->getPreviousDecl(); | |||
13415 | ||||
13416 | if (!prev) { | |||
13417 | Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; | |||
13418 | Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | |||
13419 | << /* variable */ 0; | |||
13420 | } | |||
13421 | } | |||
13422 | ||||
13423 | // Cache the result of checking for constant initialization. | |||
13424 | Optional<bool> CacheHasConstInit; | |||
13425 | const Expr *CacheCulprit = nullptr; | |||
13426 | auto checkConstInit = [&]() mutable { | |||
13427 | if (!CacheHasConstInit) | |||
13428 | CacheHasConstInit = var->getInit()->isConstantInitializer( | |||
13429 | Context, var->getType()->isReferenceType(), &CacheCulprit); | |||
13430 | return *CacheHasConstInit; | |||
13431 | }; | |||
13432 | ||||
13433 | if (var->getTLSKind() == VarDecl::TLS_Static) { | |||
13434 | if (var->getType().isDestructedType()) { | |||
13435 | // GNU C++98 edits for __thread, [basic.start.term]p3: | |||
13436 | // The type of an object with thread storage duration shall not | |||
13437 | // have a non-trivial destructor. | |||
13438 | Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); | |||
13439 | if (getLangOpts().CPlusPlus11) | |||
13440 | Diag(var->getLocation(), diag::note_use_thread_local); | |||
13441 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { | |||
13442 | if (!checkConstInit()) { | |||
13443 | // GNU C++98 edits for __thread, [basic.start.init]p4: | |||
13444 | // An object of thread storage duration shall not require dynamic | |||
13445 | // initialization. | |||
13446 | // FIXME: Need strict checking here. | |||
13447 | Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) | |||
13448 | << CacheCulprit->getSourceRange(); | |||
13449 | if (getLangOpts().CPlusPlus11) | |||
13450 | Diag(var->getLocation(), diag::note_use_thread_local); | |||
13451 | } | |||
13452 | } | |||
13453 | } | |||
13454 | ||||
13455 | ||||
13456 | if (!var->getType()->isStructureType() && var->hasInit() && | |||
13457 | isa<InitListExpr>(var->getInit())) { | |||
13458 | const auto *ILE = cast<InitListExpr>(var->getInit()); | |||
13459 | unsigned NumInits = ILE->getNumInits(); | |||
13460 | if (NumInits > 2) | |||
13461 | for (unsigned I = 0; I < NumInits; ++I) { | |||
13462 | const auto *Init = ILE->getInit(I); | |||
13463 | if (!Init) | |||
13464 | break; | |||
13465 | const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); | |||
13466 | if (!SL) | |||
13467 | break; | |||
13468 | ||||
13469 | unsigned NumConcat = SL->getNumConcatenated(); | |||
13470 | // Diagnose missing comma in string array initialization. | |||
13471 | // Do not warn when all the elements in the initializer are concatenated | |||
13472 | // together. Do not warn for macros too. | |||
13473 | if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { | |||
13474 | bool OnlyOneMissingComma = true; | |||
13475 | for (unsigned J = I + 1; J < NumInits; ++J) { | |||
13476 | const auto *Init = ILE->getInit(J); | |||
13477 | if (!Init) | |||
13478 | break; | |||
13479 | const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); | |||
13480 | if (!SLJ || SLJ->getNumConcatenated() > 1) { | |||
13481 | OnlyOneMissingComma = false; | |||
13482 | break; | |||
13483 | } | |||
13484 | } | |||
13485 | ||||
13486 | if (OnlyOneMissingComma) { | |||
13487 | SmallVector<FixItHint, 1> Hints; | |||
13488 | for (unsigned i = 0; i < NumConcat - 1; ++i) | |||
13489 | Hints.push_back(FixItHint::CreateInsertion( | |||
13490 | PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); | |||
13491 | ||||
13492 | Diag(SL->getStrTokenLoc(1), | |||
13493 | diag::warn_concatenated_literal_array_init) | |||
13494 | << Hints; | |||
13495 | Diag(SL->getBeginLoc(), | |||
13496 | diag::note_concatenated_string_literal_silence); | |||
13497 | } | |||
13498 | // In any case, stop now. | |||
13499 | break; | |||
13500 | } | |||
13501 | } | |||
13502 | } | |||
13503 | ||||
13504 | ||||
13505 | QualType type = var->getType(); | |||
13506 | ||||
13507 | if (var->hasAttr<BlocksAttr>()) | |||
13508 | getCurFunction()->addByrefBlockVar(var); | |||
13509 | ||||
13510 | Expr *Init = var->getInit(); | |||
13511 | bool GlobalStorage = var->hasGlobalStorage(); | |||
13512 | bool IsGlobal = GlobalStorage && !var->isStaticLocal(); | |||
13513 | QualType baseType = Context.getBaseElementType(type); | |||
13514 | bool HasConstInit = true; | |||
13515 | ||||
13516 | // Check whether the initializer is sufficiently constant. | |||
13517 | if (getLangOpts().CPlusPlus && !type->isDependentType() && Init && | |||
13518 | !Init->isValueDependent() && | |||
13519 | (GlobalStorage || var->isConstexpr() || | |||
13520 | var->mightBeUsableInConstantExpressions(Context))) { | |||
13521 | // If this variable might have a constant initializer or might be usable in | |||
13522 | // constant expressions, check whether or not it actually is now. We can't | |||
13523 | // do this lazily, because the result might depend on things that change | |||
13524 | // later, such as which constexpr functions happen to be defined. | |||
13525 | SmallVector<PartialDiagnosticAt, 8> Notes; | |||
13526 | if (!getLangOpts().CPlusPlus11) { | |||
13527 | // Prior to C++11, in contexts where a constant initializer is required, | |||
13528 | // the set of valid constant initializers is described by syntactic rules | |||
13529 | // in [expr.const]p2-6. | |||
13530 | // FIXME: Stricter checking for these rules would be useful for constinit / | |||
13531 | // -Wglobal-constructors. | |||
13532 | HasConstInit = checkConstInit(); | |||
13533 | ||||
13534 | // Compute and cache the constant value, and remember that we have a | |||
13535 | // constant initializer. | |||
13536 | if (HasConstInit) { | |||
13537 | (void)var->checkForConstantInitialization(Notes); | |||
13538 | Notes.clear(); | |||
13539 | } else if (CacheCulprit) { | |||
13540 | Notes.emplace_back(CacheCulprit->getExprLoc(), | |||
13541 | PDiag(diag::note_invalid_subexpr_in_const_expr)); | |||
13542 | Notes.back().second << CacheCulprit->getSourceRange(); | |||
13543 | } | |||
13544 | } else { | |||
13545 | // Evaluate the initializer to see if it's a constant initializer. | |||
13546 | HasConstInit = var->checkForConstantInitialization(Notes); | |||
13547 | } | |||
13548 | ||||
13549 | if (HasConstInit) { | |||
13550 | // FIXME: Consider replacing the initializer with a ConstantExpr. | |||
13551 | } else if (var->isConstexpr()) { | |||
13552 | SourceLocation DiagLoc = var->getLocation(); | |||
13553 | // If the note doesn't add any useful information other than a source | |||
13554 | // location, fold it into the primary diagnostic. | |||
13555 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | |||
13556 | diag::note_invalid_subexpr_in_const_expr) { | |||
13557 | DiagLoc = Notes[0].first; | |||
13558 | Notes.clear(); | |||
13559 | } | |||
13560 | Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) | |||
13561 | << var << Init->getSourceRange(); | |||
13562 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) | |||
13563 | Diag(Notes[I].first, Notes[I].second); | |||
13564 | } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) { | |||
13565 | auto *Attr = var->getAttr<ConstInitAttr>(); | |||
13566 | Diag(var->getLocation(), diag::err_require_constant_init_failed) | |||
13567 | << Init->getSourceRange(); | |||
13568 | Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here) | |||
13569 | << Attr->getRange() << Attr->isConstinit(); | |||
13570 | for (auto &it : Notes) | |||
13571 | Diag(it.first, it.second); | |||
13572 | } else if (IsGlobal && | |||
13573 | !getDiagnostics().isIgnored(diag::warn_global_constructor, | |||
13574 | var->getLocation())) { | |||
13575 | // Warn about globals which don't have a constant initializer. Don't | |||
13576 | // warn about globals with a non-trivial destructor because we already | |||
13577 | // warned about them. | |||
13578 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); | |||
13579 | if (!(RD && !RD->hasTrivialDestructor())) { | |||
13580 | // checkConstInit() here permits trivial default initialization even in | |||
13581 | // C++11 onwards, where such an initializer is not a constant initializer | |||
13582 | // but nonetheless doesn't require a global constructor. | |||
13583 | if (!checkConstInit()) | |||
13584 | Diag(var->getLocation(), diag::warn_global_constructor) | |||
13585 | << Init->getSourceRange(); | |||
13586 | } | |||
13587 | } | |||
13588 | } | |||
13589 | ||||
13590 | // Apply section attributes and pragmas to global variables. | |||
13591 | if (GlobalStorage && var->isThisDeclarationADefinition() && | |||
13592 | !inTemplateInstantiation()) { | |||
13593 | PragmaStack<StringLiteral *> *Stack = nullptr; | |||
13594 | int SectionFlags = ASTContext::PSF_Read; | |||
13595 | if (var->getType().isConstQualified()) { | |||
13596 | if (HasConstInit) | |||
13597 | Stack = &ConstSegStack; | |||
13598 | else { | |||
13599 | Stack = &BSSSegStack; | |||
13600 | SectionFlags |= ASTContext::PSF_Write; | |||
13601 | } | |||
13602 | } else if (var->hasInit() && HasConstInit) { | |||
13603 | Stack = &DataSegStack; | |||
13604 | SectionFlags |= ASTContext::PSF_Write; | |||
13605 | } else { | |||
13606 | Stack = &BSSSegStack; | |||
13607 | SectionFlags |= ASTContext::PSF_Write; | |||
13608 | } | |||
13609 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { | |||
13610 | if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) | |||
13611 | SectionFlags |= ASTContext::PSF_Implicit; | |||
13612 | UnifySection(SA->getName(), SectionFlags, var); | |||
13613 | } else if (Stack->CurrentValue) { | |||
13614 | SectionFlags |= ASTContext::PSF_Implicit; | |||
13615 | auto SectionName = Stack->CurrentValue->getString(); | |||
13616 | var->addAttr(SectionAttr::CreateImplicit( | |||
13617 | Context, SectionName, Stack->CurrentPragmaLocation, | |||
13618 | AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); | |||
13619 | if (UnifySection(SectionName, SectionFlags, var)) | |||
13620 | var->dropAttr<SectionAttr>(); | |||
13621 | } | |||
13622 | ||||
13623 | // Apply the init_seg attribute if this has an initializer. If the | |||
13624 | // initializer turns out to not be dynamic, we'll end up ignoring this | |||
13625 | // attribute. | |||
13626 | if (CurInitSeg && var->getInit()) | |||
13627 | var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), | |||
13628 | CurInitSegLoc, | |||
13629 | AttributeCommonInfo::AS_Pragma)); | |||
13630 | } | |||
13631 | ||||
13632 | // All the following checks are C++ only. | |||
13633 | if (!getLangOpts().CPlusPlus) { | |||
13634 | // If this variable must be emitted, add it as an initializer for the | |||
13635 | // current module. | |||
13636 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | |||
13637 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | |||
13638 | return; | |||
13639 | } | |||
13640 | ||||
13641 | // Require the destructor. | |||
13642 | if (!type->isDependentType()) | |||
13643 | if (const RecordType *recordType = baseType->getAs<RecordType>()) | |||
13644 | FinalizeVarWithDestructor(var, recordType); | |||
13645 | ||||
13646 | // If this variable must be emitted, add it as an initializer for the current | |||
13647 | // module. | |||
13648 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | |||
13649 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | |||
13650 | ||||
13651 | // Build the bindings if this is a structured binding declaration. | |||
13652 | if (auto *DD = dyn_cast<DecompositionDecl>(var)) | |||
13653 | CheckCompleteDecompositionDeclaration(DD); | |||
13654 | } | |||
13655 | ||||
13656 | /// Check if VD needs to be dllexport/dllimport due to being in a | |||
13657 | /// dllexport/import function. | |||
13658 | void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { | |||
13659 | assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0) : __assert_fail ("VD->isStaticLocal()", "clang/lib/Sema/SemaDecl.cpp" , 13659, __extension__ __PRETTY_FUNCTION__)); | |||
13660 | ||||
13661 | auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | |||
13662 | ||||
13663 | // Find outermost function when VD is in lambda function. | |||
13664 | while (FD && !getDLLAttr(FD) && | |||
13665 | !FD->hasAttr<DLLExportStaticLocalAttr>() && | |||
13666 | !FD->hasAttr<DLLImportStaticLocalAttr>()) { | |||
13667 | FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); | |||
13668 | } | |||
13669 | ||||
13670 | if (!FD) | |||
13671 | return; | |||
13672 | ||||
13673 | // Static locals inherit dll attributes from their function. | |||
13674 | if (Attr *A = getDLLAttr(FD)) { | |||
13675 | auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); | |||
13676 | NewAttr->setInherited(true); | |||
13677 | VD->addAttr(NewAttr); | |||
13678 | } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { | |||
13679 | auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); | |||
13680 | NewAttr->setInherited(true); | |||
13681 | VD->addAttr(NewAttr); | |||
13682 | ||||
13683 | // Export this function to enforce exporting this static variable even | |||
13684 | // if it is not used in this compilation unit. | |||
13685 | if (!FD->hasAttr<DLLExportAttr>()) | |||
13686 | FD->addAttr(NewAttr); | |||
13687 | ||||
13688 | } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { | |||
13689 | auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); | |||
13690 | NewAttr->setInherited(true); | |||
13691 | VD->addAttr(NewAttr); | |||
13692 | } | |||
13693 | } | |||
13694 | ||||
13695 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform | |||
13696 | /// any semantic actions necessary after any initializer has been attached. | |||
13697 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { | |||
13698 | // Note that we are no longer parsing the initializer for this declaration. | |||
13699 | ParsingInitForAutoVars.erase(ThisDecl); | |||
13700 | ||||
13701 | VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); | |||
13702 | if (!VD) | |||
13703 | return; | |||
13704 | ||||
13705 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active | |||
13706 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && | |||
13707 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { | |||
13708 | if (PragmaClangBSSSection.Valid) | |||
13709 | VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( | |||
13710 | Context, PragmaClangBSSSection.SectionName, | |||
13711 | PragmaClangBSSSection.PragmaLocation, | |||
13712 | AttributeCommonInfo::AS_Pragma)); | |||
13713 | if (PragmaClangDataSection.Valid) | |||
13714 | VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( | |||
13715 | Context, PragmaClangDataSection.SectionName, | |||
13716 | PragmaClangDataSection.PragmaLocation, | |||
13717 | AttributeCommonInfo::AS_Pragma)); | |||
13718 | if (PragmaClangRodataSection.Valid) | |||
13719 | VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( | |||
13720 | Context, PragmaClangRodataSection.SectionName, | |||
13721 | PragmaClangRodataSection.PragmaLocation, | |||
13722 | AttributeCommonInfo::AS_Pragma)); | |||
13723 | if (PragmaClangRelroSection.Valid) | |||
13724 | VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( | |||
13725 | Context, PragmaClangRelroSection.SectionName, | |||
13726 | PragmaClangRelroSection.PragmaLocation, | |||
13727 | AttributeCommonInfo::AS_Pragma)); | |||
13728 | } | |||
13729 | ||||
13730 | if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { | |||
13731 | for (auto *BD : DD->bindings()) { | |||
13732 | FinalizeDeclaration(BD); | |||
13733 | } | |||
13734 | } | |||
13735 | ||||
13736 | checkAttributesAfterMerging(*this, *VD); | |||
13737 | ||||
13738 | // Perform TLS alignment check here after attributes attached to the variable | |||
13739 | // which may affect the alignment have been processed. Only perform the check | |||
13740 | // if the target has a maximum TLS alignment (zero means no constraints). | |||
13741 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { | |||
13742 | // Protect the check so that it's not performed on dependent types and | |||
13743 | // dependent alignments (we can't determine the alignment in that case). | |||
13744 | if (VD->getTLSKind() && !VD->hasDependentAlignment()) { | |||
13745 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); | |||
13746 | if (Context.getDeclAlign(VD) > MaxAlignChars) { | |||
13747 | Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) | |||
13748 | << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD | |||
13749 | << (unsigned)MaxAlignChars.getQuantity(); | |||
13750 | } | |||
13751 | } | |||
13752 | } | |||
13753 | ||||
13754 | if (VD->isStaticLocal()) | |||
13755 | CheckStaticLocalForDllExport(VD); | |||
13756 | ||||
13757 | // Perform check for initializers of device-side global variables. | |||
13758 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA | |||
13759 | // 7.5). We must also apply the same checks to all __shared__ | |||
13760 | // variables whether they are local or not. CUDA also allows | |||
13761 | // constant initializers for __constant__ and __device__ variables. | |||
13762 | if (getLangOpts().CUDA) | |||
13763 | checkAllowedCUDAInitializer(VD); | |||
13764 | ||||
13765 | // Grab the dllimport or dllexport attribute off of the VarDecl. | |||
13766 | const InheritableAttr *DLLAttr = getDLLAttr(VD); | |||
13767 | ||||
13768 | // Imported static data members cannot be defined out-of-line. | |||
13769 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { | |||
13770 | if (VD->isStaticDataMember() && VD->isOutOfLine() && | |||
13771 | VD->isThisDeclarationADefinition()) { | |||
13772 | // We allow definitions of dllimport class template static data members | |||
13773 | // with a warning. | |||
13774 | CXXRecordDecl *Context = | |||
13775 | cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); | |||
13776 | bool IsClassTemplateMember = | |||
13777 | isa<ClassTemplatePartialSpecializationDecl>(Context) || | |||
13778 | Context->getDescribedClassTemplate(); | |||
13779 | ||||
13780 | Diag(VD->getLocation(), | |||
13781 | IsClassTemplateMember | |||
13782 | ? diag::warn_attribute_dllimport_static_field_definition | |||
13783 | : diag::err_attribute_dllimport_static_field_definition); | |||
13784 | Diag(IA->getLocation(), diag::note_attribute); | |||
13785 | if (!IsClassTemplateMember) | |||
13786 | VD->setInvalidDecl(); | |||
13787 | } | |||
13788 | } | |||
13789 | ||||
13790 | // dllimport/dllexport variables cannot be thread local, their TLS index | |||
13791 | // isn't exported with the variable. | |||
13792 | if (DLLAttr && VD->getTLSKind()) { | |||
13793 | auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | |||
13794 | if (F && getDLLAttr(F)) { | |||
13795 | assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0) : __assert_fail ("VD->isStaticLocal()", "clang/lib/Sema/SemaDecl.cpp" , 13795, __extension__ __PRETTY_FUNCTION__)); | |||
13796 | // But if this is a static local in a dlimport/dllexport function, the | |||
13797 | // function will never be inlined, which means the var would never be | |||
13798 | // imported, so having it marked import/export is safe. | |||
13799 | } else { | |||
13800 | Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD | |||
13801 | << DLLAttr; | |||
13802 | VD->setInvalidDecl(); | |||
13803 | } | |||
13804 | } | |||
13805 | ||||
13806 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { | |||
13807 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { | |||
13808 | Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) | |||
13809 | << Attr; | |||
13810 | VD->dropAttr<UsedAttr>(); | |||
13811 | } | |||
13812 | } | |||
13813 | if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) { | |||
13814 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { | |||
13815 | Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition) | |||
13816 | << Attr; | |||
13817 | VD->dropAttr<RetainAttr>(); | |||
13818 | } | |||
13819 | } | |||
13820 | ||||
13821 | const DeclContext *DC = VD->getDeclContext(); | |||
13822 | // If there's a #pragma GCC visibility in scope, and this isn't a class | |||
13823 | // member, set the visibility of this variable. | |||
13824 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) | |||
13825 | AddPushedVisibilityAttribute(VD); | |||
13826 | ||||
13827 | // FIXME: Warn on unused var template partial specializations. | |||
13828 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) | |||
13829 | MarkUnusedFileScopedDecl(VD); | |||
13830 | ||||
13831 | // Now we have parsed the initializer and can update the table of magic | |||
13832 | // tag values. | |||
13833 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || | |||
13834 | !VD->getType()->isIntegralOrEnumerationType()) | |||
13835 | return; | |||
13836 | ||||
13837 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { | |||
13838 | const Expr *MagicValueExpr = VD->getInit(); | |||
13839 | if (!MagicValueExpr) { | |||
13840 | continue; | |||
13841 | } | |||
13842 | Optional<llvm::APSInt> MagicValueInt; | |||
13843 | if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { | |||
13844 | Diag(I->getRange().getBegin(), | |||
13845 | diag::err_type_tag_for_datatype_not_ice) | |||
13846 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | |||
13847 | continue; | |||
13848 | } | |||
13849 | if (MagicValueInt->getActiveBits() > 64) { | |||
13850 | Diag(I->getRange().getBegin(), | |||
13851 | diag::err_type_tag_for_datatype_too_large) | |||
13852 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | |||
13853 | continue; | |||
13854 | } | |||
13855 | uint64_t MagicValue = MagicValueInt->getZExtValue(); | |||
13856 | RegisterTypeTagForDatatype(I->getArgumentKind(), | |||
13857 | MagicValue, | |||
13858 | I->getMatchingCType(), | |||
13859 | I->getLayoutCompatible(), | |||
13860 | I->getMustBeNull()); | |||
13861 | } | |||
13862 | } | |||
13863 | ||||
13864 | static bool hasDeducedAuto(DeclaratorDecl *DD) { | |||
13865 | auto *VD = dyn_cast<VarDecl>(DD); | |||
13866 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); | |||
13867 | } | |||
13868 | ||||
13869 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, | |||
13870 | ArrayRef<Decl *> Group) { | |||
13871 | SmallVector<Decl*, 8> Decls; | |||
13872 | ||||
13873 | if (DS.isTypeSpecOwned()) | |||
13874 | Decls.push_back(DS.getRepAsDecl()); | |||
13875 | ||||
13876 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; | |||
13877 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; | |||
13878 | bool DiagnosedMultipleDecomps = false; | |||
13879 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; | |||
13880 | bool DiagnosedNonDeducedAuto = false; | |||
13881 | ||||
13882 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | |||
13883 | if (Decl *D = Group[i]) { | |||
13884 | // For declarators, there are some additional syntactic-ish checks we need | |||
13885 | // to perform. | |||
13886 | if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { | |||
13887 | if (!FirstDeclaratorInGroup) | |||
13888 | FirstDeclaratorInGroup = DD; | |||
13889 | if (!FirstDecompDeclaratorInGroup) | |||
13890 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); | |||
13891 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && | |||
13892 | !hasDeducedAuto(DD)) | |||
13893 | FirstNonDeducedAutoInGroup = DD; | |||
13894 | ||||
13895 | if (FirstDeclaratorInGroup != DD) { | |||
13896 | // A decomposition declaration cannot be combined with any other | |||
13897 | // declaration in the same group. | |||
13898 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { | |||
13899 | Diag(FirstDecompDeclaratorInGroup->getLocation(), | |||
13900 | diag::err_decomp_decl_not_alone) | |||
13901 | << FirstDeclaratorInGroup->getSourceRange() | |||
13902 | << DD->getSourceRange(); | |||
13903 | DiagnosedMultipleDecomps = true; | |||
13904 | } | |||
13905 | ||||
13906 | // A declarator that uses 'auto' in any way other than to declare a | |||
13907 | // variable with a deduced type cannot be combined with any other | |||
13908 | // declarator in the same group. | |||
13909 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { | |||
13910 | Diag(FirstNonDeducedAutoInGroup->getLocation(), | |||
13911 | diag::err_auto_non_deduced_not_alone) | |||
13912 | << FirstNonDeducedAutoInGroup->getType() | |||
13913 | ->hasAutoForTrailingReturnType() | |||
13914 | << FirstDeclaratorInGroup->getSourceRange() | |||
13915 | << DD->getSourceRange(); | |||
13916 | DiagnosedNonDeducedAuto = true; | |||
13917 | } | |||
13918 | } | |||
13919 | } | |||
13920 | ||||
13921 | Decls.push_back(D); | |||
13922 | } | |||
13923 | } | |||
13924 | ||||
13925 | if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { | |||
13926 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { | |||
13927 | handleTagNumbering(Tag, S); | |||
13928 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && | |||
13929 | getLangOpts().CPlusPlus) | |||
13930 | Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); | |||
13931 | } | |||
13932 | } | |||
13933 | ||||
13934 | return BuildDeclaratorGroup(Decls); | |||
13935 | } | |||
13936 | ||||
13937 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration | |||
13938 | /// group, performing any necessary semantic checking. | |||
13939 | Sema::DeclGroupPtrTy | |||
13940 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { | |||
13941 | // C++14 [dcl.spec.auto]p7: (DR1347) | |||
13942 | // If the type that replaces the placeholder type is not the same in each | |||
13943 | // deduction, the program is ill-formed. | |||
13944 | if (Group.size() > 1) { | |||
13945 | QualType Deduced; | |||
13946 | VarDecl *DeducedDecl = nullptr; | |||
13947 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | |||
13948 | VarDecl *D = dyn_cast<VarDecl>(Group[i]); | |||
13949 | if (!D || D->isInvalidDecl()) | |||
13950 | break; | |||
13951 | DeducedType *DT = D->getType()->getContainedDeducedType(); | |||
13952 | if (!DT || DT->getDeducedType().isNull()) | |||
13953 | continue; | |||
13954 | if (Deduced.isNull()) { | |||
13955 | Deduced = DT->getDeducedType(); | |||
13956 | DeducedDecl = D; | |||
13957 | } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { | |||
13958 | auto *AT = dyn_cast<AutoType>(DT); | |||
13959 | auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), | |||
13960 | diag::err_auto_different_deductions) | |||
13961 | << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced | |||
13962 | << DeducedDecl->getDeclName() << DT->getDeducedType() | |||
13963 | << D->getDeclName(); | |||
13964 | if (DeducedDecl->hasInit()) | |||
13965 | Dia << DeducedDecl->getInit()->getSourceRange(); | |||
13966 | if (D->getInit()) | |||
13967 | Dia << D->getInit()->getSourceRange(); | |||
13968 | D->setInvalidDecl(); | |||
13969 | break; | |||
13970 | } | |||
13971 | } | |||
13972 | } | |||
13973 | ||||
13974 | ActOnDocumentableDecls(Group); | |||
13975 | ||||
13976 | return DeclGroupPtrTy::make( | |||
13977 | DeclGroupRef::Create(Context, Group.data(), Group.size())); | |||
13978 | } | |||
13979 | ||||
13980 | void Sema::ActOnDocumentableDecl(Decl *D) { | |||
13981 | ActOnDocumentableDecls(D); | |||
13982 | } | |||
13983 | ||||
13984 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { | |||
13985 | // Don't parse the comment if Doxygen diagnostics are ignored. | |||
13986 | if (Group.empty() || !Group[0]) | |||
13987 | return; | |||
13988 | ||||
13989 | if (Diags.isIgnored(diag::warn_doc_param_not_found, | |||
13990 | Group[0]->getLocation()) && | |||
13991 | Diags.isIgnored(diag::warn_unknown_comment_command_name, | |||
13992 | Group[0]->getLocation())) | |||
13993 | return; | |||
13994 | ||||
13995 | if (Group.size() >= 2) { | |||
13996 | // This is a decl group. Normally it will contain only declarations | |||
13997 | // produced from declarator list. But in case we have any definitions or | |||
13998 | // additional declaration references: | |||
13999 | // 'typedef struct S {} S;' | |||
14000 | // 'typedef struct S *S;' | |||
14001 | // 'struct S *pS;' | |||
14002 | // FinalizeDeclaratorGroup adds these as separate declarations. | |||
14003 | Decl *MaybeTagDecl = Group[0]; | |||
14004 | if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { | |||
14005 | Group = Group.slice(1); | |||
14006 | } | |||
14007 | } | |||
14008 | ||||
14009 | // FIMXE: We assume every Decl in the group is in the same file. | |||
14010 | // This is false when preprocessor constructs the group from decls in | |||
14011 | // different files (e. g. macros or #include). | |||
14012 | Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); | |||
14013 | } | |||
14014 | ||||
14015 | /// Common checks for a parameter-declaration that should apply to both function | |||
14016 | /// parameters and non-type template parameters. | |||
14017 | void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { | |||
14018 | // Check that there are no default arguments inside the type of this | |||
14019 | // parameter. | |||
14020 | if (getLangOpts().CPlusPlus) | |||
14021 | CheckExtraCXXDefaultArguments(D); | |||
14022 | ||||
14023 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). | |||
14024 | if (D.getCXXScopeSpec().isSet()) { | |||
14025 | Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) | |||
14026 | << D.getCXXScopeSpec().getRange(); | |||
14027 | } | |||
14028 | ||||
14029 | // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a | |||
14030 | // simple identifier except [...irrelevant cases...]. | |||
14031 | switch (D.getName().getKind()) { | |||
14032 | case UnqualifiedIdKind::IK_Identifier: | |||
14033 | break; | |||
14034 | ||||
14035 | case UnqualifiedIdKind::IK_OperatorFunctionId: | |||
14036 | case UnqualifiedIdKind::IK_ConversionFunctionId: | |||
14037 | case UnqualifiedIdKind::IK_LiteralOperatorId: | |||
14038 | case UnqualifiedIdKind::IK_ConstructorName: | |||
14039 | case UnqualifiedIdKind::IK_DestructorName: | |||
14040 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | |||
14041 | case UnqualifiedIdKind::IK_DeductionGuideName: | |||
14042 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) | |||
14043 | << GetNameForDeclarator(D).getName(); | |||
14044 | break; | |||
14045 | ||||
14046 | case UnqualifiedIdKind::IK_TemplateId: | |||
14047 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | |||
14048 | // GetNameForDeclarator would not produce a useful name in this case. | |||
14049 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); | |||
14050 | break; | |||
14051 | } | |||
14052 | } | |||
14053 | ||||
14054 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() | |||
14055 | /// to introduce parameters into function prototype scope. | |||
14056 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { | |||
14057 | const DeclSpec &DS = D.getDeclSpec(); | |||
14058 | ||||
14059 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. | |||
14060 | ||||
14061 | // C++03 [dcl.stc]p2 also permits 'auto'. | |||
14062 | StorageClass SC = SC_None; | |||
14063 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { | |||
14064 | SC = SC_Register; | |||
14065 | // In C++11, the 'register' storage class specifier is deprecated. | |||
14066 | // In C++17, it is not allowed, but we tolerate it as an extension. | |||
14067 | if (getLangOpts().CPlusPlus11) { | |||
14068 | Diag(DS.getStorageClassSpecLoc(), | |||
14069 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | |||
14070 | : diag::warn_deprecated_register) | |||
14071 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | |||
14072 | } | |||
14073 | } else if (getLangOpts().CPlusPlus && | |||
14074 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { | |||
14075 | SC = SC_Auto; | |||
14076 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { | |||
14077 | Diag(DS.getStorageClassSpecLoc(), | |||
14078 | diag::err_invalid_storage_class_in_func_decl); | |||
14079 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | |||
14080 | } | |||
14081 | ||||
14082 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | |||
14083 | Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) | |||
14084 | << DeclSpec::getSpecifierName(TSCS); | |||
14085 | if (DS.isInlineSpecified()) | |||
14086 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | |||
14087 | << getLangOpts().CPlusPlus17; | |||
14088 | if (DS.hasConstexprSpecifier()) | |||
14089 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) | |||
14090 | << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier()); | |||
14091 | ||||
14092 | DiagnoseFunctionSpecifiers(DS); | |||
14093 | ||||
14094 | CheckFunctionOrTemplateParamDeclarator(S, D); | |||
14095 | ||||
14096 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
14097 | QualType parmDeclType = TInfo->getType(); | |||
14098 | ||||
14099 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); | |||
14100 | IdentifierInfo *II = D.getIdentifier(); | |||
14101 | if (II) { | |||
14102 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, | |||
14103 | ForVisibleRedeclaration); | |||
14104 | LookupName(R, S); | |||
14105 | if (R.isSingleResult()) { | |||
14106 | NamedDecl *PrevDecl = R.getFoundDecl(); | |||
14107 | if (PrevDecl->isTemplateParameter()) { | |||
14108 | // Maybe we will complain about the shadowed template parameter. | |||
14109 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
14110 | // Just pretend that we didn't see the previous declaration. | |||
14111 | PrevDecl = nullptr; | |||
14112 | } else if (S->isDeclScope(PrevDecl)) { | |||
14113 | Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; | |||
14114 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
14115 | ||||
14116 | // Recover by removing the name | |||
14117 | II = nullptr; | |||
14118 | D.SetIdentifier(nullptr, D.getIdentifierLoc()); | |||
14119 | D.setInvalidType(true); | |||
14120 | } | |||
14121 | } | |||
14122 | } | |||
14123 | ||||
14124 | // Temporarily put parameter variables in the translation unit, not | |||
14125 | // the enclosing context. This prevents them from accidentally | |||
14126 | // looking like class members in C++. | |||
14127 | ParmVarDecl *New = | |||
14128 | CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), | |||
14129 | D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); | |||
14130 | ||||
14131 | if (D.isInvalidType()) | |||
14132 | New->setInvalidDecl(); | |||
14133 | ||||
14134 | assert(S->isFunctionPrototypeScope())(static_cast <bool> (S->isFunctionPrototypeScope()) ? void (0) : __assert_fail ("S->isFunctionPrototypeScope()" , "clang/lib/Sema/SemaDecl.cpp", 14134, __extension__ __PRETTY_FUNCTION__ )); | |||
14135 | assert(S->getFunctionPrototypeDepth() >= 1)(static_cast <bool> (S->getFunctionPrototypeDepth() >= 1) ? void (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1" , "clang/lib/Sema/SemaDecl.cpp", 14135, __extension__ __PRETTY_FUNCTION__ )); | |||
14136 | New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, | |||
14137 | S->getNextFunctionPrototypeIndex()); | |||
14138 | ||||
14139 | // Add the parameter declaration into this scope. | |||
14140 | S->AddDecl(New); | |||
14141 | if (II) | |||
14142 | IdResolver.AddDecl(New); | |||
14143 | ||||
14144 | ProcessDeclAttributes(S, New, D); | |||
14145 | ||||
14146 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
14147 | Diag(New->getLocation(), diag::err_module_private_local) | |||
14148 | << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
14149 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | |||
14150 | ||||
14151 | if (New->hasAttr<BlocksAttr>()) { | |||
14152 | Diag(New->getLocation(), diag::err_block_on_nonlocal); | |||
14153 | } | |||
14154 | ||||
14155 | if (getLangOpts().OpenCL) | |||
14156 | deduceOpenCLAddressSpace(New); | |||
14157 | ||||
14158 | return New; | |||
14159 | } | |||
14160 | ||||
14161 | /// Synthesizes a variable for a parameter arising from a | |||
14162 | /// typedef. | |||
14163 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, | |||
14164 | SourceLocation Loc, | |||
14165 | QualType T) { | |||
14166 | /* FIXME: setting StartLoc == Loc. | |||
14167 | Would it be worth to modify callers so as to provide proper source | |||
14168 | location for the unnamed parameters, embedding the parameter's type? */ | |||
14169 | ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, | |||
14170 | T, Context.getTrivialTypeSourceInfo(T, Loc), | |||
14171 | SC_None, nullptr); | |||
14172 | Param->setImplicit(); | |||
14173 | return Param; | |||
14174 | } | |||
14175 | ||||
14176 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { | |||
14177 | // Don't diagnose unused-parameter errors in template instantiations; we | |||
14178 | // will already have done so in the template itself. | |||
14179 | if (inTemplateInstantiation()) | |||
14180 | return; | |||
14181 | ||||
14182 | for (const ParmVarDecl *Parameter : Parameters) { | |||
14183 | if (!Parameter->isReferenced() && Parameter->getDeclName() && | |||
14184 | !Parameter->hasAttr<UnusedAttr>()) { | |||
14185 | Diag(Parameter->getLocation(), diag::warn_unused_parameter) | |||
14186 | << Parameter->getDeclName(); | |||
14187 | } | |||
14188 | } | |||
14189 | } | |||
14190 | ||||
14191 | void Sema::DiagnoseSizeOfParametersAndReturnValue( | |||
14192 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { | |||
14193 | if (LangOpts.NumLargeByValueCopy == 0) // No check. | |||
14194 | return; | |||
14195 | ||||
14196 | // Warn if the return value is pass-by-value and larger than the specified | |||
14197 | // threshold. | |||
14198 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { | |||
14199 | unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); | |||
14200 | if (Size > LangOpts.NumLargeByValueCopy) | |||
14201 | Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; | |||
14202 | } | |||
14203 | ||||
14204 | // Warn if any parameter is pass-by-value and larger than the specified | |||
14205 | // threshold. | |||
14206 | for (const ParmVarDecl *Parameter : Parameters) { | |||
14207 | QualType T = Parameter->getType(); | |||
14208 | if (T->isDependentType() || !T.isPODType(Context)) | |||
14209 | continue; | |||
14210 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); | |||
14211 | if (Size > LangOpts.NumLargeByValueCopy) | |||
14212 | Diag(Parameter->getLocation(), diag::warn_parameter_size) | |||
14213 | << Parameter << Size; | |||
14214 | } | |||
14215 | } | |||
14216 | ||||
14217 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, | |||
14218 | SourceLocation NameLoc, IdentifierInfo *Name, | |||
14219 | QualType T, TypeSourceInfo *TSInfo, | |||
14220 | StorageClass SC) { | |||
14221 | // In ARC, infer a lifetime qualifier for appropriate parameter types. | |||
14222 | if (getLangOpts().ObjCAutoRefCount && | |||
14223 | T.getObjCLifetime() == Qualifiers::OCL_None && | |||
14224 | T->isObjCLifetimeType()) { | |||
14225 | ||||
14226 | Qualifiers::ObjCLifetime lifetime; | |||
14227 | ||||
14228 | // Special cases for arrays: | |||
14229 | // - if it's const, use __unsafe_unretained | |||
14230 | // - otherwise, it's an error | |||
14231 | if (T->isArrayType()) { | |||
14232 | if (!T.isConstQualified()) { | |||
14233 | if (DelayedDiagnostics.shouldDelayDiagnostics()) | |||
14234 | DelayedDiagnostics.add( | |||
14235 | sema::DelayedDiagnostic::makeForbiddenType( | |||
14236 | NameLoc, diag::err_arc_array_param_no_ownership, T, false)); | |||
14237 | else | |||
14238 | Diag(NameLoc, diag::err_arc_array_param_no_ownership) | |||
14239 | << TSInfo->getTypeLoc().getSourceRange(); | |||
14240 | } | |||
14241 | lifetime = Qualifiers::OCL_ExplicitNone; | |||
14242 | } else { | |||
14243 | lifetime = T->getObjCARCImplicitLifetime(); | |||
14244 | } | |||
14245 | T = Context.getLifetimeQualifiedType(T, lifetime); | |||
14246 | } | |||
14247 | ||||
14248 | ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, | |||
14249 | Context.getAdjustedParameterType(T), | |||
14250 | TSInfo, SC, nullptr); | |||
14251 | ||||
14252 | // Make a note if we created a new pack in the scope of a lambda, so that | |||
14253 | // we know that references to that pack must also be expanded within the | |||
14254 | // lambda scope. | |||
14255 | if (New->isParameterPack()) | |||
14256 | if (auto *LSI = getEnclosingLambda()) | |||
14257 | LSI->LocalPacks.push_back(New); | |||
14258 | ||||
14259 | if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || | |||
14260 | New->getType().hasNonTrivialToPrimitiveCopyCUnion()) | |||
14261 | checkNonTrivialCUnion(New->getType(), New->getLocation(), | |||
14262 | NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); | |||
14263 | ||||
14264 | // Parameters can not be abstract class types. | |||
14265 | // For record types, this is done by the AbstractClassUsageDiagnoser once | |||
14266 | // the class has been completely parsed. | |||
14267 | if (!CurContext->isRecord() && | |||
14268 | RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, | |||
14269 | AbstractParamType)) | |||
14270 | New->setInvalidDecl(); | |||
14271 | ||||
14272 | // Parameter declarators cannot be interface types. All ObjC objects are | |||
14273 | // passed by reference. | |||
14274 | if (T->isObjCObjectType()) { | |||
14275 | SourceLocation TypeEndLoc = | |||
14276 | getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); | |||
14277 | Diag(NameLoc, | |||
14278 | diag::err_object_cannot_be_passed_returned_by_value) << 1 << T | |||
14279 | << FixItHint::CreateInsertion(TypeEndLoc, "*"); | |||
14280 | T = Context.getObjCObjectPointerType(T); | |||
14281 | New->setType(T); | |||
14282 | } | |||
14283 | ||||
14284 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage | |||
14285 | // duration shall not be qualified by an address-space qualifier." | |||
14286 | // Since all parameters have automatic store duration, they can not have | |||
14287 | // an address space. | |||
14288 | if (T.getAddressSpace() != LangAS::Default && | |||
14289 | // OpenCL allows function arguments declared to be an array of a type | |||
14290 | // to be qualified with an address space. | |||
14291 | !(getLangOpts().OpenCL && | |||
14292 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { | |||
14293 | Diag(NameLoc, diag::err_arg_with_address_space); | |||
14294 | New->setInvalidDecl(); | |||
14295 | } | |||
14296 | ||||
14297 | // PPC MMA non-pointer types are not allowed as function argument types. | |||
14298 | if (Context.getTargetInfo().getTriple().isPPC64() && | |||
14299 | CheckPPCMMAType(New->getOriginalType(), New->getLocation())) { | |||
14300 | New->setInvalidDecl(); | |||
14301 | } | |||
14302 | ||||
14303 | return New; | |||
14304 | } | |||
14305 | ||||
14306 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, | |||
14307 | SourceLocation LocAfterDecls) { | |||
14308 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | |||
14309 | ||||
14310 | // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' | |||
14311 | // for a K&R function. | |||
14312 | if (!FTI.hasPrototype) { | |||
14313 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { | |||
14314 | --i; | |||
14315 | if (FTI.Params[i].Param == nullptr) { | |||
14316 | SmallString<256> Code; | |||
14317 | llvm::raw_svector_ostream(Code) | |||
14318 | << " int " << FTI.Params[i].Ident->getName() << ";\n"; | |||
14319 | Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) | |||
14320 | << FTI.Params[i].Ident | |||
14321 | << FixItHint::CreateInsertion(LocAfterDecls, Code); | |||
14322 | ||||
14323 | // Implicitly declare the argument as type 'int' for lack of a better | |||
14324 | // type. | |||
14325 | AttributeFactory attrs; | |||
14326 | DeclSpec DS(attrs); | |||
14327 | const char* PrevSpec; // unused | |||
14328 | unsigned DiagID; // unused | |||
14329 | DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, | |||
14330 | DiagID, Context.getPrintingPolicy()); | |||
14331 | // Use the identifier location for the type source range. | |||
14332 | DS.SetRangeStart(FTI.Params[i].IdentLoc); | |||
14333 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); | |||
14334 | Declarator ParamD(DS, DeclaratorContext::KNRTypeList); | |||
14335 | ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); | |||
14336 | FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); | |||
14337 | } | |||
14338 | } | |||
14339 | } | |||
14340 | } | |||
14341 | ||||
14342 | Decl * | |||
14343 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, | |||
14344 | MultiTemplateParamsArg TemplateParameterLists, | |||
14345 | SkipBodyInfo *SkipBody, FnBodyKind BodyKind) { | |||
14346 | assert(getCurFunctionDecl() == nullptr && "Function parsing confused")(static_cast <bool> (getCurFunctionDecl() == nullptr && "Function parsing confused") ? void (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\"" , "clang/lib/Sema/SemaDecl.cpp", 14346, __extension__ __PRETTY_FUNCTION__ )); | |||
14347 | assert(D.isFunctionDeclarator() && "Not a function declarator!")(static_cast <bool> (D.isFunctionDeclarator() && "Not a function declarator!") ? void (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\"" , "clang/lib/Sema/SemaDecl.cpp", 14347, __extension__ __PRETTY_FUNCTION__ )); | |||
14348 | Scope *ParentScope = FnBodyScope->getParent(); | |||
14349 | ||||
14350 | // Check if we are in an `omp begin/end declare variant` scope. If we are, and | |||
14351 | // we define a non-templated function definition, we will create a declaration | |||
14352 | // instead (=BaseFD), and emit the definition with a mangled name afterwards. | |||
14353 | // The base function declaration will have the equivalent of an `omp declare | |||
14354 | // variant` annotation which specifies the mangled definition as a | |||
14355 | // specialization function under the OpenMP context defined as part of the | |||
14356 | // `omp begin declare variant`. | |||
14357 | SmallVector<FunctionDecl *, 4> Bases; | |||
14358 | if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) | |||
14359 | ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( | |||
14360 | ParentScope, D, TemplateParameterLists, Bases); | |||
14361 | ||||
14362 | D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition); | |||
14363 | Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); | |||
14364 | Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody, BodyKind); | |||
14365 | ||||
14366 | if (!Bases.empty()) | |||
14367 | ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); | |||
14368 | ||||
14369 | return Dcl; | |||
14370 | } | |||
14371 | ||||
14372 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { | |||
14373 | Consumer.HandleInlineFunctionDefinition(D); | |||
14374 | } | |||
14375 | ||||
14376 | static bool | |||
14377 | ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, | |||
14378 | const FunctionDecl *&PossiblePrototype) { | |||
14379 | // Don't warn about invalid declarations. | |||
14380 | if (FD->isInvalidDecl()) | |||
14381 | return false; | |||
14382 | ||||
14383 | // Or declarations that aren't global. | |||
14384 | if (!FD->isGlobal()) | |||
14385 | return false; | |||
14386 | ||||
14387 | // Don't warn about C++ member functions. | |||
14388 | if (isa<CXXMethodDecl>(FD)) | |||
14389 | return false; | |||
14390 | ||||
14391 | // Don't warn about 'main'. | |||
14392 | if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) | |||
14393 | if (IdentifierInfo *II = FD->getIdentifier()) | |||
14394 | if (II->isStr("main") || II->isStr("efi_main")) | |||
14395 | return false; | |||
14396 | ||||
14397 | // Don't warn about inline functions. | |||
14398 | if (FD->isInlined()) | |||
14399 | return false; | |||
14400 | ||||
14401 | // Don't warn about function templates. | |||
14402 | if (FD->getDescribedFunctionTemplate()) | |||
14403 | return false; | |||
14404 | ||||
14405 | // Don't warn about function template specializations. | |||
14406 | if (FD->isFunctionTemplateSpecialization()) | |||
14407 | return false; | |||
14408 | ||||
14409 | // Don't warn for OpenCL kernels. | |||
14410 | if (FD->hasAttr<OpenCLKernelAttr>()) | |||
14411 | return false; | |||
14412 | ||||
14413 | // Don't warn on explicitly deleted functions. | |||
14414 | if (FD->isDeleted()) | |||
14415 | return false; | |||
14416 | ||||
14417 | // Don't warn on implicitly local functions (such as having local-typed | |||
14418 | // parameters). | |||
14419 | if (!FD->isExternallyVisible()) | |||
14420 | return false; | |||
14421 | ||||
14422 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); | |||
14423 | Prev; Prev = Prev->getPreviousDecl()) { | |||
14424 | // Ignore any declarations that occur in function or method | |||
14425 | // scope, because they aren't visible from the header. | |||
14426 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) | |||
14427 | continue; | |||
14428 | ||||
14429 | PossiblePrototype = Prev; | |||
14430 | return Prev->getType()->isFunctionNoProtoType(); | |||
14431 | } | |||
14432 | ||||
14433 | return true; | |||
14434 | } | |||
14435 | ||||
14436 | void | |||
14437 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, | |||
14438 | const FunctionDecl *EffectiveDefinition, | |||
14439 | SkipBodyInfo *SkipBody) { | |||
14440 | const FunctionDecl *Definition = EffectiveDefinition; | |||
14441 | if (!Definition && | |||
14442 | !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true)) | |||
14443 | return; | |||
14444 | ||||
14445 | if (Definition->getFriendObjectKind() != Decl::FOK_None) { | |||
14446 | if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) { | |||
14447 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { | |||
14448 | // A merged copy of the same function, instantiated as a member of | |||
14449 | // the same class, is OK. | |||
14450 | if (declaresSameEntity(OrigFD, OrigDef) && | |||
14451 | declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()), | |||
14452 | cast<Decl>(FD->getLexicalDeclContext()))) | |||
14453 | return; | |||
14454 | } | |||
14455 | } | |||
14456 | } | |||
14457 | ||||
14458 | if (canRedefineFunction(Definition, getLangOpts())) | |||
14459 | return; | |||
14460 | ||||
14461 | // Don't emit an error when this is redefinition of a typo-corrected | |||
14462 | // definition. | |||
14463 | if (TypoCorrectedFunctionDefinitions.count(Definition)) | |||
14464 | return; | |||
14465 | ||||
14466 | // If we don't have a visible definition of the function, and it's inline or | |||
14467 | // a template, skip the new definition. | |||
14468 | if (SkipBody && !hasVisibleDefinition(Definition) && | |||
14469 | (Definition->getFormalLinkage() == InternalLinkage || | |||
14470 | Definition->isInlined() || | |||
14471 | Definition->getDescribedFunctionTemplate() || | |||
14472 | Definition->getNumTemplateParameterLists())) { | |||
14473 | SkipBody->ShouldSkip = true; | |||
14474 | SkipBody->Previous = const_cast<FunctionDecl*>(Definition); | |||
14475 | if (auto *TD = Definition->getDescribedFunctionTemplate()) | |||
14476 | makeMergedDefinitionVisible(TD); | |||
14477 | makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); | |||
14478 | return; | |||
14479 | } | |||
14480 | ||||
14481 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && | |||
14482 | Definition->getStorageClass() == SC_Extern) | |||
14483 | Diag(FD->getLocation(), diag::err_redefinition_extern_inline) | |||
14484 | << FD << getLangOpts().CPlusPlus; | |||
14485 | else | |||
14486 | Diag(FD->getLocation(), diag::err_redefinition) << FD; | |||
14487 | ||||
14488 | Diag(Definition->getLocation(), diag::note_previous_definition); | |||
14489 | FD->setInvalidDecl(); | |||
14490 | } | |||
14491 | ||||
14492 | static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, | |||
14493 | Sema &S) { | |||
14494 | CXXRecordDecl *const LambdaClass = CallOperator->getParent(); | |||
14495 | ||||
14496 | LambdaScopeInfo *LSI = S.PushLambdaScope(); | |||
14497 | LSI->CallOperator = CallOperator; | |||
14498 | LSI->Lambda = LambdaClass; | |||
14499 | LSI->ReturnType = CallOperator->getReturnType(); | |||
14500 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); | |||
14501 | ||||
14502 | if (LCD == LCD_None) | |||
14503 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; | |||
14504 | else if (LCD == LCD_ByCopy) | |||
14505 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; | |||
14506 | else if (LCD == LCD_ByRef) | |||
14507 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; | |||
14508 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); | |||
14509 | ||||
14510 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); | |||
14511 | LSI->Mutable = !CallOperator->isConst(); | |||
14512 | ||||
14513 | // Add the captures to the LSI so they can be noted as already | |||
14514 | // captured within tryCaptureVar. | |||
14515 | auto I = LambdaClass->field_begin(); | |||
14516 | for (const auto &C : LambdaClass->captures()) { | |||
14517 | if (C.capturesVariable()) { | |||
14518 | VarDecl *VD = C.getCapturedVar(); | |||
14519 | if (VD->isInitCapture()) | |||
14520 | S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); | |||
14521 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; | |||
14522 | LSI->addCapture(VD, /*IsBlock*/false, ByRef, | |||
14523 | /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), | |||
14524 | /*EllipsisLoc*/C.isPackExpansion() | |||
14525 | ? C.getEllipsisLoc() : SourceLocation(), | |||
14526 | I->getType(), /*Invalid*/false); | |||
14527 | ||||
14528 | } else if (C.capturesThis()) { | |||
14529 | LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), | |||
14530 | C.getCaptureKind() == LCK_StarThis); | |||
14531 | } else { | |||
14532 | LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), | |||
14533 | I->getType()); | |||
14534 | } | |||
14535 | ++I; | |||
14536 | } | |||
14537 | } | |||
14538 | ||||
14539 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, | |||
14540 | SkipBodyInfo *SkipBody, | |||
14541 | FnBodyKind BodyKind) { | |||
14542 | if (!D) { | |||
14543 | // Parsing the function declaration failed in some way. Push on a fake scope | |||
14544 | // anyway so we can try to parse the function body. | |||
14545 | PushFunctionScope(); | |||
14546 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | |||
14547 | return D; | |||
14548 | } | |||
14549 | ||||
14550 | FunctionDecl *FD = nullptr; | |||
14551 | ||||
14552 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) | |||
14553 | FD = FunTmpl->getTemplatedDecl(); | |||
14554 | else | |||
14555 | FD = cast<FunctionDecl>(D); | |||
14556 | ||||
14557 | // Do not push if it is a lambda because one is already pushed when building | |||
14558 | // the lambda in ActOnStartOfLambdaDefinition(). | |||
14559 | if (!isLambdaCallOperator(FD)) | |||
14560 | PushExpressionEvaluationContext( | |||
14561 | FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated | |||
14562 | : ExprEvalContexts.back().Context); | |||
14563 | ||||
14564 | // Check for defining attributes before the check for redefinition. | |||
14565 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { | |||
14566 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; | |||
14567 | FD->dropAttr<AliasAttr>(); | |||
14568 | FD->setInvalidDecl(); | |||
14569 | } | |||
14570 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { | |||
14571 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; | |||
14572 | FD->dropAttr<IFuncAttr>(); | |||
14573 | FD->setInvalidDecl(); | |||
14574 | } | |||
14575 | ||||
14576 | if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) { | |||
14577 | if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | |||
14578 | Ctor->isDefaultConstructor() && | |||
14579 | Context.getTargetInfo().getCXXABI().isMicrosoft()) { | |||
14580 | // If this is an MS ABI dllexport default constructor, instantiate any | |||
14581 | // default arguments. | |||
14582 | InstantiateDefaultCtorDefaultArgs(Ctor); | |||
14583 | } | |||
14584 | } | |||
14585 | ||||
14586 | // See if this is a redefinition. If 'will have body' (or similar) is already | |||
14587 | // set, then these checks were already performed when it was set. | |||
14588 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed() && | |||
14589 | !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) { | |||
14590 | CheckForFunctionRedefinition(FD, nullptr, SkipBody); | |||
14591 | ||||
14592 | // If we're skipping the body, we're done. Don't enter the scope. | |||
14593 | if (SkipBody && SkipBody->ShouldSkip) | |||
14594 | return D; | |||
14595 | } | |||
14596 | ||||
14597 | // Mark this function as "will have a body eventually". This lets users to | |||
14598 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing | |||
14599 | // this function. | |||
14600 | FD->setWillHaveBody(); | |||
14601 | ||||
14602 | // If we are instantiating a generic lambda call operator, push | |||
14603 | // a LambdaScopeInfo onto the function stack. But use the information | |||
14604 | // that's already been calculated (ActOnLambdaExpr) to prime the current | |||
14605 | // LambdaScopeInfo. | |||
14606 | // When the template operator is being specialized, the LambdaScopeInfo, | |||
14607 | // has to be properly restored so that tryCaptureVariable doesn't try | |||
14608 | // and capture any new variables. In addition when calculating potential | |||
14609 | // captures during transformation of nested lambdas, it is necessary to | |||
14610 | // have the LSI properly restored. | |||
14611 | if (isGenericLambdaCallOperatorSpecialization(FD)) { | |||
14612 | assert(inTemplateInstantiation() &&(static_cast <bool> (inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? void (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "clang/lib/Sema/SemaDecl.cpp", 14614, __extension__ __PRETTY_FUNCTION__ )) | |||
14613 | "There should be an active template instantiation on the stack "(static_cast <bool> (inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? void (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "clang/lib/Sema/SemaDecl.cpp", 14614, __extension__ __PRETTY_FUNCTION__ )) | |||
14614 | "when instantiating a generic lambda!")(static_cast <bool> (inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? void (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "clang/lib/Sema/SemaDecl.cpp", 14614, __extension__ __PRETTY_FUNCTION__ )); | |||
14615 | RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); | |||
14616 | } else { | |||
14617 | // Enter a new function scope | |||
14618 | PushFunctionScope(); | |||
14619 | } | |||
14620 | ||||
14621 | // Builtin functions cannot be defined. | |||
14622 | if (unsigned BuiltinID = FD->getBuiltinID()) { | |||
14623 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && | |||
14624 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { | |||
14625 | Diag(FD->getLocation(), diag::err_builtin_definition) << FD; | |||
14626 | FD->setInvalidDecl(); | |||
14627 | } | |||
14628 | } | |||
14629 | ||||
14630 | // The return type of a function definition must be complete (C99 6.9.1p3), | |||
14631 | // unless the function is deleted (C++ specifc, C++ [dcl.fct.def.general]p2) | |||
14632 | QualType ResultType = FD->getReturnType(); | |||
14633 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && | |||
14634 | !FD->isInvalidDecl() && BodyKind != FnBodyKind::Delete && | |||
14635 | RequireCompleteType(FD->getLocation(), ResultType, | |||
14636 | diag::err_func_def_incomplete_result)) | |||
14637 | FD->setInvalidDecl(); | |||
14638 | ||||
14639 | if (FnBodyScope) | |||
14640 | PushDeclContext(FnBodyScope, FD); | |||
14641 | ||||
14642 | // Check the validity of our function parameters | |||
14643 | if (BodyKind != FnBodyKind::Delete) | |||
14644 | CheckParmsForFunctionDef(FD->parameters(), | |||
14645 | /*CheckParameterNames=*/true); | |||
14646 | ||||
14647 | // Add non-parameter declarations already in the function to the current | |||
14648 | // scope. | |||
14649 | if (FnBodyScope) { | |||
14650 | for (Decl *NPD : FD->decls()) { | |||
14651 | auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); | |||
14652 | if (!NonParmDecl) | |||
14653 | continue; | |||
14654 | assert(!isa<ParmVarDecl>(NonParmDecl) &&(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl ) && "parameters should not be in newly created FD yet" ) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "clang/lib/Sema/SemaDecl.cpp", 14655, __extension__ __PRETTY_FUNCTION__ )) | |||
14655 | "parameters should not be in newly created FD yet")(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl ) && "parameters should not be in newly created FD yet" ) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "clang/lib/Sema/SemaDecl.cpp", 14655, __extension__ __PRETTY_FUNCTION__ )); | |||
14656 | ||||
14657 | // If the decl has a name, make it accessible in the current scope. | |||
14658 | if (NonParmDecl->getDeclName()) | |||
14659 | PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); | |||
14660 | ||||
14661 | // Similarly, dive into enums and fish their constants out, making them | |||
14662 | // accessible in this scope. | |||
14663 | if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { | |||
14664 | for (auto *EI : ED->enumerators()) | |||
14665 | PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); | |||
14666 | } | |||
14667 | } | |||
14668 | } | |||
14669 | ||||
14670 | // Introduce our parameters into the function scope | |||
14671 | for (auto Param : FD->parameters()) { | |||
14672 | Param->setOwningFunction(FD); | |||
14673 | ||||
14674 | // If this has an identifier, add it to the scope stack. | |||
14675 | if (Param->getIdentifier() && FnBodyScope) { | |||
14676 | CheckShadow(FnBodyScope, Param); | |||
14677 | ||||
14678 | PushOnScopeChains(Param, FnBodyScope); | |||
14679 | } | |||
14680 | } | |||
14681 | ||||
14682 | // Ensure that the function's exception specification is instantiated. | |||
14683 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) | |||
14684 | ResolveExceptionSpec(D->getLocation(), FPT); | |||
14685 | ||||
14686 | // dllimport cannot be applied to non-inline function definitions. | |||
14687 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && | |||
14688 | !FD->isTemplateInstantiation()) { | |||
14689 | assert(!FD->hasAttr<DLLExportAttr>())(static_cast <bool> (!FD->hasAttr<DLLExportAttr> ()) ? void (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()" , "clang/lib/Sema/SemaDecl.cpp", 14689, __extension__ __PRETTY_FUNCTION__ )); | |||
14690 | Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); | |||
14691 | FD->setInvalidDecl(); | |||
14692 | return D; | |||
14693 | } | |||
14694 | // We want to attach documentation to original Decl (which might be | |||
14695 | // a function template). | |||
14696 | ActOnDocumentableDecl(D); | |||
14697 | if (getCurLexicalContext()->isObjCContainer() && | |||
14698 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && | |||
14699 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) | |||
14700 | Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); | |||
14701 | ||||
14702 | return D; | |||
14703 | } | |||
14704 | ||||
14705 | /// Given the set of return statements within a function body, | |||
14706 | /// compute the variables that are subject to the named return value | |||
14707 | /// optimization. | |||
14708 | /// | |||
14709 | /// Each of the variables that is subject to the named return value | |||
14710 | /// optimization will be marked as NRVO variables in the AST, and any | |||
14711 | /// return statement that has a marked NRVO variable as its NRVO candidate can | |||
14712 | /// use the named return value optimization. | |||
14713 | /// | |||
14714 | /// This function applies a very simplistic algorithm for NRVO: if every return | |||
14715 | /// statement in the scope of a variable has the same NRVO candidate, that | |||
14716 | /// candidate is an NRVO variable. | |||
14717 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { | |||
14718 | ReturnStmt **Returns = Scope->Returns.data(); | |||
14719 | ||||
14720 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { | |||
14721 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { | |||
14722 | if (!NRVOCandidate->isNRVOVariable()) | |||
14723 | Returns[I]->setNRVOCandidate(nullptr); | |||
14724 | } | |||
14725 | } | |||
14726 | } | |||
14727 | ||||
14728 | bool Sema::canDelayFunctionBody(const Declarator &D) { | |||
14729 | // We can't delay parsing the body of a constexpr function template (yet). | |||
14730 | if (D.getDeclSpec().hasConstexprSpecifier()) | |||
14731 | return false; | |||
14732 | ||||
14733 | // We can't delay parsing the body of a function template with a deduced | |||
14734 | // return type (yet). | |||
14735 | if (D.getDeclSpec().hasAutoTypeSpec()) { | |||
14736 | // If the placeholder introduces a non-deduced trailing return type, | |||
14737 | // we can still delay parsing it. | |||
14738 | if (D.getNumTypeObjects()) { | |||
14739 | const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); | |||
14740 | if (Outer.Kind == DeclaratorChunk::Function && | |||
14741 | Outer.Fun.hasTrailingReturnType()) { | |||
14742 | QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); | |||
14743 | return Ty.isNull() || !Ty->isUndeducedType(); | |||
14744 | } | |||
14745 | } | |||
14746 | return false; | |||
14747 | } | |||
14748 | ||||
14749 | return true; | |||
14750 | } | |||
14751 | ||||
14752 | bool Sema::canSkipFunctionBody(Decl *D) { | |||
14753 | // We cannot skip the body of a function (or function template) which is | |||
14754 | // constexpr, since we may need to evaluate its body in order to parse the | |||
14755 | // rest of the file. | |||
14756 | // We cannot skip the body of a function with an undeduced return type, | |||
14757 | // because any callers of that function need to know the type. | |||
14758 | if (const FunctionDecl *FD = D->getAsFunction()) { | |||
14759 | if (FD->isConstexpr()) | |||
14760 | return false; | |||
14761 | // We can't simply call Type::isUndeducedType here, because inside template | |||
14762 | // auto can be deduced to a dependent type, which is not considered | |||
14763 | // "undeduced". | |||
14764 | if (FD->getReturnType()->getContainedDeducedType()) | |||
14765 | return false; | |||
14766 | } | |||
14767 | return Consumer.shouldSkipFunctionBody(D); | |||
14768 | } | |||
14769 | ||||
14770 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { | |||
14771 | if (!Decl) | |||
14772 | return nullptr; | |||
14773 | if (FunctionDecl *FD = Decl->getAsFunction()) | |||
14774 | FD->setHasSkippedBody(); | |||
14775 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) | |||
14776 | MD->setHasSkippedBody(); | |||
14777 | return Decl; | |||
14778 | } | |||
14779 | ||||
14780 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { | |||
14781 | return ActOnFinishFunctionBody(D, BodyArg, false); | |||
14782 | } | |||
14783 | ||||
14784 | /// RAII object that pops an ExpressionEvaluationContext when exiting a function | |||
14785 | /// body. | |||
14786 | class ExitFunctionBodyRAII { | |||
14787 | public: | |||
14788 | ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} | |||
14789 | ~ExitFunctionBodyRAII() { | |||
14790 | if (!IsLambda) | |||
14791 | S.PopExpressionEvaluationContext(); | |||
14792 | } | |||
14793 | ||||
14794 | private: | |||
14795 | Sema &S; | |||
14796 | bool IsLambda = false; | |||
14797 | }; | |||
14798 | ||||
14799 | static void diagnoseImplicitlyRetainedSelf(Sema &S) { | |||
14800 | llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; | |||
14801 | ||||
14802 | auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { | |||
14803 | if (EscapeInfo.count(BD)) | |||
14804 | return EscapeInfo[BD]; | |||
14805 | ||||
14806 | bool R = false; | |||
14807 | const BlockDecl *CurBD = BD; | |||
14808 | ||||
14809 | do { | |||
14810 | R = !CurBD->doesNotEscape(); | |||
14811 | if (R) | |||
14812 | break; | |||
14813 | CurBD = CurBD->getParent()->getInnermostBlockDecl(); | |||
14814 | } while (CurBD); | |||
14815 | ||||
14816 | return EscapeInfo[BD] = R; | |||
14817 | }; | |||
14818 | ||||
14819 | // If the location where 'self' is implicitly retained is inside a escaping | |||
14820 | // block, emit a diagnostic. | |||
14821 | for (const std::pair<SourceLocation, const BlockDecl *> &P : | |||
14822 | S.ImplicitlyRetainedSelfLocs) | |||
14823 | if (IsOrNestedInEscapingBlock(P.second)) | |||
14824 | S.Diag(P.first, diag::warn_implicitly_retains_self) | |||
14825 | << FixItHint::CreateInsertion(P.first, "self->"); | |||
14826 | } | |||
14827 | ||||
14828 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, | |||
14829 | bool IsInstantiation) { | |||
14830 | FunctionScopeInfo *FSI = getCurFunction(); | |||
14831 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; | |||
14832 | ||||
14833 | if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>()) | |||
14834 | FD->addAttr(StrictFPAttr::CreateImplicit(Context)); | |||
14835 | ||||
14836 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | |||
14837 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; | |||
14838 | ||||
14839 | if (getLangOpts().Coroutines && FSI->isCoroutine()) | |||
14840 | CheckCompletedCoroutineBody(FD, Body); | |||
14841 | ||||
14842 | { | |||
14843 | // Do not call PopExpressionEvaluationContext() if it is a lambda because | |||
14844 | // one is already popped when finishing the lambda in BuildLambdaExpr(). | |||
14845 | // This is meant to pop the context added in ActOnStartOfFunctionDef(). | |||
14846 | ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); | |||
14847 | ||||
14848 | if (FD) { | |||
14849 | FD->setBody(Body); | |||
14850 | FD->setWillHaveBody(false); | |||
14851 | ||||
14852 | if (getLangOpts().CPlusPlus14) { | |||
14853 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && | |||
14854 | FD->getReturnType()->isUndeducedType()) { | |||
14855 | // For a function with a deduced result type to return void, | |||
14856 | // the result type as written must be 'auto' or 'decltype(auto)', | |||
14857 | // possibly cv-qualified or constrained, but not ref-qualified. | |||
14858 | if (!FD->getReturnType()->getAs<AutoType>()) { | |||
14859 | Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) | |||
14860 | << FD->getReturnType(); | |||
14861 | FD->setInvalidDecl(); | |||
14862 | } else { | |||
14863 | // Falling off the end of the function is the same as 'return;'. | |||
14864 | Expr *Dummy = nullptr; | |||
14865 | if (DeduceFunctionTypeFromReturnExpr( | |||
14866 | FD, dcl->getLocation(), Dummy, | |||
14867 | FD->getReturnType()->getAs<AutoType>())) | |||
14868 | FD->setInvalidDecl(); | |||
14869 | } | |||
14870 | } | |||
14871 | } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { | |||
14872 | // In C++11, we don't use 'auto' deduction rules for lambda call | |||
14873 | // operators because we don't support return type deduction. | |||
14874 | auto *LSI = getCurLambda(); | |||
14875 | if (LSI->HasImplicitReturnType) { | |||
14876 | deduceClosureReturnType(*LSI); | |||
14877 | ||||
14878 | // C++11 [expr.prim.lambda]p4: | |||
14879 | // [...] if there are no return statements in the compound-statement | |||
14880 | // [the deduced type is] the type void | |||
14881 | QualType RetType = | |||
14882 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; | |||
14883 | ||||
14884 | // Update the return type to the deduced type. | |||
14885 | const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); | |||
14886 | FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), | |||
14887 | Proto->getExtProtoInfo())); | |||
14888 | } | |||
14889 | } | |||
14890 | ||||
14891 | // If the function implicitly returns zero (like 'main') or is naked, | |||
14892 | // don't complain about missing return statements. | |||
14893 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) | |||
14894 | WP.disableCheckFallThrough(); | |||
14895 | ||||
14896 | // MSVC permits the use of pure specifier (=0) on function definition, | |||
14897 | // defined at class scope, warn about this non-standard construct. | |||
14898 | if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) | |||
14899 | Diag(FD->getLocation(), diag::ext_pure_function_definition); | |||
14900 | ||||
14901 | if (!FD->isInvalidDecl()) { | |||
14902 | // Don't diagnose unused parameters of defaulted, deleted or naked | |||
14903 | // functions. | |||
14904 | if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() && | |||
14905 | !FD->hasAttr<NakedAttr>()) | |||
14906 | DiagnoseUnusedParameters(FD->parameters()); | |||
14907 | DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), | |||
14908 | FD->getReturnType(), FD); | |||
14909 | ||||
14910 | // If this is a structor, we need a vtable. | |||
14911 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) | |||
14912 | MarkVTableUsed(FD->getLocation(), Constructor->getParent()); | |||
14913 | else if (CXXDestructorDecl *Destructor = | |||
14914 | dyn_cast<CXXDestructorDecl>(FD)) | |||
14915 | MarkVTableUsed(FD->getLocation(), Destructor->getParent()); | |||
14916 | ||||
14917 | // Try to apply the named return value optimization. We have to check | |||
14918 | // if we can do this here because lambdas keep return statements around | |||
14919 | // to deduce an implicit return type. | |||
14920 | if (FD->getReturnType()->isRecordType() && | |||
14921 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) | |||
14922 | computeNRVO(Body, FSI); | |||
14923 | } | |||
14924 | ||||
14925 | // GNU warning -Wmissing-prototypes: | |||
14926 | // Warn if a global function is defined without a previous | |||
14927 | // prototype declaration. This warning is issued even if the | |||
14928 | // definition itself provides a prototype. The aim is to detect | |||
14929 | // global functions that fail to be declared in header files. | |||
14930 | const FunctionDecl *PossiblePrototype = nullptr; | |||
14931 | if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { | |||
14932 | Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; | |||
14933 | ||||
14934 | if (PossiblePrototype) { | |||
14935 | // We found a declaration that is not a prototype, | |||
14936 | // but that could be a zero-parameter prototype | |||
14937 | if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { | |||
14938 | TypeLoc TL = TI->getTypeLoc(); | |||
14939 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) | |||
14940 | Diag(PossiblePrototype->getLocation(), | |||
14941 | diag::note_declaration_not_a_prototype) | |||
14942 | << (FD->getNumParams() != 0) | |||
14943 | << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion( | |||
14944 | FTL.getRParenLoc(), "void") | |||
14945 | : FixItHint{}); | |||
14946 | } | |||
14947 | } else { | |||
14948 | // Returns true if the token beginning at this Loc is `const`. | |||
14949 | auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, | |||
14950 | const LangOptions &LangOpts) { | |||
14951 | std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); | |||
14952 | if (LocInfo.first.isInvalid()) | |||
14953 | return false; | |||
14954 | ||||
14955 | bool Invalid = false; | |||
14956 | StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); | |||
14957 | if (Invalid) | |||
14958 | return false; | |||
14959 | ||||
14960 | if (LocInfo.second > Buffer.size()) | |||
14961 | return false; | |||
14962 | ||||
14963 | const char *LexStart = Buffer.data() + LocInfo.second; | |||
14964 | StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); | |||
14965 | ||||
14966 | return StartTok.consume_front("const") && | |||
14967 | (StartTok.empty() || isWhitespace(StartTok[0]) || | |||
14968 | StartTok.startswith("/*") || StartTok.startswith("//")); | |||
14969 | }; | |||
14970 | ||||
14971 | auto findBeginLoc = [&]() { | |||
14972 | // If the return type has `const` qualifier, we want to insert | |||
14973 | // `static` before `const` (and not before the typename). | |||
14974 | if ((FD->getReturnType()->isAnyPointerType() && | |||
14975 | FD->getReturnType()->getPointeeType().isConstQualified()) || | |||
14976 | FD->getReturnType().isConstQualified()) { | |||
14977 | // But only do this if we can determine where the `const` is. | |||
14978 | ||||
14979 | if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), | |||
14980 | getLangOpts())) | |||
14981 | ||||
14982 | return FD->getBeginLoc(); | |||
14983 | } | |||
14984 | return FD->getTypeSpecStartLoc(); | |||
14985 | }; | |||
14986 | Diag(FD->getTypeSpecStartLoc(), | |||
14987 | diag::note_static_for_internal_linkage) | |||
14988 | << /* function */ 1 | |||
14989 | << (FD->getStorageClass() == SC_None | |||
14990 | ? FixItHint::CreateInsertion(findBeginLoc(), "static ") | |||
14991 | : FixItHint{}); | |||
14992 | } | |||
14993 | } | |||
14994 | ||||
14995 | // If the function being defined does not have a prototype, then we may | |||
14996 | // need to diagnose it as changing behavior in C2x because we now know | |||
14997 | // whether the function accepts arguments or not. This only handles the | |||
14998 | // case where the definition has no prototype but does have parameters | |||
14999 | // and either there is no previous potential prototype, or the previous | |||
15000 | // potential prototype also has no actual prototype. This handles cases | |||
15001 | // like: | |||
15002 | // void f(); void f(a) int a; {} | |||
15003 | // void g(a) int a; {} | |||
15004 | // See MergeFunctionDecl() for other cases of the behavior change | |||
15005 | // diagnostic. See GetFullTypeForDeclarator() for handling of a function | |||
15006 | // type without a prototype. | |||
15007 | if (!FD->hasWrittenPrototype() && FD->getNumParams() != 0 && | |||
15008 | (!PossiblePrototype || (!PossiblePrototype->hasWrittenPrototype() && | |||
15009 | !PossiblePrototype->isImplicit()))) { | |||
15010 | // The function definition has parameters, so this will change behavior | |||
15011 | // in C2x. If there is a possible prototype, it comes before the | |||
15012 | // function definition. | |||
15013 | // FIXME: The declaration may have already been diagnosed as being | |||
15014 | // deprecated in GetFullTypeForDeclarator() if it had no arguments, but | |||
15015 | // there's no way to test for the "changes behavior" condition in | |||
15016 | // SemaType.cpp when forming the declaration's function type. So, we do | |||
15017 | // this awkward dance instead. | |||
15018 | // | |||
15019 | // If we have a possible prototype and it declares a function with a | |||
15020 | // prototype, we don't want to diagnose it; if we have a possible | |||
15021 | // prototype and it has no prototype, it may have already been | |||
15022 | // diagnosed in SemaType.cpp as deprecated depending on whether | |||
15023 | // -Wstrict-prototypes is enabled. If we already warned about it being | |||
15024 | // deprecated, add a note that it also changes behavior. If we didn't | |||
15025 | // warn about it being deprecated (because the diagnostic is not | |||
15026 | // enabled), warn now that it is deprecated and changes behavior. | |||
15027 | bool AddNote = false; | |||
15028 | if (PossiblePrototype) { | |||
15029 | if (Diags.isIgnored(diag::warn_strict_prototypes, | |||
15030 | PossiblePrototype->getLocation())) { | |||
15031 | ||||
15032 | PartialDiagnostic PD = | |||
15033 | PDiag(diag::warn_non_prototype_changes_behavior); | |||
15034 | if (TypeSourceInfo *TSI = PossiblePrototype->getTypeSourceInfo()) { | |||
15035 | if (auto FTL = TSI->getTypeLoc().getAs<FunctionNoProtoTypeLoc>()) | |||
15036 | PD << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); | |||
15037 | } | |||
15038 | Diag(PossiblePrototype->getLocation(), PD); | |||
15039 | } else { | |||
15040 | AddNote = true; | |||
15041 | } | |||
15042 | } | |||
15043 | ||||
15044 | // Because this function definition has no prototype and it has | |||
15045 | // parameters, it will definitely change behavior in C2x. | |||
15046 | Diag(FD->getLocation(), diag::warn_non_prototype_changes_behavior); | |||
15047 | if (AddNote) | |||
15048 | Diag(PossiblePrototype->getLocation(), | |||
15049 | diag::note_func_decl_changes_behavior); | |||
15050 | } | |||
15051 | ||||
15052 | // Warn on CPUDispatch with an actual body. | |||
15053 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) | |||
15054 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) | |||
15055 | if (!CmpndBody->body_empty()) | |||
15056 | Diag(CmpndBody->body_front()->getBeginLoc(), | |||
15057 | diag::warn_dispatch_body_ignored); | |||
15058 | ||||
15059 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | |||
15060 | const CXXMethodDecl *KeyFunction; | |||
15061 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && | |||
15062 | MD->isVirtual() && | |||
15063 | (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && | |||
15064 | MD == KeyFunction->getCanonicalDecl()) { | |||
15065 | // Update the key-function state if necessary for this ABI. | |||
15066 | if (FD->isInlined() && | |||
15067 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { | |||
15068 | Context.setNonKeyFunction(MD); | |||
15069 | ||||
15070 | // If the newly-chosen key function is already defined, then we | |||
15071 | // need to mark the vtable as used retroactively. | |||
15072 | KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); | |||
15073 | const FunctionDecl *Definition; | |||
15074 | if (KeyFunction && KeyFunction->isDefined(Definition)) | |||
15075 | MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); | |||
15076 | } else { | |||
15077 | // We just defined they key function; mark the vtable as used. | |||
15078 | MarkVTableUsed(FD->getLocation(), MD->getParent(), true); | |||
15079 | } | |||
15080 | } | |||
15081 | } | |||
15082 | ||||
15083 | assert((static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda ()->CallOperator == FD) && "Function parsing confused" ) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "clang/lib/Sema/SemaDecl.cpp", 15085, __extension__ __PRETTY_FUNCTION__ )) | |||
15084 | (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda ()->CallOperator == FD) && "Function parsing confused" ) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "clang/lib/Sema/SemaDecl.cpp", 15085, __extension__ __PRETTY_FUNCTION__ )) | |||
15085 | "Function parsing confused")(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda ()->CallOperator == FD) && "Function parsing confused" ) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "clang/lib/Sema/SemaDecl.cpp", 15085, __extension__ __PRETTY_FUNCTION__ )); | |||
15086 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { | |||
15087 | assert(MD == getCurMethodDecl() && "Method parsing confused")(static_cast <bool> (MD == getCurMethodDecl() && "Method parsing confused") ? void (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\"" , "clang/lib/Sema/SemaDecl.cpp", 15087, __extension__ __PRETTY_FUNCTION__ )); | |||
15088 | MD->setBody(Body); | |||
15089 | if (!MD->isInvalidDecl()) { | |||
15090 | DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), | |||
15091 | MD->getReturnType(), MD); | |||
15092 | ||||
15093 | if (Body) | |||
15094 | computeNRVO(Body, FSI); | |||
15095 | } | |||
15096 | if (FSI->ObjCShouldCallSuper) { | |||
15097 | Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) | |||
15098 | << MD->getSelector().getAsString(); | |||
15099 | FSI->ObjCShouldCallSuper = false; | |||
15100 | } | |||
15101 | if (FSI->ObjCWarnForNoDesignatedInitChain) { | |||
15102 | const ObjCMethodDecl *InitMethod = nullptr; | |||
15103 | bool isDesignated = | |||
15104 | MD->isDesignatedInitializerForTheInterface(&InitMethod); | |||
15105 | assert(isDesignated && InitMethod)(static_cast <bool> (isDesignated && InitMethod ) ? void (0) : __assert_fail ("isDesignated && InitMethod" , "clang/lib/Sema/SemaDecl.cpp", 15105, __extension__ __PRETTY_FUNCTION__ )); | |||
15106 | (void)isDesignated; | |||
15107 | ||||
15108 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { | |||
15109 | auto IFace = MD->getClassInterface(); | |||
15110 | if (!IFace) | |||
15111 | return false; | |||
15112 | auto SuperD = IFace->getSuperClass(); | |||
15113 | if (!SuperD) | |||
15114 | return false; | |||
15115 | return SuperD->getIdentifier() == | |||
15116 | NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); | |||
15117 | }; | |||
15118 | // Don't issue this warning for unavailable inits or direct subclasses | |||
15119 | // of NSObject. | |||
15120 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { | |||
15121 | Diag(MD->getLocation(), | |||
15122 | diag::warn_objc_designated_init_missing_super_call); | |||
15123 | Diag(InitMethod->getLocation(), | |||
15124 | diag::note_objc_designated_init_marked_here); | |||
15125 | } | |||
15126 | FSI->ObjCWarnForNoDesignatedInitChain = false; | |||
15127 | } | |||
15128 | if (FSI->ObjCWarnForNoInitDelegation) { | |||
15129 | // Don't issue this warning for unavaialable inits. | |||
15130 | if (!MD->isUnavailable()) | |||
15131 | Diag(MD->getLocation(), | |||
15132 | diag::warn_objc_secondary_init_missing_init_call); | |||
15133 | FSI->ObjCWarnForNoInitDelegation = false; | |||
15134 | } | |||
15135 | ||||
15136 | diagnoseImplicitlyRetainedSelf(*this); | |||
15137 | } else { | |||
15138 | // Parsing the function declaration failed in some way. Pop the fake scope | |||
15139 | // we pushed on. | |||
15140 | PopFunctionScopeInfo(ActivePolicy, dcl); | |||
15141 | return nullptr; | |||
15142 | } | |||
15143 | ||||
15144 | if (Body && FSI->HasPotentialAvailabilityViolations) | |||
15145 | DiagnoseUnguardedAvailabilityViolations(dcl); | |||
15146 | ||||
15147 | assert(!FSI->ObjCShouldCallSuper &&(static_cast <bool> (!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "clang/lib/Sema/SemaDecl.cpp", 15149, __extension__ __PRETTY_FUNCTION__ )) | |||
15148 | "This should only be set for ObjC methods, which should have been "(static_cast <bool> (!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "clang/lib/Sema/SemaDecl.cpp", 15149, __extension__ __PRETTY_FUNCTION__ )) | |||
15149 | "handled in the block above.")(static_cast <bool> (!FSI->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? void (0) : __assert_fail ("!FSI->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "clang/lib/Sema/SemaDecl.cpp", 15149, __extension__ __PRETTY_FUNCTION__ )); | |||
15150 | ||||
15151 | // Verify and clean out per-function state. | |||
15152 | if (Body && (!FD || !FD->isDefaulted())) { | |||
15153 | // C++ constructors that have function-try-blocks can't have return | |||
15154 | // statements in the handlers of that block. (C++ [except.handle]p14) | |||
15155 | // Verify this. | |||
15156 | if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) | |||
15157 | DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); | |||
15158 | ||||
15159 | // Verify that gotos and switch cases don't jump into scopes illegally. | |||
15160 | if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled()) | |||
15161 | DiagnoseInvalidJumps(Body); | |||
15162 | ||||
15163 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { | |||
15164 | if (!Destructor->getParent()->isDependentType()) | |||
15165 | CheckDestructor(Destructor); | |||
15166 | ||||
15167 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | |||
15168 | Destructor->getParent()); | |||
15169 | } | |||
15170 | ||||
15171 | // If any errors have occurred, clear out any temporaries that may have | |||
15172 | // been leftover. This ensures that these temporaries won't be picked up | |||
15173 | // for deletion in some later function. | |||
15174 | if (hasUncompilableErrorOccurred() || | |||
15175 | getDiagnostics().getSuppressAllDiagnostics()) { | |||
15176 | DiscardCleanupsInEvaluationContext(); | |||
15177 | } | |||
15178 | if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) { | |||
15179 | // Since the body is valid, issue any analysis-based warnings that are | |||
15180 | // enabled. | |||
15181 | ActivePolicy = &WP; | |||
15182 | } | |||
15183 | ||||
15184 | if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && | |||
15185 | !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) | |||
15186 | FD->setInvalidDecl(); | |||
15187 | ||||
15188 | if (FD && FD->hasAttr<NakedAttr>()) { | |||
15189 | for (const Stmt *S : Body->children()) { | |||
15190 | // Allow local register variables without initializer as they don't | |||
15191 | // require prologue. | |||
15192 | bool RegisterVariables = false; | |||
15193 | if (auto *DS = dyn_cast<DeclStmt>(S)) { | |||
15194 | for (const auto *Decl : DS->decls()) { | |||
15195 | if (const auto *Var = dyn_cast<VarDecl>(Decl)) { | |||
15196 | RegisterVariables = | |||
15197 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); | |||
15198 | if (!RegisterVariables) | |||
15199 | break; | |||
15200 | } | |||
15201 | } | |||
15202 | } | |||
15203 | if (RegisterVariables) | |||
15204 | continue; | |||
15205 | if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { | |||
15206 | Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); | |||
15207 | Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); | |||
15208 | FD->setInvalidDecl(); | |||
15209 | break; | |||
15210 | } | |||
15211 | } | |||
15212 | } | |||
15213 | ||||
15214 | assert(ExprCleanupObjects.size() ==(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts .back().NumCleanupObjects && "Leftover temporaries in function" ) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "clang/lib/Sema/SemaDecl.cpp", 15216, __extension__ __PRETTY_FUNCTION__ )) | |||
15215 | ExprEvalContexts.back().NumCleanupObjects &&(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts .back().NumCleanupObjects && "Leftover temporaries in function" ) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "clang/lib/Sema/SemaDecl.cpp", 15216, __extension__ __PRETTY_FUNCTION__ )) | |||
15216 | "Leftover temporaries in function")(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts .back().NumCleanupObjects && "Leftover temporaries in function" ) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "clang/lib/Sema/SemaDecl.cpp", 15216, __extension__ __PRETTY_FUNCTION__ )); | |||
15217 | assert(!Cleanup.exprNeedsCleanups() &&(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"" , "clang/lib/Sema/SemaDecl.cpp", 15218, __extension__ __PRETTY_FUNCTION__ )) | |||
15218 | "Unaccounted cleanups in function")(static_cast <bool> (!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function") ? void (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"" , "clang/lib/Sema/SemaDecl.cpp", 15218, __extension__ __PRETTY_FUNCTION__ )); | |||
15219 | assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "clang/lib/Sema/SemaDecl.cpp", 15220, __extension__ __PRETTY_FUNCTION__ )) | |||
15220 | "Leftover expressions for odr-use checking")(static_cast <bool> (MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking") ? void (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "clang/lib/Sema/SemaDecl.cpp", 15220, __extension__ __PRETTY_FUNCTION__ )); | |||
15221 | } | |||
15222 | } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop | |||
15223 | // the declaration context below. Otherwise, we're unable to transform | |||
15224 | // 'this' expressions when transforming immediate context functions. | |||
15225 | ||||
15226 | if (!IsInstantiation) | |||
15227 | PopDeclContext(); | |||
15228 | ||||
15229 | PopFunctionScopeInfo(ActivePolicy, dcl); | |||
15230 | // If any errors have occurred, clear out any temporaries that may have | |||
15231 | // been leftover. This ensures that these temporaries won't be picked up for | |||
15232 | // deletion in some later function. | |||
15233 | if (hasUncompilableErrorOccurred()) { | |||
15234 | DiscardCleanupsInEvaluationContext(); | |||
15235 | } | |||
15236 | ||||
15237 | if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice || | |||
15238 | !LangOpts.OMPTargetTriples.empty())) || | |||
15239 | LangOpts.CUDA || LangOpts.SYCLIsDevice)) { | |||
15240 | auto ES = getEmissionStatus(FD); | |||
15241 | if (ES == Sema::FunctionEmissionStatus::Emitted || | |||
15242 | ES == Sema::FunctionEmissionStatus::Unknown) | |||
15243 | DeclsToCheckForDeferredDiags.insert(FD); | |||
15244 | } | |||
15245 | ||||
15246 | if (FD && !FD->isDeleted()) | |||
15247 | checkTypeSupport(FD->getType(), FD->getLocation(), FD); | |||
15248 | ||||
15249 | return dcl; | |||
15250 | } | |||
15251 | ||||
15252 | /// When we finish delayed parsing of an attribute, we must attach it to the | |||
15253 | /// relevant Decl. | |||
15254 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, | |||
15255 | ParsedAttributes &Attrs) { | |||
15256 | // Always attach attributes to the underlying decl. | |||
15257 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | |||
15258 | D = TD->getTemplatedDecl(); | |||
15259 | ProcessDeclAttributeList(S, D, Attrs); | |||
15260 | ||||
15261 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) | |||
15262 | if (Method->isStatic()) | |||
15263 | checkThisInStaticMemberFunctionAttributes(Method); | |||
15264 | } | |||
15265 | ||||
15266 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function | |||
15267 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). | |||
15268 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, | |||
15269 | IdentifierInfo &II, Scope *S) { | |||
15270 | // Find the scope in which the identifier is injected and the corresponding | |||
15271 | // DeclContext. | |||
15272 | // FIXME: C89 does not say what happens if there is no enclosing block scope. | |||
15273 | // In that case, we inject the declaration into the translation unit scope | |||
15274 | // instead. | |||
15275 | Scope *BlockScope = S; | |||
15276 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) | |||
15277 | BlockScope = BlockScope->getParent(); | |||
15278 | ||||
15279 | Scope *ContextScope = BlockScope; | |||
15280 | while (!ContextScope->getEntity()) | |||
15281 | ContextScope = ContextScope->getParent(); | |||
15282 | ContextRAII SavedContext(*this, ContextScope->getEntity()); | |||
15283 | ||||
15284 | // Before we produce a declaration for an implicitly defined | |||
15285 | // function, see whether there was a locally-scoped declaration of | |||
15286 | // this name as a function or variable. If so, use that | |||
15287 | // (non-visible) declaration, and complain about it. | |||
15288 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); | |||
15289 | if (ExternCPrev) { | |||
15290 | // We still need to inject the function into the enclosing block scope so | |||
15291 | // that later (non-call) uses can see it. | |||
15292 | PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); | |||
15293 | ||||
15294 | // C89 footnote 38: | |||
15295 | // If in fact it is not defined as having type "function returning int", | |||
15296 | // the behavior is undefined. | |||
15297 | if (!isa<FunctionDecl>(ExternCPrev) || | |||
15298 | !Context.typesAreCompatible( | |||
15299 | cast<FunctionDecl>(ExternCPrev)->getType(), | |||
15300 | Context.getFunctionNoProtoType(Context.IntTy))) { | |||
15301 | Diag(Loc, diag::ext_use_out_of_scope_declaration) | |||
15302 | << ExternCPrev << !getLangOpts().C99; | |||
15303 | Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); | |||
15304 | return ExternCPrev; | |||
15305 | } | |||
15306 | } | |||
15307 | ||||
15308 | // Extension in C99. Legal in C90, but warn about it. | |||
15309 | unsigned diag_id; | |||
15310 | if (II.getName().startswith("__builtin_")) | |||
15311 | diag_id = diag::warn_builtin_unknown; | |||
15312 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. | |||
15313 | else if (getLangOpts().OpenCL) | |||
15314 | diag_id = diag::err_opencl_implicit_function_decl; | |||
15315 | else if (getLangOpts().C99) | |||
15316 | diag_id = diag::ext_implicit_function_decl; | |||
15317 | else | |||
15318 | diag_id = diag::warn_implicit_function_decl; | |||
15319 | ||||
15320 | TypoCorrection Corrected; | |||
15321 | // Because typo correction is expensive, only do it if the implicit | |||
15322 | // function declaration is going to be treated as an error. | |||
15323 | // | |||
15324 | // Perform the corection before issuing the main diagnostic, as some consumers | |||
15325 | // use typo-correction callbacks to enhance the main diagnostic. | |||
15326 | if (S && !ExternCPrev && | |||
15327 | (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) { | |||
15328 | DeclFilterCCC<FunctionDecl> CCC{}; | |||
15329 | Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, | |||
15330 | S, nullptr, CCC, CTK_NonError); | |||
15331 | } | |||
15332 | ||||
15333 | Diag(Loc, diag_id) << &II; | |||
15334 | if (Corrected) | |||
15335 | diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), | |||
15336 | /*ErrorRecovery*/ false); | |||
15337 | ||||
15338 | // If we found a prior declaration of this function, don't bother building | |||
15339 | // another one. We've already pushed that one into scope, so there's nothing | |||
15340 | // more to do. | |||
15341 | if (ExternCPrev) | |||
15342 | return ExternCPrev; | |||
15343 | ||||
15344 | // Set a Declarator for the implicit definition: int foo(); | |||
15345 | const char *Dummy; | |||
15346 | AttributeFactory attrFactory; | |||
15347 | DeclSpec DS(attrFactory); | |||
15348 | unsigned DiagID; | |||
15349 | bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, | |||
15350 | Context.getPrintingPolicy()); | |||
15351 | (void)Error; // Silence warning. | |||
15352 | assert(!Error && "Error setting up implicit decl!")(static_cast <bool> (!Error && "Error setting up implicit decl!" ) ? void (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\"" , "clang/lib/Sema/SemaDecl.cpp", 15352, __extension__ __PRETTY_FUNCTION__ )); | |||
15353 | SourceLocation NoLoc; | |||
15354 | Declarator D(DS, DeclaratorContext::Block); | |||
15355 | D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, | |||
15356 | /*IsAmbiguous=*/false, | |||
15357 | /*LParenLoc=*/NoLoc, | |||
15358 | /*Params=*/nullptr, | |||
15359 | /*NumParams=*/0, | |||
15360 | /*EllipsisLoc=*/NoLoc, | |||
15361 | /*RParenLoc=*/NoLoc, | |||
15362 | /*RefQualifierIsLvalueRef=*/true, | |||
15363 | /*RefQualifierLoc=*/NoLoc, | |||
15364 | /*MutableLoc=*/NoLoc, EST_None, | |||
15365 | /*ESpecRange=*/SourceRange(), | |||
15366 | /*Exceptions=*/nullptr, | |||
15367 | /*ExceptionRanges=*/nullptr, | |||
15368 | /*NumExceptions=*/0, | |||
15369 | /*NoexceptExpr=*/nullptr, | |||
15370 | /*ExceptionSpecTokens=*/nullptr, | |||
15371 | /*DeclsInPrototype=*/None, Loc, | |||
15372 | Loc, D), | |||
15373 | std::move(DS.getAttributes()), SourceLocation()); | |||
15374 | D.SetIdentifier(&II, Loc); | |||
15375 | ||||
15376 | // Insert this function into the enclosing block scope. | |||
15377 | FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); | |||
15378 | FD->setImplicit(); | |||
15379 | ||||
15380 | AddKnownFunctionAttributes(FD); | |||
15381 | ||||
15382 | return FD; | |||
15383 | } | |||
15384 | ||||
15385 | /// If this function is a C++ replaceable global allocation function | |||
15386 | /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), | |||
15387 | /// adds any function attributes that we know a priori based on the standard. | |||
15388 | /// | |||
15389 | /// We need to check for duplicate attributes both here and where user-written | |||
15390 | /// attributes are applied to declarations. | |||
15391 | void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( | |||
15392 | FunctionDecl *FD) { | |||
15393 | if (FD->isInvalidDecl()) | |||
15394 | return; | |||
15395 | ||||
15396 | if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && | |||
15397 | FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) | |||
15398 | return; | |||
15399 | ||||
15400 | Optional<unsigned> AlignmentParam; | |||
15401 | bool IsNothrow = false; | |||
15402 | if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) | |||
15403 | return; | |||
15404 | ||||
15405 | // C++2a [basic.stc.dynamic.allocation]p4: | |||
15406 | // An allocation function that has a non-throwing exception specification | |||
15407 | // indicates failure by returning a null pointer value. Any other allocation | |||
15408 | // function never returns a null pointer value and indicates failure only by | |||
15409 | // throwing an exception [...] | |||
15410 | if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) | |||
15411 | FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); | |||
15412 | ||||
15413 | // C++2a [basic.stc.dynamic.allocation]p2: | |||
15414 | // An allocation function attempts to allocate the requested amount of | |||
15415 | // storage. [...] If the request succeeds, the value returned by a | |||
15416 | // replaceable allocation function is a [...] pointer value p0 different | |||
15417 | // from any previously returned value p1 [...] | |||
15418 | // | |||
15419 | // However, this particular information is being added in codegen, | |||
15420 | // because there is an opt-out switch for it (-fno-assume-sane-operator-new) | |||
15421 | ||||
15422 | // C++2a [basic.stc.dynamic.allocation]p2: | |||
15423 | // An allocation function attempts to allocate the requested amount of | |||
15424 | // storage. If it is successful, it returns the address of the start of a | |||
15425 | // block of storage whose length in bytes is at least as large as the | |||
15426 | // requested size. | |||
15427 | if (!FD->hasAttr<AllocSizeAttr>()) { | |||
15428 | FD->addAttr(AllocSizeAttr::CreateImplicit( | |||
15429 | Context, /*ElemSizeParam=*/ParamIdx(1, FD), | |||
15430 | /*NumElemsParam=*/ParamIdx(), FD->getLocation())); | |||
15431 | } | |||
15432 | ||||
15433 | // C++2a [basic.stc.dynamic.allocation]p3: | |||
15434 | // For an allocation function [...], the pointer returned on a successful | |||
15435 | // call shall represent the address of storage that is aligned as follows: | |||
15436 | // (3.1) If the allocation function takes an argument of type | |||
15437 | // std::align_val_t, the storage will have the alignment | |||
15438 | // specified by the value of this argument. | |||
15439 | if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { | |||
15440 | FD->addAttr(AllocAlignAttr::CreateImplicit( | |||
15441 | Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); | |||
15442 | } | |||
15443 | ||||
15444 | // FIXME: | |||
15445 | // C++2a [basic.stc.dynamic.allocation]p3: | |||
15446 | // For an allocation function [...], the pointer returned on a successful | |||
15447 | // call shall represent the address of storage that is aligned as follows: | |||
15448 | // (3.2) Otherwise, if the allocation function is named operator new[], | |||
15449 | // the storage is aligned for any object that does not have | |||
15450 | // new-extended alignment ([basic.align]) and is no larger than the | |||
15451 | // requested size. | |||
15452 | // (3.3) Otherwise, the storage is aligned for any object that does not | |||
15453 | // have new-extended alignment and is of the requested size. | |||
15454 | } | |||
15455 | ||||
15456 | /// Adds any function attributes that we know a priori based on | |||
15457 | /// the declaration of this function. | |||
15458 | /// | |||
15459 | /// These attributes can apply both to implicitly-declared builtins | |||
15460 | /// (like __builtin___printf_chk) or to library-declared functions | |||
15461 | /// like NSLog or printf. | |||
15462 | /// | |||
15463 | /// We need to check for duplicate attributes both here and where user-written | |||
15464 | /// attributes are applied to declarations. | |||
15465 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { | |||
15466 | if (FD->isInvalidDecl()) | |||
15467 | return; | |||
15468 | ||||
15469 | // If this is a built-in function, map its builtin attributes to | |||
15470 | // actual attributes. | |||
15471 | if (unsigned BuiltinID = FD->getBuiltinID()) { | |||
15472 | // Handle printf-formatting attributes. | |||
15473 | unsigned FormatIdx; | |||
15474 | bool HasVAListArg; | |||
15475 | if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { | |||
15476 | if (!FD->hasAttr<FormatAttr>()) { | |||
15477 | const char *fmt = "printf"; | |||
15478 | unsigned int NumParams = FD->getNumParams(); | |||
15479 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) | |||
15480 | FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) | |||
15481 | fmt = "NSString"; | |||
15482 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
15483 | &Context.Idents.get(fmt), | |||
15484 | FormatIdx+1, | |||
15485 | HasVAListArg ? 0 : FormatIdx+2, | |||
15486 | FD->getLocation())); | |||
15487 | } | |||
15488 | } | |||
15489 | if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, | |||
15490 | HasVAListArg)) { | |||
15491 | if (!FD->hasAttr<FormatAttr>()) | |||
15492 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
15493 | &Context.Idents.get("scanf"), | |||
15494 | FormatIdx+1, | |||
15495 | HasVAListArg ? 0 : FormatIdx+2, | |||
15496 | FD->getLocation())); | |||
15497 | } | |||
15498 | ||||
15499 | // Handle automatically recognized callbacks. | |||
15500 | SmallVector<int, 4> Encoding; | |||
15501 | if (!FD->hasAttr<CallbackAttr>() && | |||
15502 | Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) | |||
15503 | FD->addAttr(CallbackAttr::CreateImplicit( | |||
15504 | Context, Encoding.data(), Encoding.size(), FD->getLocation())); | |||
15505 | ||||
15506 | // Mark const if we don't care about errno and that is the only thing | |||
15507 | // preventing the function from being const. This allows IRgen to use LLVM | |||
15508 | // intrinsics for such functions. | |||
15509 | if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && | |||
15510 | Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) | |||
15511 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
15512 | ||||
15513 | // We make "fma" on GNU or Windows const because we know it does not set | |||
15514 | // errno in those environments even though it could set errno based on the | |||
15515 | // C standard. | |||
15516 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); | |||
15517 | if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) && | |||
15518 | !FD->hasAttr<ConstAttr>()) { | |||
15519 | switch (BuiltinID) { | |||
15520 | case Builtin::BI__builtin_fma: | |||
15521 | case Builtin::BI__builtin_fmaf: | |||
15522 | case Builtin::BI__builtin_fmal: | |||
15523 | case Builtin::BIfma: | |||
15524 | case Builtin::BIfmaf: | |||
15525 | case Builtin::BIfmal: | |||
15526 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
15527 | break; | |||
15528 | default: | |||
15529 | break; | |||
15530 | } | |||
15531 | } | |||
15532 | ||||
15533 | if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && | |||
15534 | !FD->hasAttr<ReturnsTwiceAttr>()) | |||
15535 | FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, | |||
15536 | FD->getLocation())); | |||
15537 | if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) | |||
15538 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | |||
15539 | if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) | |||
15540 | FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); | |||
15541 | if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) | |||
15542 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | |||
15543 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && | |||
15544 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { | |||
15545 | // Add the appropriate attribute, depending on the CUDA compilation mode | |||
15546 | // and which target the builtin belongs to. For example, during host | |||
15547 | // compilation, aux builtins are __device__, while the rest are __host__. | |||
15548 | if (getLangOpts().CUDAIsDevice != | |||
15549 | Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) | |||
15550 | FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); | |||
15551 | else | |||
15552 | FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); | |||
15553 | } | |||
15554 | ||||
15555 | // Add known guaranteed alignment for allocation functions. | |||
15556 | switch (BuiltinID) { | |||
15557 | case Builtin::BImemalign: | |||
15558 | case Builtin::BIaligned_alloc: | |||
15559 | if (!FD->hasAttr<AllocAlignAttr>()) | |||
15560 | FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD), | |||
15561 | FD->getLocation())); | |||
15562 | break; | |||
15563 | default: | |||
15564 | break; | |||
15565 | } | |||
15566 | ||||
15567 | // Add allocsize attribute for allocation functions. | |||
15568 | switch (BuiltinID) { | |||
15569 | case Builtin::BIcalloc: | |||
15570 | FD->addAttr(AllocSizeAttr::CreateImplicit( | |||
15571 | Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation())); | |||
15572 | break; | |||
15573 | case Builtin::BImemalign: | |||
15574 | case Builtin::BIaligned_alloc: | |||
15575 | case Builtin::BIrealloc: | |||
15576 | FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD), | |||
15577 | ParamIdx(), FD->getLocation())); | |||
15578 | break; | |||
15579 | case Builtin::BImalloc: | |||
15580 | FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD), | |||
15581 | ParamIdx(), FD->getLocation())); | |||
15582 | break; | |||
15583 | default: | |||
15584 | break; | |||
15585 | } | |||
15586 | } | |||
15587 | ||||
15588 | AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); | |||
15589 | ||||
15590 | // If C++ exceptions are enabled but we are told extern "C" functions cannot | |||
15591 | // throw, add an implicit nothrow attribute to any extern "C" function we come | |||
15592 | // across. | |||
15593 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && | |||
15594 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { | |||
15595 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); | |||
15596 | if (!FPT || FPT->getExceptionSpecType() == EST_None) | |||
15597 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | |||
15598 | } | |||
15599 | ||||
15600 | IdentifierInfo *Name = FD->getIdentifier(); | |||
15601 | if (!Name) | |||
15602 | return; | |||
15603 | if ((!getLangOpts().CPlusPlus && | |||
15604 | FD->getDeclContext()->isTranslationUnit()) || | |||
15605 | (isa<LinkageSpecDecl>(FD->getDeclContext()) && | |||
15606 | cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == | |||
15607 | LinkageSpecDecl::lang_c)) { | |||
15608 | // Okay: this could be a libc/libm/Objective-C function we know | |||
15609 | // about. | |||
15610 | } else | |||
15611 | return; | |||
15612 | ||||
15613 | if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { | |||
15614 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be | |||
15615 | // target-specific builtins, perhaps? | |||
15616 | if (!FD->hasAttr<FormatAttr>()) | |||
15617 | FD->addAttr(FormatAttr::CreateImplicit(Context, | |||
15618 | &Context.Idents.get("printf"), 2, | |||
15619 | Name->isStr("vasprintf") ? 0 : 3, | |||
15620 | FD->getLocation())); | |||
15621 | } | |||
15622 | ||||
15623 | if (Name->isStr("__CFStringMakeConstantString")) { | |||
15624 | // We already have a __builtin___CFStringMakeConstantString, | |||
15625 | // but builds that use -fno-constant-cfstrings don't go through that. | |||
15626 | if (!FD->hasAttr<FormatArgAttr>()) | |||
15627 | FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), | |||
15628 | FD->getLocation())); | |||
15629 | } | |||
15630 | } | |||
15631 | ||||
15632 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, | |||
15633 | TypeSourceInfo *TInfo) { | |||
15634 | assert(D.getIdentifier() && "Wrong callback for declspec without declarator")(static_cast <bool> (D.getIdentifier() && "Wrong callback for declspec without declarator" ) ? void (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\"" , "clang/lib/Sema/SemaDecl.cpp", 15634, __extension__ __PRETTY_FUNCTION__ )); | |||
15635 | assert(!T.isNull() && "GetTypeForDeclarator() returned null type")(static_cast <bool> (!T.isNull() && "GetTypeForDeclarator() returned null type" ) ? void (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\"" , "clang/lib/Sema/SemaDecl.cpp", 15635, __extension__ __PRETTY_FUNCTION__ )); | |||
15636 | ||||
15637 | if (!TInfo) { | |||
15638 | assert(D.isInvalidType() && "no declarator info for valid type")(static_cast <bool> (D.isInvalidType() && "no declarator info for valid type" ) ? void (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\"" , "clang/lib/Sema/SemaDecl.cpp", 15638, __extension__ __PRETTY_FUNCTION__ )); | |||
15639 | TInfo = Context.getTrivialTypeSourceInfo(T); | |||
15640 | } | |||
15641 | ||||
15642 | // Scope manipulation handled by caller. | |||
15643 | TypedefDecl *NewTD = | |||
15644 | TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), | |||
15645 | D.getIdentifierLoc(), D.getIdentifier(), TInfo); | |||
15646 | ||||
15647 | // Bail out immediately if we have an invalid declaration. | |||
15648 | if (D.isInvalidType()) { | |||
15649 | NewTD->setInvalidDecl(); | |||
15650 | return NewTD; | |||
15651 | } | |||
15652 | ||||
15653 | if (D.getDeclSpec().isModulePrivateSpecified()) { | |||
15654 | if (CurContext->isFunctionOrMethod()) | |||
15655 | Diag(NewTD->getLocation(), diag::err_module_private_local) | |||
15656 | << 2 << NewTD | |||
15657 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | |||
15658 | << FixItHint::CreateRemoval( | |||
15659 | D.getDeclSpec().getModulePrivateSpecLoc()); | |||
15660 | else | |||
15661 | NewTD->setModulePrivate(); | |||
15662 | } | |||
15663 | ||||
15664 | // C++ [dcl.typedef]p8: | |||
15665 | // If the typedef declaration defines an unnamed class (or | |||
15666 | // enum), the first typedef-name declared by the declaration | |||
15667 | // to be that class type (or enum type) is used to denote the | |||
15668 | // class type (or enum type) for linkage purposes only. | |||
15669 | // We need to check whether the type was declared in the declaration. | |||
15670 | switch (D.getDeclSpec().getTypeSpecType()) { | |||
15671 | case TST_enum: | |||
15672 | case TST_struct: | |||
15673 | case TST_interface: | |||
15674 | case TST_union: | |||
15675 | case TST_class: { | |||
15676 | TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | |||
15677 | setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); | |||
15678 | break; | |||
15679 | } | |||
15680 | ||||
15681 | default: | |||
15682 | break; | |||
15683 | } | |||
15684 | ||||
15685 | return NewTD; | |||
15686 | } | |||
15687 | ||||
15688 | /// Check that this is a valid underlying type for an enum declaration. | |||
15689 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { | |||
15690 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); | |||
15691 | QualType T = TI->getType(); | |||
15692 | ||||
15693 | if (T->isDependentType()) | |||
15694 | return false; | |||
15695 | ||||
15696 | // This doesn't use 'isIntegralType' despite the error message mentioning | |||
15697 | // integral type because isIntegralType would also allow enum types in C. | |||
15698 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) | |||
15699 | if (BT->isInteger()) | |||
15700 | return false; | |||
15701 | ||||
15702 | if (T->isBitIntType()) | |||
15703 | return false; | |||
15704 | ||||
15705 | return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; | |||
15706 | } | |||
15707 | ||||
15708 | /// Check whether this is a valid redeclaration of a previous enumeration. | |||
15709 | /// \return true if the redeclaration was invalid. | |||
15710 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, | |||
15711 | QualType EnumUnderlyingTy, bool IsFixed, | |||
15712 | const EnumDecl *Prev) { | |||
15713 | if (IsScoped != Prev->isScoped()) { | |||
15714 | Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) | |||
15715 | << Prev->isScoped(); | |||
15716 | Diag(Prev->getLocation(), diag::note_previous_declaration); | |||
15717 | return true; | |||
15718 | } | |||
15719 | ||||
15720 | if (IsFixed && Prev->isFixed()) { | |||
15721 | if (!EnumUnderlyingTy->isDependentType() && | |||
15722 | !Prev->getIntegerType()->isDependentType() && | |||
15723 | !Context.hasSameUnqualifiedType(EnumUnderlyingTy, | |||
15724 | Prev->getIntegerType())) { | |||
15725 | // TODO: Highlight the underlying type of the redeclaration. | |||
15726 | Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) | |||
15727 | << EnumUnderlyingTy << Prev->getIntegerType(); | |||
15728 | Diag(Prev->getLocation(), diag::note_previous_declaration) | |||
15729 | << Prev->getIntegerTypeRange(); | |||
15730 | return true; | |||
15731 | } | |||
15732 | } else if (IsFixed != Prev->isFixed()) { | |||
15733 | Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) | |||
15734 | << Prev->isFixed(); | |||
15735 | Diag(Prev->getLocation(), diag::note_previous_declaration); | |||
15736 | return true; | |||
15737 | } | |||
15738 | ||||
15739 | return false; | |||
15740 | } | |||
15741 | ||||
15742 | /// Get diagnostic %select index for tag kind for | |||
15743 | /// redeclaration diagnostic message. | |||
15744 | /// WARNING: Indexes apply to particular diagnostics only! | |||
15745 | /// | |||
15746 | /// \returns diagnostic %select index. | |||
15747 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { | |||
15748 | switch (Tag) { | |||
15749 | case TTK_Struct: return 0; | |||
15750 | case TTK_Interface: return 1; | |||
15751 | case TTK_Class: return 2; | |||
15752 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!" , "clang/lib/Sema/SemaDecl.cpp", 15752); | |||
15753 | } | |||
15754 | } | |||
15755 | ||||
15756 | /// Determine if tag kind is a class-key compatible with | |||
15757 | /// class for redeclaration (class, struct, or __interface). | |||
15758 | /// | |||
15759 | /// \returns true iff the tag kind is compatible. | |||
15760 | static bool isClassCompatTagKind(TagTypeKind Tag) | |||
15761 | { | |||
15762 | return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; | |||
15763 | } | |||
15764 | ||||
15765 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, | |||
15766 | TagTypeKind TTK) { | |||
15767 | if (isa<TypedefDecl>(PrevDecl)) | |||
15768 | return NTK_Typedef; | |||
15769 | else if (isa<TypeAliasDecl>(PrevDecl)) | |||
15770 | return NTK_TypeAlias; | |||
15771 | else if (isa<ClassTemplateDecl>(PrevDecl)) | |||
15772 | return NTK_Template; | |||
15773 | else if (isa<TypeAliasTemplateDecl>(PrevDecl)) | |||
15774 | return NTK_TypeAliasTemplate; | |||
15775 | else if (isa<TemplateTemplateParmDecl>(PrevDecl)) | |||
15776 | return NTK_TemplateTemplateArgument; | |||
15777 | switch (TTK) { | |||
15778 | case TTK_Struct: | |||
15779 | case TTK_Interface: | |||
15780 | case TTK_Class: | |||
15781 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; | |||
15782 | case TTK_Union: | |||
15783 | return NTK_NonUnion; | |||
15784 | case TTK_Enum: | |||
15785 | return NTK_NonEnum; | |||
15786 | } | |||
15787 | llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "clang/lib/Sema/SemaDecl.cpp" , 15787); | |||
15788 | } | |||
15789 | ||||
15790 | /// Determine whether a tag with a given kind is acceptable | |||
15791 | /// as a redeclaration of the given tag declaration. | |||
15792 | /// | |||
15793 | /// \returns true if the new tag kind is acceptable, false otherwise. | |||
15794 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, | |||
15795 | TagTypeKind NewTag, bool isDefinition, | |||
15796 | SourceLocation NewTagLoc, | |||
15797 | const IdentifierInfo *Name) { | |||
15798 | // C++ [dcl.type.elab]p3: | |||
15799 | // The class-key or enum keyword present in the | |||
15800 | // elaborated-type-specifier shall agree in kind with the | |||
15801 | // declaration to which the name in the elaborated-type-specifier | |||
15802 | // refers. This rule also applies to the form of | |||
15803 | // elaborated-type-specifier that declares a class-name or | |||
15804 | // friend class since it can be construed as referring to the | |||
15805 | // definition of the class. Thus, in any | |||
15806 | // elaborated-type-specifier, the enum keyword shall be used to | |||
15807 | // refer to an enumeration (7.2), the union class-key shall be | |||
15808 | // used to refer to a union (clause 9), and either the class or | |||
15809 | // struct class-key shall be used to refer to a class (clause 9) | |||
15810 | // declared using the class or struct class-key. | |||
15811 | TagTypeKind OldTag = Previous->getTagKind(); | |||
15812 | if (OldTag != NewTag && | |||
15813 | !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) | |||
15814 | return false; | |||
15815 | ||||
15816 | // Tags are compatible, but we might still want to warn on mismatched tags. | |||
15817 | // Non-class tags can't be mismatched at this point. | |||
15818 | if (!isClassCompatTagKind(NewTag)) | |||
15819 | return true; | |||
15820 | ||||
15821 | // Declarations for which -Wmismatched-tags is disabled are entirely ignored | |||
15822 | // by our warning analysis. We don't want to warn about mismatches with (eg) | |||
15823 | // declarations in system headers that are designed to be specialized, but if | |||
15824 | // a user asks us to warn, we should warn if their code contains mismatched | |||
15825 | // declarations. | |||
15826 | auto IsIgnoredLoc = [&](SourceLocation Loc) { | |||
15827 | return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, | |||
15828 | Loc); | |||
15829 | }; | |||
15830 | if (IsIgnoredLoc(NewTagLoc)) | |||
15831 | return true; | |||
15832 | ||||
15833 | auto IsIgnored = [&](const TagDecl *Tag) { | |||
15834 | return IsIgnoredLoc(Tag->getLocation()); | |||
15835 | }; | |||
15836 | while (IsIgnored(Previous)) { | |||
15837 | Previous = Previous->getPreviousDecl(); | |||
15838 | if (!Previous) | |||
15839 | return true; | |||
15840 | OldTag = Previous->getTagKind(); | |||
15841 | } | |||
15842 | ||||
15843 | bool isTemplate = false; | |||
15844 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) | |||
15845 | isTemplate = Record->getDescribedClassTemplate(); | |||
15846 | ||||
15847 | if (inTemplateInstantiation()) { | |||
15848 | if (OldTag != NewTag) { | |||
15849 | // In a template instantiation, do not offer fix-its for tag mismatches | |||
15850 | // since they usually mess up the template instead of fixing the problem. | |||
15851 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | |||
15852 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
15853 | << getRedeclDiagFromTagKind(OldTag); | |||
15854 | // FIXME: Note previous location? | |||
15855 | } | |||
15856 | return true; | |||
15857 | } | |||
15858 | ||||
15859 | if (isDefinition) { | |||
15860 | // On definitions, check all previous tags and issue a fix-it for each | |||
15861 | // one that doesn't match the current tag. | |||
15862 | if (Previous->getDefinition()) { | |||
15863 | // Don't suggest fix-its for redefinitions. | |||
15864 | return true; | |||
15865 | } | |||
15866 | ||||
15867 | bool previousMismatch = false; | |||
15868 | for (const TagDecl *I : Previous->redecls()) { | |||
15869 | if (I->getTagKind() != NewTag) { | |||
15870 | // Ignore previous declarations for which the warning was disabled. | |||
15871 | if (IsIgnored(I)) | |||
15872 | continue; | |||
15873 | ||||
15874 | if (!previousMismatch) { | |||
15875 | previousMismatch = true; | |||
15876 | Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) | |||
15877 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
15878 | << getRedeclDiagFromTagKind(I->getTagKind()); | |||
15879 | } | |||
15880 | Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) | |||
15881 | << getRedeclDiagFromTagKind(NewTag) | |||
15882 | << FixItHint::CreateReplacement(I->getInnerLocStart(), | |||
15883 | TypeWithKeyword::getTagTypeKindName(NewTag)); | |||
15884 | } | |||
15885 | } | |||
15886 | return true; | |||
15887 | } | |||
15888 | ||||
15889 | // Identify the prevailing tag kind: this is the kind of the definition (if | |||
15890 | // there is a non-ignored definition), or otherwise the kind of the prior | |||
15891 | // (non-ignored) declaration. | |||
15892 | const TagDecl *PrevDef = Previous->getDefinition(); | |||
15893 | if (PrevDef && IsIgnored(PrevDef)) | |||
15894 | PrevDef = nullptr; | |||
15895 | const TagDecl *Redecl = PrevDef ? PrevDef : Previous; | |||
15896 | if (Redecl->getTagKind() != NewTag) { | |||
15897 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | |||
15898 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | |||
15899 | << getRedeclDiagFromTagKind(OldTag); | |||
15900 | Diag(Redecl->getLocation(), diag::note_previous_use); | |||
15901 | ||||
15902 | // If there is a previous definition, suggest a fix-it. | |||
15903 | if (PrevDef) { | |||
15904 | Diag(NewTagLoc, diag::note_struct_class_suggestion) | |||
15905 | << getRedeclDiagFromTagKind(Redecl->getTagKind()) | |||
15906 | << FixItHint::CreateReplacement(SourceRange(NewTagLoc), | |||
15907 | TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); | |||
15908 | } | |||
15909 | } | |||
15910 | ||||
15911 | return true; | |||
15912 | } | |||
15913 | ||||
15914 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name | |||
15915 | /// from an outer enclosing namespace or file scope inside a friend declaration. | |||
15916 | /// This should provide the commented out code in the following snippet: | |||
15917 | /// namespace N { | |||
15918 | /// struct X; | |||
15919 | /// namespace M { | |||
15920 | /// struct Y { friend struct /*N::*/ X; }; | |||
15921 | /// } | |||
15922 | /// } | |||
15923 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, | |||
15924 | SourceLocation NameLoc) { | |||
15925 | // While the decl is in a namespace, do repeated lookup of that name and see | |||
15926 | // if we get the same namespace back. If we do not, continue until | |||
15927 | // translation unit scope, at which point we have a fully qualified NNS. | |||
15928 | SmallVector<IdentifierInfo *, 4> Namespaces; | |||
15929 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | |||
15930 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { | |||
15931 | // This tag should be declared in a namespace, which can only be enclosed by | |||
15932 | // other namespaces. Bail if there's an anonymous namespace in the chain. | |||
15933 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); | |||
15934 | if (!Namespace || Namespace->isAnonymousNamespace()) | |||
15935 | return FixItHint(); | |||
15936 | IdentifierInfo *II = Namespace->getIdentifier(); | |||
15937 | Namespaces.push_back(II); | |||
15938 | NamedDecl *Lookup = SemaRef.LookupSingleName( | |||
15939 | S, II, NameLoc, Sema::LookupNestedNameSpecifierName); | |||
15940 | if (Lookup == Namespace) | |||
15941 | break; | |||
15942 | } | |||
15943 | ||||
15944 | // Once we have all the namespaces, reverse them to go outermost first, and | |||
15945 | // build an NNS. | |||
15946 | SmallString<64> Insertion; | |||
15947 | llvm::raw_svector_ostream OS(Insertion); | |||
15948 | if (DC->isTranslationUnit()) | |||
15949 | OS << "::"; | |||
15950 | std::reverse(Namespaces.begin(), Namespaces.end()); | |||
15951 | for (auto *II : Namespaces) | |||
15952 | OS << II->getName() << "::"; | |||
15953 | return FixItHint::CreateInsertion(NameLoc, Insertion); | |||
15954 | } | |||
15955 | ||||
15956 | /// Determine whether a tag originally declared in context \p OldDC can | |||
15957 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup | |||
15958 | /// found a declaration in \p OldDC as a previous decl, perhaps through a | |||
15959 | /// using-declaration). | |||
15960 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, | |||
15961 | DeclContext *NewDC) { | |||
15962 | OldDC = OldDC->getRedeclContext(); | |||
15963 | NewDC = NewDC->getRedeclContext(); | |||
15964 | ||||
15965 | if (OldDC->Equals(NewDC)) | |||
15966 | return true; | |||
15967 | ||||
15968 | // In MSVC mode, we allow a redeclaration if the contexts are related (either | |||
15969 | // encloses the other). | |||
15970 | if (S.getLangOpts().MSVCCompat && | |||
15971 | (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) | |||
15972 | return true; | |||
15973 | ||||
15974 | return false; | |||
15975 | } | |||
15976 | ||||
15977 | /// This is invoked when we see 'struct foo' or 'struct {'. In the | |||
15978 | /// former case, Name will be non-null. In the later case, Name will be null. | |||
15979 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a | |||
15980 | /// reference/declaration/definition of a tag. | |||
15981 | /// | |||
15982 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or | |||
15983 | /// trailing-type-specifier) other than one in an alias-declaration. | |||
15984 | /// | |||
15985 | /// \param SkipBody If non-null, will be set to indicate if the caller should | |||
15986 | /// skip the definition of this tag and treat it as if it were a declaration. | |||
15987 | Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, | |||
15988 | SourceLocation KWLoc, CXXScopeSpec &SS, | |||
15989 | IdentifierInfo *Name, SourceLocation NameLoc, | |||
15990 | const ParsedAttributesView &Attrs, AccessSpecifier AS, | |||
15991 | SourceLocation ModulePrivateLoc, | |||
15992 | MultiTemplateParamsArg TemplateParameterLists, | |||
15993 | bool &OwnedDecl, bool &IsDependent, | |||
15994 | SourceLocation ScopedEnumKWLoc, | |||
15995 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, | |||
15996 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, | |||
15997 | SkipBodyInfo *SkipBody) { | |||
15998 | // If this is not a definition, it must have a name. | |||
15999 | IdentifierInfo *OrigName = Name; | |||
16000 | assert((Name != nullptr || TUK == TUK_Definition) &&(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition ) && "Nameless record must be a definition!") ? void ( 0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "clang/lib/Sema/SemaDecl.cpp", 16001, __extension__ __PRETTY_FUNCTION__ )) | |||
16001 | "Nameless record must be a definition!")(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition ) && "Nameless record must be a definition!") ? void ( 0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "clang/lib/Sema/SemaDecl.cpp", 16001, __extension__ __PRETTY_FUNCTION__ )); | |||
16002 | assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)(static_cast <bool> (TemplateParameterLists.size() == 0 || TUK != TUK_Reference) ? void (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference" , "clang/lib/Sema/SemaDecl.cpp", 16002, __extension__ __PRETTY_FUNCTION__ )); | |||
16003 | ||||
16004 | OwnedDecl = false; | |||
16005 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | |||
16006 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); | |||
16007 | ||||
16008 | // FIXME: Check member specializations more carefully. | |||
16009 | bool isMemberSpecialization = false; | |||
16010 | bool Invalid = false; | |||
16011 | ||||
16012 | // We only need to do this matching if we have template parameters | |||
16013 | // or a scope specifier, which also conveniently avoids this work | |||
16014 | // for non-C++ cases. | |||
16015 | if (TemplateParameterLists.size() > 0 || | |||
16016 | (SS.isNotEmpty() && TUK != TUK_Reference)) { | |||
16017 | if (TemplateParameterList *TemplateParams = | |||
16018 | MatchTemplateParametersToScopeSpecifier( | |||
16019 | KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, | |||
16020 | TUK == TUK_Friend, isMemberSpecialization, Invalid)) { | |||
16021 | if (Kind == TTK_Enum) { | |||
16022 | Diag(KWLoc, diag::err_enum_template); | |||
16023 | return nullptr; | |||
16024 | } | |||
16025 | ||||
16026 | if (TemplateParams->size() > 0) { | |||
16027 | // This is a declaration or definition of a class template (which may | |||
16028 | // be a member of another template). | |||
16029 | ||||
16030 | if (Invalid) | |||
16031 | return nullptr; | |||
16032 | ||||
16033 | OwnedDecl = false; | |||
16034 | DeclResult Result = CheckClassTemplate( | |||
16035 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, | |||
16036 | AS, ModulePrivateLoc, | |||
16037 | /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, | |||
16038 | TemplateParameterLists.data(), SkipBody); | |||
16039 | return Result.get(); | |||
16040 | } else { | |||
16041 | // The "template<>" header is extraneous. | |||
16042 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | |||
16043 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | |||
16044 | isMemberSpecialization = true; | |||
16045 | } | |||
16046 | } | |||
16047 | ||||
16048 | if (!TemplateParameterLists.empty() && isMemberSpecialization && | |||
16049 | CheckTemplateDeclScope(S, TemplateParameterLists.back())) | |||
16050 | return nullptr; | |||
16051 | } | |||
16052 | ||||
16053 | // Figure out the underlying type if this a enum declaration. We need to do | |||
16054 | // this early, because it's needed to detect if this is an incompatible | |||
16055 | // redeclaration. | |||
16056 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; | |||
16057 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; | |||
16058 | ||||
16059 | if (Kind == TTK_Enum) { | |||
16060 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { | |||
16061 | // No underlying type explicitly specified, or we failed to parse the | |||
16062 | // type, default to int. | |||
16063 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
16064 | } else if (UnderlyingType.get()) { | |||
16065 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an | |||
16066 | // integral type; any cv-qualification is ignored. | |||
16067 | TypeSourceInfo *TI = nullptr; | |||
16068 | GetTypeFromParser(UnderlyingType.get(), &TI); | |||
16069 | EnumUnderlying = TI; | |||
16070 | ||||
16071 | if (CheckEnumUnderlyingType(TI)) | |||
16072 | // Recover by falling back to int. | |||
16073 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
16074 | ||||
16075 | if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, | |||
16076 | UPPC_FixedUnderlyingType)) | |||
16077 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
16078 | ||||
16079 | } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { | |||
16080 | // For MSVC ABI compatibility, unfixed enums must use an underlying type | |||
16081 | // of 'int'. However, if this is an unfixed forward declaration, don't set | |||
16082 | // the underlying type unless the user enables -fms-compatibility. This | |||
16083 | // makes unfixed forward declared enums incomplete and is more conforming. | |||
16084 | if (TUK == TUK_Definition || getLangOpts().MSVCCompat) | |||
16085 | EnumUnderlying = Context.IntTy.getTypePtr(); | |||
16086 | } | |||
16087 | } | |||
16088 | ||||
16089 | DeclContext *SearchDC = CurContext; | |||
16090 | DeclContext *DC = CurContext; | |||
16091 | bool isStdBadAlloc = false; | |||
16092 | bool isStdAlignValT = false; | |||
16093 | ||||
16094 | RedeclarationKind Redecl = forRedeclarationInCurContext(); | |||
16095 | if (TUK == TUK_Friend || TUK == TUK_Reference) | |||
16096 | Redecl = NotForRedeclaration; | |||
16097 | ||||
16098 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C | |||
16099 | /// implemented asks for structural equivalence checking, the returned decl | |||
16100 | /// here is passed back to the parser, allowing the tag body to be parsed. | |||
16101 | auto createTagFromNewDecl = [&]() -> TagDecl * { | |||
16102 | assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")(static_cast <bool> (!getLangOpts().CPlusPlus && "not meant for C++ usage") ? void (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\"" , "clang/lib/Sema/SemaDecl.cpp", 16102, __extension__ __PRETTY_FUNCTION__ )); | |||
16103 | // If there is an identifier, use the location of the identifier as the | |||
16104 | // location of the decl, otherwise use the location of the struct/union | |||
16105 | // keyword. | |||
16106 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | |||
16107 | TagDecl *New = nullptr; | |||
16108 | ||||
16109 | if (Kind == TTK_Enum) { | |||
16110 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, | |||
16111 | ScopedEnum, ScopedEnumUsesClassTag, IsFixed); | |||
16112 | // If this is an undefined enum, bail. | |||
16113 | if (TUK != TUK_Definition && !Invalid) | |||
16114 | return nullptr; | |||
16115 | if (EnumUnderlying) { | |||
16116 | EnumDecl *ED = cast<EnumDecl>(New); | |||
16117 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) | |||
16118 | ED->setIntegerTypeSourceInfo(TI); | |||
16119 | else | |||
16120 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); | |||
16121 | ED->setPromotionType(ED->getIntegerType()); | |||
16122 | } | |||
16123 | } else { // struct/union | |||
16124 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
16125 | nullptr); | |||
16126 | } | |||
16127 | ||||
16128 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | |||
16129 | // Add alignment attributes if necessary; these attributes are checked | |||
16130 | // when the ASTContext lays out the structure. | |||
16131 | // | |||
16132 | // It is important for implementing the correct semantics that this | |||
16133 | // happen here (in ActOnTag). The #pragma pack stack is | |||
16134 | // maintained as a result of parser callbacks which can occur at | |||
16135 | // many points during the parsing of a struct declaration (because | |||
16136 | // the #pragma tokens are effectively skipped over during the | |||
16137 | // parsing of the struct). | |||
16138 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | |||
16139 | AddAlignmentAttributesForRecord(RD); | |||
16140 | AddMsStructLayoutForRecord(RD); | |||
16141 | } | |||
16142 | } | |||
16143 | New->setLexicalDeclContext(CurContext); | |||
16144 | return New; | |||
16145 | }; | |||
16146 | ||||
16147 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); | |||
16148 | if (Name && SS.isNotEmpty()) { | |||
16149 | // We have a nested-name tag ('struct foo::bar'). | |||
16150 | ||||
16151 | // Check for invalid 'foo::'. | |||
16152 | if (SS.isInvalid()) { | |||
16153 | Name = nullptr; | |||
16154 | goto CreateNewDecl; | |||
16155 | } | |||
16156 | ||||
16157 | // If this is a friend or a reference to a class in a dependent | |||
16158 | // context, don't try to make a decl for it. | |||
16159 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | |||
16160 | DC = computeDeclContext(SS, false); | |||
16161 | if (!DC) { | |||
16162 | IsDependent = true; | |||
16163 | return nullptr; | |||
16164 | } | |||
16165 | } else { | |||
16166 | DC = computeDeclContext(SS, true); | |||
16167 | if (!DC) { | |||
16168 | Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) | |||
16169 | << SS.getRange(); | |||
16170 | return nullptr; | |||
16171 | } | |||
16172 | } | |||
16173 | ||||
16174 | if (RequireCompleteDeclContext(SS, DC)) | |||
16175 | return nullptr; | |||
16176 | ||||
16177 | SearchDC = DC; | |||
16178 | // Look-up name inside 'foo::'. | |||
16179 | LookupQualifiedName(Previous, DC); | |||
16180 | ||||
16181 | if (Previous.isAmbiguous()) | |||
16182 | return nullptr; | |||
16183 | ||||
16184 | if (Previous.empty()) { | |||
16185 | // Name lookup did not find anything. However, if the | |||
16186 | // nested-name-specifier refers to the current instantiation, | |||
16187 | // and that current instantiation has any dependent base | |||
16188 | // classes, we might find something at instantiation time: treat | |||
16189 | // this as a dependent elaborated-type-specifier. | |||
16190 | // But this only makes any sense for reference-like lookups. | |||
16191 | if (Previous.wasNotFoundInCurrentInstantiation() && | |||
16192 | (TUK == TUK_Reference || TUK == TUK_Friend)) { | |||
16193 | IsDependent = true; | |||
16194 | return nullptr; | |||
16195 | } | |||
16196 | ||||
16197 | // A tag 'foo::bar' must already exist. | |||
16198 | Diag(NameLoc, diag::err_not_tag_in_scope) | |||
16199 | << Kind << Name << DC << SS.getRange(); | |||
16200 | Name = nullptr; | |||
16201 | Invalid = true; | |||
16202 | goto CreateNewDecl; | |||
16203 | } | |||
16204 | } else if (Name) { | |||
16205 | // C++14 [class.mem]p14: | |||
16206 | // If T is the name of a class, then each of the following shall have a | |||
16207 | // name different from T: | |||
16208 | // -- every member of class T that is itself a type | |||
16209 | if (TUK != TUK_Reference && TUK != TUK_Friend && | |||
16210 | DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) | |||
16211 | return nullptr; | |||
16212 | ||||
16213 | // If this is a named struct, check to see if there was a previous forward | |||
16214 | // declaration or definition. | |||
16215 | // FIXME: We're looking into outer scopes here, even when we | |||
16216 | // shouldn't be. Doing so can result in ambiguities that we | |||
16217 | // shouldn't be diagnosing. | |||
16218 | LookupName(Previous, S); | |||
16219 | ||||
16220 | // When declaring or defining a tag, ignore ambiguities introduced | |||
16221 | // by types using'ed into this scope. | |||
16222 | if (Previous.isAmbiguous() && | |||
16223 | (TUK == TUK_Definition || TUK == TUK_Declaration)) { | |||
16224 | LookupResult::Filter F = Previous.makeFilter(); | |||
16225 | while (F.hasNext()) { | |||
16226 | NamedDecl *ND = F.next(); | |||
16227 | if (!ND->getDeclContext()->getRedeclContext()->Equals( | |||
16228 | SearchDC->getRedeclContext())) | |||
16229 | F.erase(); | |||
16230 | } | |||
16231 | F.done(); | |||
16232 | } | |||
16233 | ||||
16234 | // C++11 [namespace.memdef]p3: | |||
16235 | // If the name in a friend declaration is neither qualified nor | |||
16236 | // a template-id and the declaration is a function or an | |||
16237 | // elaborated-type-specifier, the lookup to determine whether | |||
16238 | // the entity has been previously declared shall not consider | |||
16239 | // any scopes outside the innermost enclosing namespace. | |||
16240 | // | |||
16241 | // MSVC doesn't implement the above rule for types, so a friend tag | |||
16242 | // declaration may be a redeclaration of a type declared in an enclosing | |||
16243 | // scope. They do implement this rule for friend functions. | |||
16244 | // | |||
16245 | // Does it matter that this should be by scope instead of by | |||
16246 | // semantic context? | |||
16247 | if (!Previous.empty() && TUK == TUK_Friend) { | |||
16248 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); | |||
16249 | LookupResult::Filter F = Previous.makeFilter(); | |||
16250 | bool FriendSawTagOutsideEnclosingNamespace = false; | |||
16251 | while (F.hasNext()) { | |||
16252 | NamedDecl *ND = F.next(); | |||
16253 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | |||
16254 | if (DC->isFileContext() && | |||
16255 | !EnclosingNS->Encloses(ND->getDeclContext())) { | |||
16256 | if (getLangOpts().MSVCCompat) | |||
16257 | FriendSawTagOutsideEnclosingNamespace = true; | |||
16258 | else | |||
16259 | F.erase(); | |||
16260 | } | |||
16261 | } | |||
16262 | F.done(); | |||
16263 | ||||
16264 | // Diagnose this MSVC extension in the easy case where lookup would have | |||
16265 | // unambiguously found something outside the enclosing namespace. | |||
16266 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { | |||
16267 | NamedDecl *ND = Previous.getFoundDecl(); | |||
16268 | Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) | |||
16269 | << createFriendTagNNSFixIt(*this, ND, S, NameLoc); | |||
16270 | } | |||
16271 | } | |||
16272 | ||||
16273 | // Note: there used to be some attempt at recovery here. | |||
16274 | if (Previous.isAmbiguous()) | |||
16275 | return nullptr; | |||
16276 | ||||
16277 | if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { | |||
16278 | // FIXME: This makes sure that we ignore the contexts associated | |||
16279 | // with C structs, unions, and enums when looking for a matching | |||
16280 | // tag declaration or definition. See the similar lookup tweak | |||
16281 | // in Sema::LookupName; is there a better way to deal with this? | |||
16282 | while (isa<RecordDecl, EnumDecl, ObjCContainerDecl>(SearchDC)) | |||
16283 | SearchDC = SearchDC->getParent(); | |||
16284 | } else if (getLangOpts().CPlusPlus) { | |||
16285 | // Inside ObjCContainer want to keep it as a lexical decl context but go | |||
16286 | // past it (most often to TranslationUnit) to find the semantic decl | |||
16287 | // context. | |||
16288 | while (isa<ObjCContainerDecl>(SearchDC)) | |||
16289 | SearchDC = SearchDC->getParent(); | |||
16290 | } | |||
16291 | } else if (getLangOpts().CPlusPlus) { | |||
16292 | // Don't use ObjCContainerDecl as the semantic decl context for anonymous | |||
16293 | // TagDecl the same way as we skip it for named TagDecl. | |||
16294 | while (isa<ObjCContainerDecl>(SearchDC)) | |||
16295 | SearchDC = SearchDC->getParent(); | |||
16296 | } | |||
16297 | ||||
16298 | if (Previous.isSingleResult() && | |||
16299 | Previous.getFoundDecl()->isTemplateParameter()) { | |||
16300 | // Maybe we will complain about the shadowed template parameter. | |||
16301 | DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); | |||
16302 | // Just pretend that we didn't see the previous declaration. | |||
16303 | Previous.clear(); | |||
16304 | } | |||
16305 | ||||
16306 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && | |||
16307 | DC->Equals(getStdNamespace())) { | |||
16308 | if (Name->isStr("bad_alloc")) { | |||
16309 | // This is a declaration of or a reference to "std::bad_alloc". | |||
16310 | isStdBadAlloc = true; | |||
16311 | ||||
16312 | // If std::bad_alloc has been implicitly declared (but made invisible to | |||
16313 | // name lookup), fill in this implicit declaration as the previous | |||
16314 | // declaration, so that the declarations get chained appropriately. | |||
16315 | if (Previous.empty() && StdBadAlloc) | |||
16316 | Previous.addDecl(getStdBadAlloc()); | |||
16317 | } else if (Name->isStr("align_val_t")) { | |||
16318 | isStdAlignValT = true; | |||
16319 | if (Previous.empty() && StdAlignValT) | |||
16320 | Previous.addDecl(getStdAlignValT()); | |||
16321 | } | |||
16322 | } | |||
16323 | ||||
16324 | // If we didn't find a previous declaration, and this is a reference | |||
16325 | // (or friend reference), move to the correct scope. In C++, we | |||
16326 | // also need to do a redeclaration lookup there, just in case | |||
16327 | // there's a shadow friend decl. | |||
16328 | if (Name && Previous.empty() && | |||
16329 | (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { | |||
16330 | if (Invalid) goto CreateNewDecl; | |||
16331 | assert(SS.isEmpty())(static_cast <bool> (SS.isEmpty()) ? void (0) : __assert_fail ("SS.isEmpty()", "clang/lib/Sema/SemaDecl.cpp", 16331, __extension__ __PRETTY_FUNCTION__)); | |||
16332 | ||||
16333 | if (TUK == TUK_Reference || IsTemplateParamOrArg) { | |||
16334 | // C++ [basic.scope.pdecl]p5: | |||
16335 | // -- for an elaborated-type-specifier of the form | |||
16336 | // | |||
16337 | // class-key identifier | |||
16338 | // | |||
16339 | // if the elaborated-type-specifier is used in the | |||
16340 | // decl-specifier-seq or parameter-declaration-clause of a | |||
16341 | // function defined in namespace scope, the identifier is | |||
16342 | // declared as a class-name in the namespace that contains | |||
16343 | // the declaration; otherwise, except as a friend | |||
16344 | // declaration, the identifier is declared in the smallest | |||
16345 | // non-class, non-function-prototype scope that contains the | |||
16346 | // declaration. | |||
16347 | // | |||
16348 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for | |||
16349 | // C structs and unions. | |||
16350 | // | |||
16351 | // It is an error in C++ to declare (rather than define) an enum | |||
16352 | // type, including via an elaborated type specifier. We'll | |||
16353 | // diagnose that later; for now, declare the enum in the same | |||
16354 | // scope as we would have picked for any other tag type. | |||
16355 | // | |||
16356 | // GNU C also supports this behavior as part of its incomplete | |||
16357 | // enum types extension, while GNU C++ does not. | |||
16358 | // | |||
16359 | // Find the context where we'll be declaring the tag. | |||
16360 | // FIXME: We would like to maintain the current DeclContext as the | |||
16361 | // lexical context, | |||
16362 | SearchDC = getTagInjectionContext(SearchDC); | |||
16363 | ||||
16364 | // Find the scope where we'll be declaring the tag. | |||
16365 | S = getTagInjectionScope(S, getLangOpts()); | |||
16366 | } else { | |||
16367 | assert(TUK == TUK_Friend)(static_cast <bool> (TUK == TUK_Friend) ? void (0) : __assert_fail ("TUK == TUK_Friend", "clang/lib/Sema/SemaDecl.cpp", 16367, __extension__ __PRETTY_FUNCTION__)); | |||
16368 | // C++ [namespace.memdef]p3: | |||
16369 | // If a friend declaration in a non-local class first declares a | |||
16370 | // class or function, the friend class or function is a member of | |||
16371 | // the innermost enclosing namespace. | |||
16372 | SearchDC = SearchDC->getEnclosingNamespaceContext(); | |||
16373 | } | |||
16374 | ||||
16375 | // In C++, we need to do a redeclaration lookup to properly | |||
16376 | // diagnose some problems. | |||
16377 | // FIXME: redeclaration lookup is also used (with and without C++) to find a | |||
16378 | // hidden declaration so that we don't get ambiguity errors when using a | |||
16379 | // type declared by an elaborated-type-specifier. In C that is not correct | |||
16380 | // and we should instead merge compatible types found by lookup. | |||
16381 | if (getLangOpts().CPlusPlus) { | |||
16382 | // FIXME: This can perform qualified lookups into function contexts, | |||
16383 | // which are meaningless. | |||
16384 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | |||
16385 | LookupQualifiedName(Previous, SearchDC); | |||
16386 | } else { | |||
16387 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | |||
16388 | LookupName(Previous, S); | |||
16389 | } | |||
16390 | } | |||
16391 | ||||
16392 | // If we have a known previous declaration to use, then use it. | |||
16393 | if (Previous.empty() && SkipBody && SkipBody->Previous) | |||
16394 | Previous.addDecl(SkipBody->Previous); | |||
16395 | ||||
16396 | if (!Previous.empty()) { | |||
16397 | NamedDecl *PrevDecl = Previous.getFoundDecl(); | |||
16398 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); | |||
16399 | ||||
16400 | // It's okay to have a tag decl in the same scope as a typedef | |||
16401 | // which hides a tag decl in the same scope. Finding this | |||
16402 | // with a redeclaration lookup can only actually happen in C++. | |||
16403 | // | |||
16404 | // This is also okay for elaborated-type-specifiers, which is | |||
16405 | // technically forbidden by the current standard but which is | |||
16406 | // okay according to the likely resolution of an open issue; | |||
16407 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 | |||
16408 | if (getLangOpts().CPlusPlus) { | |||
16409 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { | |||
16410 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { | |||
16411 | TagDecl *Tag = TT->getDecl(); | |||
16412 | if (Tag->getDeclName() == Name && | |||
16413 | Tag->getDeclContext()->getRedeclContext() | |||
16414 | ->Equals(TD->getDeclContext()->getRedeclContext())) { | |||
16415 | PrevDecl = Tag; | |||
16416 | Previous.clear(); | |||
16417 | Previous.addDecl(Tag); | |||
16418 | Previous.resolveKind(); | |||
16419 | } | |||
16420 | } | |||
16421 | } | |||
16422 | } | |||
16423 | ||||
16424 | // If this is a redeclaration of a using shadow declaration, it must | |||
16425 | // declare a tag in the same context. In MSVC mode, we allow a | |||
16426 | // redefinition if either context is within the other. | |||
16427 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { | |||
16428 | auto *OldTag = dyn_cast<TagDecl>(PrevDecl); | |||
16429 | if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && | |||
16430 | isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && | |||
16431 | !(OldTag && isAcceptableTagRedeclContext( | |||
16432 | *this, OldTag->getDeclContext(), SearchDC))) { | |||
16433 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); | |||
16434 | Diag(Shadow->getTargetDecl()->getLocation(), | |||
16435 | diag::note_using_decl_target); | |||
16436 | Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) | |||
16437 | << 0; | |||
16438 | // Recover by ignoring the old declaration. | |||
16439 | Previous.clear(); | |||
16440 | goto CreateNewDecl; | |||
16441 | } | |||
16442 | } | |||
16443 | ||||
16444 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { | |||
16445 | // If this is a use of a previous tag, or if the tag is already declared | |||
16446 | // in the same scope (so that the definition/declaration completes or | |||
16447 | // rementions the tag), reuse the decl. | |||
16448 | if (TUK == TUK_Reference || TUK == TUK_Friend || | |||
16449 | isDeclInScope(DirectPrevDecl, SearchDC, S, | |||
16450 | SS.isNotEmpty() || isMemberSpecialization)) { | |||
16451 | // Make sure that this wasn't declared as an enum and now used as a | |||
16452 | // struct or something similar. | |||
16453 | if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, | |||
16454 | TUK == TUK_Definition, KWLoc, | |||
16455 | Name)) { | |||
16456 | bool SafeToContinue | |||
16457 | = (PrevTagDecl->getTagKind() != TTK_Enum && | |||
16458 | Kind != TTK_Enum); | |||
16459 | if (SafeToContinue) | |||
16460 | Diag(KWLoc, diag::err_use_with_wrong_tag) | |||
16461 | << Name | |||
16462 | << FixItHint::CreateReplacement(SourceRange(KWLoc), | |||
16463 | PrevTagDecl->getKindName()); | |||
16464 | else | |||
16465 | Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; | |||
16466 | Diag(PrevTagDecl->getLocation(), diag::note_previous_use); | |||
16467 | ||||
16468 | if (SafeToContinue) | |||
16469 | Kind = PrevTagDecl->getTagKind(); | |||
16470 | else { | |||
16471 | // Recover by making this an anonymous redefinition. | |||
16472 | Name = nullptr; | |||
16473 | Previous.clear(); | |||
16474 | Invalid = true; | |||
16475 | } | |||
16476 | } | |||
16477 | ||||
16478 | if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { | |||
16479 | const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); | |||
16480 | if (TUK == TUK_Reference || TUK == TUK_Friend) | |||
16481 | return PrevTagDecl; | |||
16482 | ||||
16483 | QualType EnumUnderlyingTy; | |||
16484 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | |||
16485 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); | |||
16486 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) | |||
16487 | EnumUnderlyingTy = QualType(T, 0); | |||
16488 | ||||
16489 | // All conflicts with previous declarations are recovered by | |||
16490 | // returning the previous declaration, unless this is a definition, | |||
16491 | // in which case we want the caller to bail out. | |||
16492 | if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, | |||
16493 | ScopedEnum, EnumUnderlyingTy, | |||
16494 | IsFixed, PrevEnum)) | |||
16495 | return TUK == TUK_Declaration ? PrevTagDecl : nullptr; | |||
16496 | } | |||
16497 | ||||
16498 | // C++11 [class.mem]p1: | |||
16499 | // A member shall not be declared twice in the member-specification, | |||
16500 | // except that a nested class or member class template can be declared | |||
16501 | // and then later defined. | |||
16502 | if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && | |||
16503 | S->isDeclScope(PrevDecl)) { | |||
16504 | Diag(NameLoc, diag::ext_member_redeclared); | |||
16505 | Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); | |||
16506 | } | |||
16507 | ||||
16508 | if (!Invalid) { | |||
16509 | // If this is a use, just return the declaration we found, unless | |||
16510 | // we have attributes. | |||
16511 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | |||
16512 | if (!Attrs.empty()) { | |||
16513 | // FIXME: Diagnose these attributes. For now, we create a new | |||
16514 | // declaration to hold them. | |||
16515 | } else if (TUK == TUK_Reference && | |||
16516 | (PrevTagDecl->getFriendObjectKind() == | |||
16517 | Decl::FOK_Undeclared || | |||
16518 | PrevDecl->getOwningModule() != getCurrentModule()) && | |||
16519 | SS.isEmpty()) { | |||
16520 | // This declaration is a reference to an existing entity, but | |||
16521 | // has different visibility from that entity: it either makes | |||
16522 | // a friend visible or it makes a type visible in a new module. | |||
16523 | // In either case, create a new declaration. We only do this if | |||
16524 | // the declaration would have meant the same thing if no prior | |||
16525 | // declaration were found, that is, if it was found in the same | |||
16526 | // scope where we would have injected a declaration. | |||
16527 | if (!getTagInjectionContext(CurContext)->getRedeclContext() | |||
16528 | ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) | |||
16529 | return PrevTagDecl; | |||
16530 | // This is in the injected scope, create a new declaration in | |||
16531 | // that scope. | |||
16532 | S = getTagInjectionScope(S, getLangOpts()); | |||
16533 | } else { | |||
16534 | return PrevTagDecl; | |||
16535 | } | |||
16536 | } | |||
16537 | ||||
16538 | // Diagnose attempts to redefine a tag. | |||
16539 | if (TUK == TUK_Definition) { | |||
16540 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { | |||
16541 | // If we're defining a specialization and the previous definition | |||
16542 | // is from an implicit instantiation, don't emit an error | |||
16543 | // here; we'll catch this in the general case below. | |||
16544 | bool IsExplicitSpecializationAfterInstantiation = false; | |||
16545 | if (isMemberSpecialization) { | |||
16546 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) | |||
16547 | IsExplicitSpecializationAfterInstantiation = | |||
16548 | RD->getTemplateSpecializationKind() != | |||
16549 | TSK_ExplicitSpecialization; | |||
16550 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) | |||
16551 | IsExplicitSpecializationAfterInstantiation = | |||
16552 | ED->getTemplateSpecializationKind() != | |||
16553 | TSK_ExplicitSpecialization; | |||
16554 | } | |||
16555 | ||||
16556 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do | |||
16557 | // not keep more that one definition around (merge them). However, | |||
16558 | // ensure the decl passes the structural compatibility check in | |||
16559 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). | |||
16560 | NamedDecl *Hidden = nullptr; | |||
16561 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { | |||
16562 | // There is a definition of this tag, but it is not visible. We | |||
16563 | // explicitly make use of C++'s one definition rule here, and | |||
16564 | // assume that this definition is identical to the hidden one | |||
16565 | // we already have. Make the existing definition visible and | |||
16566 | // use it in place of this one. | |||
16567 | if (!getLangOpts().CPlusPlus) { | |||
16568 | // Postpone making the old definition visible until after we | |||
16569 | // complete parsing the new one and do the structural | |||
16570 | // comparison. | |||
16571 | SkipBody->CheckSameAsPrevious = true; | |||
16572 | SkipBody->New = createTagFromNewDecl(); | |||
16573 | SkipBody->Previous = Def; | |||
16574 | return Def; | |||
16575 | } else { | |||
16576 | SkipBody->ShouldSkip = true; | |||
16577 | SkipBody->Previous = Def; | |||
16578 | makeMergedDefinitionVisible(Hidden); | |||
16579 | // Carry on and handle it like a normal definition. We'll | |||
16580 | // skip starting the definitiion later. | |||
16581 | } | |||
16582 | } else if (!IsExplicitSpecializationAfterInstantiation) { | |||
16583 | // A redeclaration in function prototype scope in C isn't | |||
16584 | // visible elsewhere, so merely issue a warning. | |||
16585 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) | |||
16586 | Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; | |||
16587 | else | |||
16588 | Diag(NameLoc, diag::err_redefinition) << Name; | |||
16589 | notePreviousDefinition(Def, | |||
16590 | NameLoc.isValid() ? NameLoc : KWLoc); | |||
16591 | // If this is a redefinition, recover by making this | |||
16592 | // struct be anonymous, which will make any later | |||
16593 | // references get the previous definition. | |||
16594 | Name = nullptr; | |||
16595 | Previous.clear(); | |||
16596 | Invalid = true; | |||
16597 | } | |||
16598 | } else { | |||
16599 | // If the type is currently being defined, complain | |||
16600 | // about a nested redefinition. | |||
16601 | auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); | |||
16602 | if (TD->isBeingDefined()) { | |||
16603 | Diag(NameLoc, diag::err_nested_redefinition) << Name; | |||
16604 | Diag(PrevTagDecl->getLocation(), | |||
16605 | diag::note_previous_definition); | |||
16606 | Name = nullptr; | |||
16607 | Previous.clear(); | |||
16608 | Invalid = true; | |||
16609 | } | |||
16610 | } | |||
16611 | ||||
16612 | // Okay, this is definition of a previously declared or referenced | |||
16613 | // tag. We're going to create a new Decl for it. | |||
16614 | } | |||
16615 | ||||
16616 | // Okay, we're going to make a redeclaration. If this is some kind | |||
16617 | // of reference, make sure we build the redeclaration in the same DC | |||
16618 | // as the original, and ignore the current access specifier. | |||
16619 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | |||
16620 | SearchDC = PrevTagDecl->getDeclContext(); | |||
16621 | AS = AS_none; | |||
16622 | } | |||
16623 | } | |||
16624 | // If we get here we have (another) forward declaration or we | |||
16625 | // have a definition. Just create a new decl. | |||
16626 | ||||
16627 | } else { | |||
16628 | // If we get here, this is a definition of a new tag type in a nested | |||
16629 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a | |||
16630 | // new decl/type. We set PrevDecl to NULL so that the entities | |||
16631 | // have distinct types. | |||
16632 | Previous.clear(); | |||
16633 | } | |||
16634 | // If we get here, we're going to create a new Decl. If PrevDecl | |||
16635 | // is non-NULL, it's a definition of the tag declared by | |||
16636 | // PrevDecl. If it's NULL, we have a new definition. | |||
16637 | ||||
16638 | // Otherwise, PrevDecl is not a tag, but was found with tag | |||
16639 | // lookup. This is only actually possible in C++, where a few | |||
16640 | // things like templates still live in the tag namespace. | |||
16641 | } else { | |||
16642 | // Use a better diagnostic if an elaborated-type-specifier | |||
16643 | // found the wrong kind of type on the first | |||
16644 | // (non-redeclaration) lookup. | |||
16645 | if ((TUK == TUK_Reference || TUK == TUK_Friend) && | |||
16646 | !Previous.isForRedeclaration()) { | |||
16647 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | |||
16648 | Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK | |||
16649 | << Kind; | |||
16650 | Diag(PrevDecl->getLocation(), diag::note_declared_at); | |||
16651 | Invalid = true; | |||
16652 | ||||
16653 | // Otherwise, only diagnose if the declaration is in scope. | |||
16654 | } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, | |||
16655 | SS.isNotEmpty() || isMemberSpecialization)) { | |||
16656 | // do nothing | |||
16657 | ||||
16658 | // Diagnose implicit declarations introduced by elaborated types. | |||
16659 | } else if (TUK == TUK_Reference || TUK == TUK_Friend) { | |||
16660 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | |||
16661 | Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; | |||
16662 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | |||
16663 | Invalid = true; | |||
16664 | ||||
16665 | // Otherwise it's a declaration. Call out a particularly common | |||
16666 | // case here. | |||
16667 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { | |||
16668 | unsigned Kind = 0; | |||
16669 | if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; | |||
16670 | Diag(NameLoc, diag::err_tag_definition_of_typedef) | |||
16671 | << Name << Kind << TND->getUnderlyingType(); | |||
16672 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | |||
16673 | Invalid = true; | |||
16674 | ||||
16675 | // Otherwise, diagnose. | |||
16676 | } else { | |||
16677 | // The tag name clashes with something else in the target scope, | |||
16678 | // issue an error and recover by making this tag be anonymous. | |||
16679 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; | |||
16680 | notePreviousDefinition(PrevDecl, NameLoc); | |||
16681 | Name = nullptr; | |||
16682 | Invalid = true; | |||
16683 | } | |||
16684 | ||||
16685 | // The existing declaration isn't relevant to us; we're in a | |||
16686 | // new scope, so clear out the previous declaration. | |||
16687 | Previous.clear(); | |||
16688 | } | |||
16689 | } | |||
16690 | ||||
16691 | CreateNewDecl: | |||
16692 | ||||
16693 | TagDecl *PrevDecl = nullptr; | |||
16694 | if (Previous.isSingleResult()) | |||
16695 | PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); | |||
16696 | ||||
16697 | // If there is an identifier, use the location of the identifier as the | |||
16698 | // location of the decl, otherwise use the location of the struct/union | |||
16699 | // keyword. | |||
16700 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | |||
16701 | ||||
16702 | // Otherwise, create a new declaration. If there is a previous | |||
16703 | // declaration of the same entity, the two will be linked via | |||
16704 | // PrevDecl. | |||
16705 | TagDecl *New; | |||
16706 | ||||
16707 | if (Kind == TTK_Enum) { | |||
16708 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | |||
16709 | // enum X { A, B, C } D; D should chain to X. | |||
16710 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, | |||
16711 | cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, | |||
16712 | ScopedEnumUsesClassTag, IsFixed); | |||
16713 | ||||
16714 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) | |||
16715 | StdAlignValT = cast<EnumDecl>(New); | |||
16716 | ||||
16717 | // If this is an undefined enum, warn. | |||
16718 | if (TUK != TUK_Definition && !Invalid) { | |||
16719 | TagDecl *Def; | |||
16720 | if (IsFixed && cast<EnumDecl>(New)->isFixed()) { | |||
16721 | // C++0x: 7.2p2: opaque-enum-declaration. | |||
16722 | // Conflicts are diagnosed above. Do nothing. | |||
16723 | } | |||
16724 | else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { | |||
16725 | Diag(Loc, diag::ext_forward_ref_enum_def) | |||
16726 | << New; | |||
16727 | Diag(Def->getLocation(), diag::note_previous_definition); | |||
16728 | } else { | |||
16729 | unsigned DiagID = diag::ext_forward_ref_enum; | |||
16730 | if (getLangOpts().MSVCCompat) | |||
16731 | DiagID = diag::ext_ms_forward_ref_enum; | |||
16732 | else if (getLangOpts().CPlusPlus) | |||
16733 | DiagID = diag::err_forward_ref_enum; | |||
16734 | Diag(Loc, DiagID); | |||
16735 | } | |||
16736 | } | |||
16737 | ||||
16738 | if (EnumUnderlying) { | |||
16739 | EnumDecl *ED = cast<EnumDecl>(New); | |||
16740 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | |||
16741 | ED->setIntegerTypeSourceInfo(TI); | |||
16742 | else | |||
16743 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); | |||
16744 | ED->setPromotionType(ED->getIntegerType()); | |||
16745 | assert(ED->isComplete() && "enum with type should be complete")(static_cast <bool> (ED->isComplete() && "enum with type should be complete" ) ? void (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\"" , "clang/lib/Sema/SemaDecl.cpp", 16745, __extension__ __PRETTY_FUNCTION__ )); | |||
16746 | } | |||
16747 | } else { | |||
16748 | // struct/union/class | |||
16749 | ||||
16750 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | |||
16751 | // struct X { int A; } D; D should chain to X. | |||
16752 | if (getLangOpts().CPlusPlus) { | |||
16753 | // FIXME: Look for a way to use RecordDecl for simple structs. | |||
16754 | New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
16755 | cast_or_null<CXXRecordDecl>(PrevDecl)); | |||
16756 | ||||
16757 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) | |||
16758 | StdBadAlloc = cast<CXXRecordDecl>(New); | |||
16759 | } else | |||
16760 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | |||
16761 | cast_or_null<RecordDecl>(PrevDecl)); | |||
16762 | } | |||
16763 | ||||
16764 | // C++11 [dcl.type]p3: | |||
16765 | // A type-specifier-seq shall not define a class or enumeration [...]. | |||
16766 | if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && | |||
16767 | TUK == TUK_Definition) { | |||
16768 | Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) | |||
16769 | << Context.getTagDeclType(New); | |||
16770 | Invalid = true; | |||
16771 | } | |||
16772 | ||||
16773 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && | |||
16774 | DC->getDeclKind() == Decl::Enum) { | |||
16775 | Diag(New->getLocation(), diag::err_type_defined_in_enum) | |||
16776 | << Context.getTagDeclType(New); | |||
16777 | Invalid = true; | |||
16778 | } | |||
16779 | ||||
16780 | // Maybe add qualifier info. | |||
16781 | if (SS.isNotEmpty()) { | |||
16782 | if (SS.isSet()) { | |||
16783 | // If this is either a declaration or a definition, check the | |||
16784 | // nested-name-specifier against the current context. | |||
16785 | if ((TUK == TUK_Definition || TUK == TUK_Declaration) && | |||
16786 | diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, | |||
16787 | isMemberSpecialization)) | |||
16788 | Invalid = true; | |||
16789 | ||||
16790 | New->setQualifierInfo(SS.getWithLocInContext(Context)); | |||
16791 | if (TemplateParameterLists.size() > 0) { | |||
16792 | New->setTemplateParameterListsInfo(Context, TemplateParameterLists); | |||
16793 | } | |||
16794 | } | |||
16795 | else | |||
16796 | Invalid = true; | |||
16797 | } | |||
16798 | ||||
16799 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | |||
16800 | // Add alignment attributes if necessary; these attributes are checked when | |||
16801 | // the ASTContext lays out the structure. | |||
16802 | // | |||
16803 | // It is important for implementing the correct semantics that this | |||
16804 | // happen here (in ActOnTag). The #pragma pack stack is | |||
16805 | // maintained as a result of parser callbacks which can occur at | |||
16806 | // many points during the parsing of a struct declaration (because | |||
16807 | // the #pragma tokens are effectively skipped over during the | |||
16808 | // parsing of the struct). | |||
16809 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | |||
16810 | AddAlignmentAttributesForRecord(RD); | |||
16811 | AddMsStructLayoutForRecord(RD); | |||
16812 | } | |||
16813 | } | |||
16814 | ||||
16815 | if (ModulePrivateLoc.isValid()) { | |||
16816 | if (isMemberSpecialization) | |||
16817 | Diag(New->getLocation(), diag::err_module_private_specialization) | |||
16818 | << 2 | |||
16819 | << FixItHint::CreateRemoval(ModulePrivateLoc); | |||
16820 | // __module_private__ does not apply to local classes. However, we only | |||
16821 | // diagnose this as an error when the declaration specifiers are | |||
16822 | // freestanding. Here, we just ignore the __module_private__. | |||
16823 | else if (!SearchDC->isFunctionOrMethod()) | |||
16824 | New->setModulePrivate(); | |||
16825 | } | |||
16826 | ||||
16827 | // If this is a specialization of a member class (of a class template), | |||
16828 | // check the specialization. | |||
16829 | if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) | |||
16830 | Invalid = true; | |||
16831 | ||||
16832 | // If we're declaring or defining a tag in function prototype scope in C, | |||
16833 | // note that this type can only be used within the function and add it to | |||
16834 | // the list of decls to inject into the function definition scope. | |||
16835 | if ((Name || Kind == TTK_Enum) && | |||
16836 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { | |||
16837 | if (getLangOpts().CPlusPlus) { | |||
16838 | // C++ [dcl.fct]p6: | |||
16839 | // Types shall not be defined in return or parameter types. | |||
16840 | if (TUK == TUK_Definition && !IsTypeSpecifier) { | |||
16841 | Diag(Loc, diag::err_type_defined_in_param_type) | |||
16842 | << Name; | |||
16843 | Invalid = true; | |||
16844 | } | |||
16845 | } else if (!PrevDecl) { | |||
16846 | Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); | |||
16847 | } | |||
16848 | } | |||
16849 | ||||
16850 | if (Invalid) | |||
16851 | New->setInvalidDecl(); | |||
16852 | ||||
16853 | // Set the lexical context. If the tag has a C++ scope specifier, the | |||
16854 | // lexical context will be different from the semantic context. | |||
16855 | New->setLexicalDeclContext(CurContext); | |||
16856 | ||||
16857 | // Mark this as a friend decl if applicable. | |||
16858 | // In Microsoft mode, a friend declaration also acts as a forward | |||
16859 | // declaration so we always pass true to setObjectOfFriendDecl to make | |||
16860 | // the tag name visible. | |||
16861 | if (TUK == TUK_Friend) | |||
16862 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); | |||
16863 | ||||
16864 | // Set the access specifier. | |||
16865 | if (!Invalid && SearchDC->isRecord()) | |||
16866 | SetMemberAccessSpecifier(New, PrevDecl, AS); | |||
16867 | ||||
16868 | if (PrevDecl) | |||
16869 | CheckRedeclarationInModule(New, PrevDecl); | |||
16870 | ||||
16871 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) | |||
16872 | New->startDefinition(); | |||
16873 | ||||
16874 | ProcessDeclAttributeList(S, New, Attrs); | |||
16875 | AddPragmaAttributes(S, New); | |||
16876 | ||||
16877 | // If this has an identifier, add it to the scope stack. | |||
16878 | if (TUK == TUK_Friend) { | |||
16879 | // We might be replacing an existing declaration in the lookup tables; | |||
16880 | // if so, borrow its access specifier. | |||
16881 | if (PrevDecl) | |||
16882 | New->setAccess(PrevDecl->getAccess()); | |||
16883 | ||||
16884 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); | |||
16885 | DC->makeDeclVisibleInContext(New); | |||
16886 | if (Name) // can be null along some error paths | |||
16887 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | |||
16888 | PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); | |||
16889 | } else if (Name) { | |||
16890 | S = getNonFieldDeclScope(S); | |||
16891 | PushOnScopeChains(New, S, true); | |||
16892 | } else { | |||
16893 | CurContext->addDecl(New); | |||
16894 | } | |||
16895 | ||||
16896 | // If this is the C FILE type, notify the AST context. | |||
16897 | if (IdentifierInfo *II = New->getIdentifier()) | |||
16898 | if (!New->isInvalidDecl() && | |||
16899 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && | |||
16900 | II->isStr("FILE")) | |||
16901 | Context.setFILEDecl(New); | |||
16902 | ||||
16903 | if (PrevDecl) | |||
16904 | mergeDeclAttributes(New, PrevDecl); | |||
16905 | ||||
16906 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) | |||
16907 | inferGslOwnerPointerAttribute(CXXRD); | |||
16908 | ||||
16909 | // If there's a #pragma GCC visibility in scope, set the visibility of this | |||
16910 | // record. | |||
16911 | AddPushedVisibilityAttribute(New); | |||
16912 | ||||
16913 | if (isMemberSpecialization && !New->isInvalidDecl()) | |||
16914 | CompleteMemberSpecialization(New, Previous); | |||
16915 | ||||
16916 | OwnedDecl = true; | |||
16917 | // In C++, don't return an invalid declaration. We can't recover well from | |||
16918 | // the cases where we make the type anonymous. | |||
16919 | if (Invalid && getLangOpts().CPlusPlus) { | |||
16920 | if (New->isBeingDefined()) | |||
16921 | if (auto RD = dyn_cast<RecordDecl>(New)) | |||
16922 | RD->completeDefinition(); | |||
16923 | return nullptr; | |||
16924 | } else if (SkipBody && SkipBody->ShouldSkip) { | |||
16925 | return SkipBody->Previous; | |||
16926 | } else { | |||
16927 | return New; | |||
16928 | } | |||
16929 | } | |||
16930 | ||||
16931 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { | |||
16932 | AdjustDeclIfTemplate(TagD); | |||
16933 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
16934 | ||||
16935 | // Enter the tag context. | |||
16936 | PushDeclContext(S, Tag); | |||
16937 | ||||
16938 | ActOnDocumentableDecl(TagD); | |||
16939 | ||||
16940 | // If there's a #pragma GCC visibility in scope, set the visibility of this | |||
16941 | // record. | |||
16942 | AddPushedVisibilityAttribute(Tag); | |||
16943 | } | |||
16944 | ||||
16945 | bool Sema::ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody) { | |||
16946 | if (!hasStructuralCompatLayout(Prev, SkipBody.New)) | |||
16947 | return false; | |||
16948 | ||||
16949 | // Make the previous decl visible. | |||
16950 | makeMergedDefinitionVisible(SkipBody.Previous); | |||
16951 | return true; | |||
16952 | } | |||
16953 | ||||
16954 | Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { | |||
16955 | assert(isa<ObjCContainerDecl>(IDecl) &&(static_cast <bool> (isa<ObjCContainerDecl>(IDecl ) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "clang/lib/Sema/SemaDecl.cpp", 16956, __extension__ __PRETTY_FUNCTION__ )) | |||
16956 | "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")(static_cast <bool> (isa<ObjCContainerDecl>(IDecl ) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "clang/lib/Sema/SemaDecl.cpp", 16956, __extension__ __PRETTY_FUNCTION__ )); | |||
16957 | DeclContext *OCD = cast<DeclContext>(IDecl); | |||
16958 | assert(OCD->getLexicalParent() == CurContext &&(static_cast <bool> (OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 16959, __extension__ __PRETTY_FUNCTION__ )) | |||
16959 | "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? void (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "clang/lib/Sema/SemaDecl.cpp", 16959, __extension__ __PRETTY_FUNCTION__ )); | |||
16960 | CurContext = OCD; | |||
16961 | return IDecl; | |||
16962 | } | |||
16963 | ||||
16964 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, | |||
16965 | SourceLocation FinalLoc, | |||
16966 | bool IsFinalSpelledSealed, | |||
16967 | bool IsAbstract, | |||
16968 | SourceLocation LBraceLoc) { | |||
16969 | AdjustDeclIfTemplate(TagD); | |||
16970 | CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); | |||
16971 | ||||
16972 | FieldCollector->StartClass(); | |||
16973 | ||||
16974 | if (!Record->getIdentifier()) | |||
16975 | return; | |||
16976 | ||||
16977 | if (IsAbstract) | |||
16978 | Record->markAbstract(); | |||
16979 | ||||
16980 | if (FinalLoc.isValid()) { | |||
16981 | Record->addAttr(FinalAttr::Create( | |||
16982 | Context, FinalLoc, AttributeCommonInfo::AS_Keyword, | |||
16983 | static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); | |||
16984 | } | |||
16985 | // C++ [class]p2: | |||
16986 | // [...] The class-name is also inserted into the scope of the | |||
16987 | // class itself; this is known as the injected-class-name. For | |||
16988 | // purposes of access checking, the injected-class-name is treated | |||
16989 | // as if it were a public member name. | |||
16990 | CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( | |||
16991 | Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), | |||
16992 | Record->getLocation(), Record->getIdentifier(), | |||
16993 | /*PrevDecl=*/nullptr, | |||
16994 | /*DelayTypeCreation=*/true); | |||
16995 | Context.getTypeDeclType(InjectedClassName, Record); | |||
16996 | InjectedClassName->setImplicit(); | |||
16997 | InjectedClassName->setAccess(AS_public); | |||
16998 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) | |||
16999 | InjectedClassName->setDescribedClassTemplate(Template); | |||
17000 | PushOnScopeChains(InjectedClassName, S); | |||
17001 | assert(InjectedClassName->isInjectedClassName() &&(static_cast <bool> (InjectedClassName->isInjectedClassName () && "Broken injected-class-name") ? void (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "clang/lib/Sema/SemaDecl.cpp", 17002, __extension__ __PRETTY_FUNCTION__ )) | |||
17002 | "Broken injected-class-name")(static_cast <bool> (InjectedClassName->isInjectedClassName () && "Broken injected-class-name") ? void (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "clang/lib/Sema/SemaDecl.cpp", 17002, __extension__ __PRETTY_FUNCTION__ )); | |||
17003 | } | |||
17004 | ||||
17005 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, | |||
17006 | SourceRange BraceRange) { | |||
17007 | AdjustDeclIfTemplate(TagD); | |||
17008 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
17009 | Tag->setBraceRange(BraceRange); | |||
17010 | ||||
17011 | // Make sure we "complete" the definition even it is invalid. | |||
17012 | if (Tag->isBeingDefined()) { | |||
17013 | assert(Tag->isInvalidDecl() && "We should already have completed it")(static_cast <bool> (Tag->isInvalidDecl() && "We should already have completed it") ? void (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\"" , "clang/lib/Sema/SemaDecl.cpp", 17013, __extension__ __PRETTY_FUNCTION__ )); | |||
17014 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | |||
17015 | RD->completeDefinition(); | |||
17016 | } | |||
17017 | ||||
17018 | if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) { | |||
17019 | FieldCollector->FinishClass(); | |||
17020 | if (RD->hasAttr<SYCLSpecialClassAttr>()) { | |||
17021 | auto *Def = RD->getDefinition(); | |||
17022 | assert(Def && "The record is expected to have a completed definition")(static_cast <bool> (Def && "The record is expected to have a completed definition" ) ? void (0) : __assert_fail ("Def && \"The record is expected to have a completed definition\"" , "clang/lib/Sema/SemaDecl.cpp", 17022, __extension__ __PRETTY_FUNCTION__ )); | |||
17023 | unsigned NumInitMethods = 0; | |||
17024 | for (auto *Method : Def->methods()) { | |||
17025 | if (!Method->getIdentifier()) | |||
17026 | continue; | |||
17027 | if (Method->getName() == "__init") | |||
17028 | NumInitMethods++; | |||
17029 | } | |||
17030 | if (NumInitMethods > 1 || !Def->hasInitMethod()) | |||
17031 | Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method); | |||
17032 | } | |||
17033 | } | |||
17034 | ||||
17035 | // Exit this scope of this tag's definition. | |||
17036 | PopDeclContext(); | |||
17037 | ||||
17038 | if (getCurLexicalContext()->isObjCContainer() && | |||
17039 | Tag->getDeclContext()->isFileContext()) | |||
17040 | Tag->setTopLevelDeclInObjCContainer(); | |||
17041 | ||||
17042 | // Notify the consumer that we've defined a tag. | |||
17043 | if (!Tag->isInvalidDecl()) | |||
17044 | Consumer.HandleTagDeclDefinition(Tag); | |||
17045 | ||||
17046 | // Clangs implementation of #pragma align(packed) differs in bitfield layout | |||
17047 | // from XLs and instead matches the XL #pragma pack(1) behavior. | |||
17048 | if (Context.getTargetInfo().getTriple().isOSAIX() && | |||
17049 | AlignPackStack.hasValue()) { | |||
17050 | AlignPackInfo APInfo = AlignPackStack.CurrentValue; | |||
17051 | // Only diagnose #pragma align(packed). | |||
17052 | if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed) | |||
17053 | return; | |||
17054 | const RecordDecl *RD = dyn_cast<RecordDecl>(Tag); | |||
17055 | if (!RD) | |||
17056 | return; | |||
17057 | // Only warn if there is at least 1 bitfield member. | |||
17058 | if (llvm::any_of(RD->fields(), | |||
17059 | [](const FieldDecl *FD) { return FD->isBitField(); })) | |||
17060 | Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible); | |||
17061 | } | |||
17062 | } | |||
17063 | ||||
17064 | void Sema::ActOnObjCContainerFinishDefinition() { | |||
17065 | // Exit this scope of this interface definition. | |||
17066 | PopDeclContext(); | |||
17067 | } | |||
17068 | ||||
17069 | void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { | |||
17070 | assert(DC == CurContext && "Mismatch of container contexts")(static_cast <bool> (DC == CurContext && "Mismatch of container contexts" ) ? void (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\"" , "clang/lib/Sema/SemaDecl.cpp", 17070, __extension__ __PRETTY_FUNCTION__ )); | |||
17071 | OriginalLexicalContext = DC; | |||
17072 | ActOnObjCContainerFinishDefinition(); | |||
17073 | } | |||
17074 | ||||
17075 | void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { | |||
17076 | ActOnObjCContainerStartDefinition(cast<Decl>(DC)); | |||
17077 | OriginalLexicalContext = nullptr; | |||
17078 | } | |||
17079 | ||||
17080 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { | |||
17081 | AdjustDeclIfTemplate(TagD); | |||
17082 | TagDecl *Tag = cast<TagDecl>(TagD); | |||
17083 | Tag->setInvalidDecl(); | |||
17084 | ||||
17085 | // Make sure we "complete" the definition even it is invalid. | |||
17086 | if (Tag->isBeingDefined()) { | |||
17087 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | |||
17088 | RD->completeDefinition(); | |||
17089 | } | |||
17090 | ||||
17091 | // We're undoing ActOnTagStartDefinition here, not | |||
17092 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with | |||
17093 | // the FieldCollector. | |||
17094 | ||||
17095 | PopDeclContext(); | |||
17096 | } | |||
17097 | ||||
17098 | // Note that FieldName may be null for anonymous bitfields. | |||
17099 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, | |||
17100 | IdentifierInfo *FieldName, | |||
17101 | QualType FieldTy, bool IsMsStruct, | |||
17102 | Expr *BitWidth, bool *ZeroWidth) { | |||
17103 | assert(BitWidth)(static_cast <bool> (BitWidth) ? void (0) : __assert_fail ("BitWidth", "clang/lib/Sema/SemaDecl.cpp", 17103, __extension__ __PRETTY_FUNCTION__)); | |||
17104 | if (BitWidth->containsErrors()) | |||
17105 | return ExprError(); | |||
17106 | ||||
17107 | // Default to true; that shouldn't confuse checks for emptiness | |||
17108 | if (ZeroWidth) | |||
17109 | *ZeroWidth = true; | |||
17110 | ||||
17111 | // C99 6.7.2.1p4 - verify the field type. | |||
17112 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | |||
17113 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { | |||
17114 | // Handle incomplete and sizeless types with a specific error. | |||
17115 | if (RequireCompleteSizedType(FieldLoc, FieldTy, | |||
17116 | diag::err_field_incomplete_or_sizeless)) | |||
17117 | return ExprError(); | |||
17118 | if (FieldName) | |||
17119 | return Diag(FieldLoc, diag::err_not_integral_type_bitfield) | |||
17120 | << FieldName << FieldTy << BitWidth->getSourceRange(); | |||
17121 | return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) | |||
17122 | << FieldTy << BitWidth->getSourceRange(); | |||
17123 | } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), | |||
17124 | UPPC_BitFieldWidth)) | |||
17125 | return ExprError(); | |||
17126 | ||||
17127 | // If the bit-width is type- or value-dependent, don't try to check | |||
17128 | // it now. | |||
17129 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) | |||
17130 | return BitWidth; | |||
17131 | ||||
17132 | llvm::APSInt Value; | |||
17133 | ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold); | |||
17134 | if (ICE.isInvalid()) | |||
17135 | return ICE; | |||
17136 | BitWidth = ICE.get(); | |||
17137 | ||||
17138 | if (Value != 0 && ZeroWidth) | |||
17139 | *ZeroWidth = false; | |||
17140 | ||||
17141 | // Zero-width bitfield is ok for anonymous field. | |||
17142 | if (Value == 0 && FieldName) | |||
17143 | return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; | |||
17144 | ||||
17145 | if (Value.isSigned() && Value.isNegative()) { | |||
17146 | if (FieldName) | |||
17147 | return Diag(FieldLoc, diag::err_bitfield_has_negative_width) | |||
17148 | << FieldName << toString(Value, 10); | |||
17149 | return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) | |||
17150 | << toString(Value, 10); | |||
17151 | } | |||
17152 | ||||
17153 | // The size of the bit-field must not exceed our maximum permitted object | |||
17154 | // size. | |||
17155 | if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) { | |||
17156 | return Diag(FieldLoc, diag::err_bitfield_too_wide) | |||
17157 | << !FieldName << FieldName << toString(Value, 10); | |||
17158 | } | |||
17159 | ||||
17160 | if (!FieldTy->isDependentType()) { | |||
17161 | uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); | |||
17162 | uint64_t TypeWidth = Context.getIntWidth(FieldTy); | |||
17163 | bool BitfieldIsOverwide = Value.ugt(TypeWidth); | |||
17164 | ||||
17165 | // Over-wide bitfields are an error in C or when using the MSVC bitfield | |||
17166 | // ABI. | |||
17167 | bool CStdConstraintViolation = | |||
17168 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; | |||
17169 | bool MSBitfieldViolation = | |||
17170 | Value.ugt(TypeStorageSize) && | |||
17171 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); | |||
17172 | if (CStdConstraintViolation || MSBitfieldViolation) { | |||
17173 | unsigned DiagWidth = | |||
17174 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; | |||
17175 | return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) | |||
17176 | << (bool)FieldName << FieldName << toString(Value, 10) | |||
17177 | << !CStdConstraintViolation << DiagWidth; | |||
17178 | } | |||
17179 | ||||
17180 | // Warn on types where the user might conceivably expect to get all | |||
17181 | // specified bits as value bits: that's all integral types other than | |||
17182 | // 'bool'. | |||
17183 | if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) { | |||
17184 | Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) | |||
17185 | << FieldName << toString(Value, 10) | |||
17186 | << (unsigned)TypeWidth; | |||
17187 | } | |||
17188 | } | |||
17189 | ||||
17190 | return BitWidth; | |||
17191 | } | |||
17192 | ||||
17193 | /// ActOnField - Each field of a C struct/union is passed into this in order | |||
17194 | /// to create a FieldDecl object for it. | |||
17195 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, | |||
17196 | Declarator &D, Expr *BitfieldWidth) { | |||
17197 | FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), | |||
| ||||
17198 | DeclStart, D, static_cast<Expr*>(BitfieldWidth), | |||
17199 | /*InitStyle=*/ICIS_NoInit, AS_public); | |||
17200 | return Res; | |||
17201 | } | |||
17202 | ||||
17203 | /// HandleField - Analyze a field of a C struct or a C++ data member. | |||
17204 | /// | |||
17205 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, | |||
17206 | SourceLocation DeclStart, | |||
17207 | Declarator &D, Expr *BitWidth, | |||
17208 | InClassInitStyle InitStyle, | |||
17209 | AccessSpecifier AS) { | |||
17210 | if (D.isDecompositionDeclarator()) { | |||
17211 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | |||
17212 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | |||
17213 | << Decomp.getSourceRange(); | |||
17214 | return nullptr; | |||
17215 | } | |||
17216 | ||||
17217 | IdentifierInfo *II = D.getIdentifier(); | |||
17218 | SourceLocation Loc = DeclStart; | |||
17219 | if (II
| |||
17220 | ||||
17221 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
17222 | QualType T = TInfo->getType(); | |||
17223 | if (getLangOpts().CPlusPlus) { | |||
17224 | CheckExtraCXXDefaultArguments(D); | |||
17225 | ||||
17226 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | |||
17227 | UPPC_DataMemberType)) { | |||
17228 | D.setInvalidType(); | |||
17229 | T = Context.IntTy; | |||
17230 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | |||
17231 | } | |||
17232 | } | |||
17233 | ||||
17234 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | |||
17235 | ||||
17236 | if (D.getDeclSpec().isInlineSpecified()) | |||
17237 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | |||
17238 | << getLangOpts().CPlusPlus17; | |||
17239 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | |||
17240 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | |||
17241 | diag::err_invalid_thread) | |||
17242 | << DeclSpec::getSpecifierName(TSCS); | |||
17243 | ||||
17244 | // Check to see if this name was declared as a member previously | |||
17245 | NamedDecl *PrevDecl = nullptr; | |||
17246 | LookupResult Previous(*this, II, Loc, LookupMemberName, | |||
17247 | ForVisibleRedeclaration); | |||
17248 | LookupName(Previous, S); | |||
17249 | switch (Previous.getResultKind()) { | |||
17250 | case LookupResult::Found: | |||
17251 | case LookupResult::FoundUnresolvedValue: | |||
17252 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | |||
17253 | break; | |||
17254 | ||||
17255 | case LookupResult::FoundOverloaded: | |||
17256 | PrevDecl = Previous.getRepresentativeDecl(); | |||
17257 | break; | |||
17258 | ||||
17259 | case LookupResult::NotFound: | |||
17260 | case LookupResult::NotFoundInCurrentInstantiation: | |||
17261 | case LookupResult::Ambiguous: | |||
17262 | break; | |||
17263 | } | |||
17264 | Previous.suppressDiagnostics(); | |||
17265 | ||||
17266 | if (PrevDecl
| |||
17267 | // Maybe we will complain about the shadowed template parameter. | |||
17268 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | |||
17269 | // Just pretend that we didn't see the previous declaration. | |||
17270 | PrevDecl = nullptr; | |||
17271 | } | |||
17272 | ||||
17273 | if (PrevDecl
| |||
17274 | PrevDecl = nullptr; | |||
17275 | ||||
17276 | bool Mutable | |||
17277 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); | |||
17278 | SourceLocation TSSL = D.getBeginLoc(); | |||
17279 | FieldDecl *NewFD | |||
17280 | = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, | |||
17281 | TSSL, AS, PrevDecl, &D); | |||
17282 | ||||
17283 | if (NewFD->isInvalidDecl()) | |||
17284 | Record->setInvalidDecl(); | |||
17285 | ||||
17286 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
17287 | NewFD->setModulePrivate(); | |||
17288 | ||||
17289 | if (NewFD->isInvalidDecl() && PrevDecl) { | |||
17290 | // Don't introduce NewFD into scope; there's already something | |||
17291 | // with the same name in the same scope. | |||
17292 | } else if (II) { | |||
17293 | PushOnScopeChains(NewFD, S); | |||
17294 | } else | |||
17295 | Record->addDecl(NewFD); | |||
17296 | ||||
17297 | return NewFD; | |||
17298 | } | |||
17299 | ||||
17300 | /// Build a new FieldDecl and check its well-formedness. | |||
17301 | /// | |||
17302 | /// This routine builds a new FieldDecl given the fields name, type, | |||
17303 | /// record, etc. \p PrevDecl should refer to any previous declaration | |||
17304 | /// with the same name and in the same scope as the field to be | |||
17305 | /// created. | |||
17306 | /// | |||
17307 | /// \returns a new FieldDecl. | |||
17308 | /// | |||
17309 | /// \todo The Declarator argument is a hack. It will be removed once | |||
17310 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, | |||
17311 | TypeSourceInfo *TInfo, | |||
17312 | RecordDecl *Record, SourceLocation Loc, | |||
17313 | bool Mutable, Expr *BitWidth, | |||
17314 | InClassInitStyle InitStyle, | |||
17315 | SourceLocation TSSL, | |||
17316 | AccessSpecifier AS, NamedDecl *PrevDecl, | |||
17317 | Declarator *D) { | |||
17318 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | |||
17319 | bool InvalidDecl = false; | |||
17320 | if (D
| |||
17321 | ||||
17322 | // If we receive a broken type, recover by assuming 'int' and | |||
17323 | // marking this declaration as invalid. | |||
17324 | if (T.isNull() || T->containsErrors()) { | |||
17325 | InvalidDecl = true; | |||
17326 | T = Context.IntTy; | |||
17327 | } | |||
17328 | ||||
17329 | QualType EltTy = Context.getBaseElementType(T); | |||
17330 | if (!EltTy->isDependentType() && !EltTy->containsErrors()) { | |||
17331 | if (RequireCompleteSizedType(Loc, EltTy, | |||
17332 | diag::err_field_incomplete_or_sizeless)) { | |||
17333 | // Fields of incomplete type force their record to be invalid. | |||
17334 | Record->setInvalidDecl(); | |||
17335 | InvalidDecl = true; | |||
17336 | } else { | |||
17337 | NamedDecl *Def; | |||
17338 | EltTy->isIncompleteType(&Def); | |||
17339 | if (Def && Def->isInvalidDecl()) { | |||
17340 | Record->setInvalidDecl(); | |||
17341 | InvalidDecl = true; | |||
17342 | } | |||
17343 | } | |||
17344 | } | |||
17345 | ||||
17346 | // TR 18037 does not allow fields to be declared with address space | |||
17347 | if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || | |||
17348 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { | |||
17349 | Diag(Loc, diag::err_field_with_address_space); | |||
17350 | Record->setInvalidDecl(); | |||
17351 | InvalidDecl = true; | |||
17352 | } | |||
17353 | ||||
17354 | if (LangOpts.OpenCL) { | |||
17355 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be | |||
17356 | // used as structure or union field: image, sampler, event or block types. | |||
17357 | if (T->isEventT() || T->isImageType() || T->isSamplerT() || | |||
17358 | T->isBlockPointerType()) { | |||
17359 | Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; | |||
17360 | Record->setInvalidDecl(); | |||
| ||||
17361 | InvalidDecl = true; | |||
17362 | } | |||
17363 | // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension | |||
17364 | // is enabled. | |||
17365 | if (BitWidth && !getOpenCLOptions().isAvailableOption( | |||
17366 | "__cl_clang_bitfields", LangOpts)) { | |||
17367 | Diag(Loc, diag::err_opencl_bitfields); | |||
17368 | InvalidDecl = true; | |||
17369 | } | |||
17370 | } | |||
17371 | ||||
17372 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). | |||
17373 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && | |||
17374 | T.hasQualifiers()) { | |||
17375 | InvalidDecl = true; | |||
17376 | Diag(Loc, diag::err_anon_bitfield_qualifiers); | |||
17377 | } | |||
17378 | ||||
17379 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | |||
17380 | // than a variably modified type. | |||
17381 | if (!InvalidDecl && T->isVariablyModifiedType()) { | |||
17382 | if (!tryToFixVariablyModifiedVarType( | |||
17383 | TInfo, T, Loc, diag::err_typecheck_field_variable_size)) | |||
17384 | InvalidDecl = true; | |||
17385 | } | |||
17386 | ||||
17387 | // Fields can not have abstract class types | |||
17388 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, | |||
17389 | diag::err_abstract_type_in_decl, | |||
17390 | AbstractFieldType)) | |||
17391 | InvalidDecl = true; | |||
17392 | ||||
17393 | bool ZeroWidth = false; | |||
17394 | if (InvalidDecl) | |||
17395 | BitWidth = nullptr; | |||
17396 | // If this is declared as a bit-field, check the bit-field. | |||
17397 | if (BitWidth) { | |||
17398 | BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, | |||
17399 | &ZeroWidth).get(); | |||
17400 | if (!BitWidth) { | |||
17401 | InvalidDecl = true; | |||
17402 | BitWidth = nullptr; | |||
17403 | ZeroWidth = false; | |||
17404 | } | |||
17405 | } | |||
17406 | ||||
17407 | // Check that 'mutable' is consistent with the type of the declaration. | |||
17408 | if (!InvalidDecl && Mutable) { | |||
17409 | unsigned DiagID = 0; | |||
17410 | if (T->isReferenceType()) | |||
17411 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference | |||
17412 | : diag::err_mutable_reference; | |||
17413 | else if (T.isConstQualified()) | |||
17414 | DiagID = diag::err_mutable_const; | |||
17415 | ||||
17416 | if (DiagID) { | |||
17417 | SourceLocation ErrLoc = Loc; | |||
17418 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) | |||
17419 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); | |||
17420 | Diag(ErrLoc, DiagID); | |||
17421 | if (DiagID != diag::ext_mutable_reference) { | |||
17422 | Mutable = false; | |||
17423 | InvalidDecl = true; | |||
17424 | } | |||
17425 | } | |||
17426 | } | |||
17427 | ||||
17428 | // C++11 [class.union]p8 (DR1460): | |||
17429 | // At most one variant member of a union may have a | |||
17430 | // brace-or-equal-initializer. | |||
17431 | if (InitStyle != ICIS_NoInit) | |||
17432 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); | |||
17433 | ||||
17434 | FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, | |||
17435 | BitWidth, Mutable, InitStyle); | |||
17436 | if (InvalidDecl) | |||
17437 | NewFD->setInvalidDecl(); | |||
17438 | ||||
17439 | if (PrevDecl && !isa<TagDecl>(PrevDecl)) { | |||
17440 | Diag(Loc, diag::err_duplicate_member) << II; | |||
17441 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
17442 | NewFD->setInvalidDecl(); | |||
17443 | } | |||
17444 | ||||
17445 | if (!InvalidDecl && getLangOpts().CPlusPlus) { | |||
17446 | if (Record->isUnion()) { | |||
17447 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | |||
17448 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
17449 | if (RDecl->getDefinition()) { | |||
17450 | // C++ [class.union]p1: An object of a class with a non-trivial | |||
17451 | // constructor, a non-trivial copy constructor, a non-trivial | |||
17452 | // destructor, or a non-trivial copy assignment operator | |||
17453 | // cannot be a member of a union, nor can an array of such | |||
17454 | // objects. | |||
17455 | if (CheckNontrivialField(NewFD)) | |||
17456 | NewFD->setInvalidDecl(); | |||
17457 | } | |||
17458 | } | |||
17459 | ||||
17460 | // C++ [class.union]p1: If a union contains a member of reference type, | |||
17461 | // the program is ill-formed, except when compiling with MSVC extensions | |||
17462 | // enabled. | |||
17463 | if (EltTy->isReferenceType()) { | |||
17464 | Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? | |||
17465 | diag::ext_union_member_of_reference_type : | |||
17466 | diag::err_union_member_of_reference_type) | |||
17467 | << NewFD->getDeclName() << EltTy; | |||
17468 | if (!getLangOpts().MicrosoftExt) | |||
17469 | NewFD->setInvalidDecl(); | |||
17470 | } | |||
17471 | } | |||
17472 | } | |||
17473 | ||||
17474 | // FIXME: We need to pass in the attributes given an AST | |||
17475 | // representation, not a parser representation. | |||
17476 | if (D) { | |||
17477 | // FIXME: The current scope is almost... but not entirely... correct here. | |||
17478 | ProcessDeclAttributes(getCurScope(), NewFD, *D); | |||
17479 | ||||
17480 | if (NewFD->hasAttrs()) | |||
17481 | CheckAlignasUnderalignment(NewFD); | |||
17482 | } | |||
17483 | ||||
17484 | // In auto-retain/release, infer strong retension for fields of | |||
17485 | // retainable type. | |||
17486 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) | |||
17487 | NewFD->setInvalidDecl(); | |||
17488 | ||||
17489 | if (T.isObjCGCWeak()) | |||
17490 | Diag(Loc, diag::warn_attribute_weak_on_field); | |||
17491 | ||||
17492 | // PPC MMA non-pointer types are not allowed as field types. | |||
17493 | if (Context.getTargetInfo().getTriple().isPPC64() && | |||
17494 | CheckPPCMMAType(T, NewFD->getLocation())) | |||
17495 | NewFD->setInvalidDecl(); | |||
17496 | ||||
17497 | NewFD->setAccess(AS); | |||
17498 | return NewFD; | |||
17499 | } | |||
17500 | ||||
17501 | bool Sema::CheckNontrivialField(FieldDecl *FD) { | |||
17502 | assert(FD)(static_cast <bool> (FD) ? void (0) : __assert_fail ("FD" , "clang/lib/Sema/SemaDecl.cpp", 17502, __extension__ __PRETTY_FUNCTION__ )); | |||
17503 | assert(getLangOpts().CPlusPlus && "valid check only for C++")(static_cast <bool> (getLangOpts().CPlusPlus && "valid check only for C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\"" , "clang/lib/Sema/SemaDecl.cpp", 17503, __extension__ __PRETTY_FUNCTION__ )); | |||
17504 | ||||
17505 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) | |||
17506 | return false; | |||
17507 | ||||
17508 | QualType EltTy = Context.getBaseElementType(FD->getType()); | |||
17509 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | |||
17510 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); | |||
17511 | if (RDecl->getDefinition()) { | |||
17512 | // We check for copy constructors before constructors | |||
17513 | // because otherwise we'll never get complaints about | |||
17514 | // copy constructors. | |||
17515 | ||||
17516 | CXXSpecialMember member = CXXInvalid; | |||
17517 | // We're required to check for any non-trivial constructors. Since the | |||
17518 | // implicit default constructor is suppressed if there are any | |||
17519 | // user-declared constructors, we just need to check that there is a | |||
17520 | // trivial default constructor and a trivial copy constructor. (We don't | |||
17521 | // worry about move constructors here, since this is a C++98 check.) | |||
17522 | if (RDecl->hasNonTrivialCopyConstructor()) | |||
17523 | member = CXXCopyConstructor; | |||
17524 | else if (!RDecl->hasTrivialDefaultConstructor()) | |||
17525 | member = CXXDefaultConstructor; | |||
17526 | else if (RDecl->hasNonTrivialCopyAssignment()) | |||
17527 | member = CXXCopyAssignment; | |||
17528 | else if (RDecl->hasNonTrivialDestructor()) | |||
17529 | member = CXXDestructor; | |||
17530 | ||||
17531 | if (member != CXXInvalid) { | |||
17532 | if (!getLangOpts().CPlusPlus11 && | |||
17533 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { | |||
17534 | // Objective-C++ ARC: it is an error to have a non-trivial field of | |||
17535 | // a union. However, system headers in Objective-C programs | |||
17536 | // occasionally have Objective-C lifetime objects within unions, | |||
17537 | // and rather than cause the program to fail, we make those | |||
17538 | // members unavailable. | |||
17539 | SourceLocation Loc = FD->getLocation(); | |||
17540 | if (getSourceManager().isInSystemHeader(Loc)) { | |||
17541 | if (!FD->hasAttr<UnavailableAttr>()) | |||
17542 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | |||
17543 | UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); | |||
17544 | return false; | |||
17545 | } | |||
17546 | } | |||
17547 | ||||
17548 | Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? | |||
17549 | diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : | |||
17550 | diag::err_illegal_union_or_anon_struct_member) | |||
17551 | << FD->getParent()->isUnion() << FD->getDeclName() << member; | |||
17552 | DiagnoseNontrivial(RDecl, member); | |||
17553 | return !getLangOpts().CPlusPlus11; | |||
17554 | } | |||
17555 | } | |||
17556 | } | |||
17557 | ||||
17558 | return false; | |||
17559 | } | |||
17560 | ||||
17561 | /// TranslateIvarVisibility - Translate visibility from a token ID to an | |||
17562 | /// AST enum value. | |||
17563 | static ObjCIvarDecl::AccessControl | |||
17564 | TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { | |||
17565 | switch (ivarVisibility) { | |||
17566 | default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind" , "clang/lib/Sema/SemaDecl.cpp", 17566); | |||
17567 | case tok::objc_private: return ObjCIvarDecl::Private; | |||
17568 | case tok::objc_public: return ObjCIvarDecl::Public; | |||
17569 | case tok::objc_protected: return ObjCIvarDecl::Protected; | |||
17570 | case tok::objc_package: return ObjCIvarDecl::Package; | |||
17571 | } | |||
17572 | } | |||
17573 | ||||
17574 | /// ActOnIvar - Each ivar field of an objective-c class is passed into this | |||
17575 | /// in order to create an IvarDecl object for it. | |||
17576 | Decl *Sema::ActOnIvar(Scope *S, | |||
17577 | SourceLocation DeclStart, | |||
17578 | Declarator &D, Expr *BitfieldWidth, | |||
17579 | tok::ObjCKeywordKind Visibility) { | |||
17580 | ||||
17581 | IdentifierInfo *II = D.getIdentifier(); | |||
17582 | Expr *BitWidth = (Expr*)BitfieldWidth; | |||
17583 | SourceLocation Loc = DeclStart; | |||
17584 | if (II) Loc = D.getIdentifierLoc(); | |||
17585 | ||||
17586 | // FIXME: Unnamed fields can be handled in various different ways, for | |||
17587 | // example, unnamed unions inject all members into the struct namespace! | |||
17588 | ||||
17589 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | |||
17590 | QualType T = TInfo->getType(); | |||
17591 | ||||
17592 | if (BitWidth) { | |||
17593 | // 6.7.2.1p3, 6.7.2.1p4 | |||
17594 | BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); | |||
17595 | if (!BitWidth) | |||
17596 | D.setInvalidType(); | |||
17597 | } else { | |||
17598 | // Not a bitfield. | |||
17599 | ||||
17600 | // validate II. | |||
17601 | ||||
17602 | } | |||
17603 | if (T->isReferenceType()) { | |||
17604 | Diag(Loc, diag::err_ivar_reference_type); | |||
17605 | D.setInvalidType(); | |||
17606 | } | |||
17607 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | |||
17608 | // than a variably modified type. | |||
17609 | else if (T->isVariablyModifiedType()) { | |||
17610 | if (!tryToFixVariablyModifiedVarType( | |||
17611 | TInfo, T, Loc, diag::err_typecheck_ivar_variable_size)) | |||
17612 | D.setInvalidType(); | |||
17613 | } | |||
17614 | ||||
17615 | // Get the visibility (access control) for this ivar. | |||
17616 | ObjCIvarDecl::AccessControl ac = | |||
17617 | Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) | |||
17618 | : ObjCIvarDecl::None; | |||
17619 | // Must set ivar's DeclContext to its enclosing interface. | |||
17620 | ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); | |||
17621 | if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) | |||
17622 | return nullptr; | |||
17623 | ObjCContainerDecl *EnclosingContext; | |||
17624 | if (ObjCImplementationDecl *IMPDecl = | |||
17625 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | |||
17626 | if (LangOpts.ObjCRuntime.isFragile()) { | |||
17627 | // Case of ivar declared in an implementation. Context is that of its class. | |||
17628 | EnclosingContext = IMPDecl->getClassInterface(); | |||
17629 | assert(EnclosingContext && "Implementation has no class interface!")(static_cast <bool> (EnclosingContext && "Implementation has no class interface!" ) ? void (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\"" , "clang/lib/Sema/SemaDecl.cpp", 17629, __extension__ __PRETTY_FUNCTION__ )); | |||
17630 | } | |||
17631 | else | |||
17632 | EnclosingContext = EnclosingDecl; | |||
17633 | } else { | |||
17634 | if (ObjCCategoryDecl *CDecl = | |||
17635 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | |||
17636 | if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { | |||
17637 | Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); | |||
17638 | return nullptr; | |||
17639 | } | |||
17640 | } | |||
17641 | EnclosingContext = EnclosingDecl; | |||
17642 | } | |||
17643 | ||||
17644 | // Construct the decl. | |||
17645 | ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, | |||
17646 | DeclStart, Loc, II, T, | |||
17647 | TInfo, ac, (Expr *)BitfieldWidth); | |||
17648 | ||||
17649 | if (II) { | |||
17650 | NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, | |||
17651 | ForVisibleRedeclaration); | |||
17652 | if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) | |||
17653 | && !isa<TagDecl>(PrevDecl)) { | |||
17654 | Diag(Loc, diag::err_duplicate_member) << II; | |||
17655 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | |||
17656 | NewID->setInvalidDecl(); | |||
17657 | } | |||
17658 | } | |||
17659 | ||||
17660 | // Process attributes attached to the ivar. | |||
17661 | ProcessDeclAttributes(S, NewID, D); | |||
17662 | ||||
17663 | if (D.isInvalidType()) | |||
17664 | NewID->setInvalidDecl(); | |||
17665 | ||||
17666 | // In ARC, infer 'retaining' for ivars of retainable type. | |||
17667 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) | |||
17668 | NewID->setInvalidDecl(); | |||
17669 | ||||
17670 | if (D.getDeclSpec().isModulePrivateSpecified()) | |||
17671 | NewID->setModulePrivate(); | |||
17672 | ||||
17673 | if (II) { | |||
17674 | // FIXME: When interfaces are DeclContexts, we'll need to add | |||
17675 | // these to the interface. | |||
17676 | S->AddDecl(NewID); | |||
17677 | IdResolver.AddDecl(NewID); | |||
17678 | } | |||
17679 | ||||
17680 | if (LangOpts.ObjCRuntime.isNonFragile() && | |||
17681 | !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) | |||
17682 | Diag(Loc, diag::warn_ivars_in_interface); | |||
17683 | ||||
17684 | return NewID; | |||
17685 | } | |||
17686 | ||||
17687 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for | |||
17688 | /// class and class extensions. For every class \@interface and class | |||
17689 | /// extension \@interface, if the last ivar is a bitfield of any type, | |||
17690 | /// then add an implicit `char :0` ivar to the end of that interface. | |||
17691 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, | |||
17692 | SmallVectorImpl<Decl *> &AllIvarDecls) { | |||
17693 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) | |||
17694 | return; | |||
17695 | ||||
17696 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; | |||
17697 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); | |||
17698 | ||||
17699 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) | |||
17700 | return; | |||
17701 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); | |||
17702 | if (!ID) { | |||
17703 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { | |||
17704 | if (!CD->IsClassExtension()) | |||
17705 | return; | |||
17706 | } | |||
17707 | // No need to add this to end of @implementation. | |||
17708 | else | |||
17709 | return; | |||
17710 | } | |||
17711 | // All conditions are met. Add a new bitfield to the tail end of ivars. | |||
17712 | llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); | |||
17713 | Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); | |||
17714 | ||||
17715 | Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), | |||
17716 | DeclLoc, DeclLoc, nullptr, | |||
17717 | Context.CharTy, | |||
17718 | Context.getTrivialTypeSourceInfo(Context.CharTy, | |||
17719 | DeclLoc), | |||
17720 | ObjCIvarDecl::Private, BW, | |||
17721 | true); | |||
17722 | AllIvarDecls.push_back(Ivar); | |||
17723 | } | |||
17724 | ||||
17725 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, | |||
17726 | ArrayRef<Decl *> Fields, SourceLocation LBrac, | |||
17727 | SourceLocation RBrac, | |||
17728 | const ParsedAttributesView &Attrs) { | |||
17729 | assert(EnclosingDecl && "missing record or interface decl")(static_cast <bool> (EnclosingDecl && "missing record or interface decl" ) ? void (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\"" , "clang/lib/Sema/SemaDecl.cpp", 17729, __extension__ __PRETTY_FUNCTION__ )); | |||
17730 | ||||
17731 | // If this is an Objective-C @implementation or category and we have | |||
17732 | // new fields here we should reset the layout of the interface since | |||
17733 | // it will now change. | |||
17734 | if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { | |||
17735 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); | |||
17736 | switch (DC->getKind()) { | |||
17737 | default: break; | |||
17738 | case Decl::ObjCCategory: | |||
17739 | Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); | |||
17740 | break; | |||
17741 | case Decl::ObjCImplementation: | |||
17742 | Context. | |||
17743 | ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); | |||
17744 | break; | |||
17745 | } | |||
17746 | } | |||
17747 | ||||
17748 | RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); | |||
17749 | CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); | |||
17750 | ||||
17751 | // Start counting up the number of named members; make sure to include | |||
17752 | // members of anonymous structs and unions in the total. | |||
17753 | unsigned NumNamedMembers = 0; | |||
17754 | if (Record) { | |||
17755 | for (const auto *I : Record->decls()) { | |||
17756 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | |||
17757 | if (IFD->getDeclName()) | |||
17758 | ++NumNamedMembers; | |||
17759 | } | |||
17760 | } | |||
17761 | ||||
17762 | // Verify that all the fields are okay. | |||
17763 | SmallVector<FieldDecl*, 32> RecFields; | |||
17764 | ||||
17765 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); | |||
17766 | i != end; ++i) { | |||
17767 | FieldDecl *FD = cast<FieldDecl>(*i); | |||
17768 | ||||
17769 | // Get the type for the field. | |||
17770 | const Type *FDTy = FD->getType().getTypePtr(); | |||
17771 | ||||
17772 | if (!FD->isAnonymousStructOrUnion()) { | |||
17773 | // Remember all fields written by the user. | |||
17774 | RecFields.push_back(FD); | |||
17775 | } | |||
17776 | ||||
17777 | // If the field is already invalid for some reason, don't emit more | |||
17778 | // diagnostics about it. | |||
17779 | if (FD->isInvalidDecl()) { | |||
17780 | EnclosingDecl->setInvalidDecl(); | |||
17781 | continue; | |||
17782 | } | |||
17783 | ||||
17784 | // C99 6.7.2.1p2: | |||
17785 | // A structure or union shall not contain a member with | |||
17786 | // incomplete or function type (hence, a structure shall not | |||
17787 | // contain an instance of itself, but may contain a pointer to | |||
17788 | // an instance of itself), except that the last member of a | |||
17789 | // structure with more than one named member may have incomplete | |||
17790 | // array type; such a structure (and any union containing, | |||
17791 | // possibly recursively, a member that is such a structure) | |||
17792 | // shall not be a member of a structure or an element of an | |||
17793 | // array. | |||
17794 | bool IsLastField = (i + 1 == Fields.end()); | |||
17795 | if (FDTy->isFunctionType()) { | |||
17796 | // Field declared as a function. | |||
17797 | Diag(FD->getLocation(), diag::err_field_declared_as_function) | |||
17798 | << FD->getDeclName(); | |||
17799 | FD->setInvalidDecl(); | |||
17800 | EnclosingDecl->setInvalidDecl(); | |||
17801 | continue; | |||
17802 | } else if (FDTy->isIncompleteArrayType() && | |||
17803 | (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { | |||
17804 | if (Record) { | |||
17805 | // Flexible array member. | |||
17806 | // Microsoft and g++ is more permissive regarding flexible array. | |||
17807 | // It will accept flexible array in union and also | |||
17808 | // as the sole element of a struct/class. | |||
17809 | unsigned DiagID = 0; | |||
17810 | if (!Record->isUnion() && !IsLastField) { | |||
17811 | Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) | |||
17812 | << FD->getDeclName() << FD->getType() << Record->getTagKind(); | |||
17813 | Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); | |||
17814 | FD->setInvalidDecl(); | |||
17815 | EnclosingDecl->setInvalidDecl(); | |||
17816 | continue; | |||
17817 | } else if (Record->isUnion()) | |||
17818 | DiagID = getLangOpts().MicrosoftExt | |||
17819 | ? diag::ext_flexible_array_union_ms | |||
17820 | : getLangOpts().CPlusPlus | |||
17821 | ? diag::ext_flexible_array_union_gnu | |||
17822 | : diag::err_flexible_array_union; | |||
17823 | else if (NumNamedMembers < 1) | |||
17824 | DiagID = getLangOpts().MicrosoftExt | |||
17825 | ? diag::ext_flexible_array_empty_aggregate_ms | |||
17826 | : getLangOpts().CPlusPlus | |||
17827 | ? diag::ext_flexible_array_empty_aggregate_gnu | |||
17828 | : diag::err_flexible_array_empty_aggregate; | |||
17829 | ||||
17830 | if (DiagID) | |||
17831 | Diag(FD->getLocation(), DiagID) << FD->getDeclName() | |||
17832 | << Record->getTagKind(); | |||
17833 | // While the layout of types that contain virtual bases is not specified | |||
17834 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place | |||
17835 | // virtual bases after the derived members. This would make a flexible | |||
17836 | // array member declared at the end of an object not adjacent to the end | |||
17837 | // of the type. | |||
17838 | if (CXXRecord && CXXRecord->getNumVBases() != 0) | |||
17839 | Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) | |||
17840 | << FD->getDeclName() << Record->getTagKind(); | |||
17841 | if (!getLangOpts().C99) | |||
17842 | Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) | |||
17843 | << FD->getDeclName() << Record->getTagKind(); | |||
17844 | ||||
17845 | // If the element type has a non-trivial destructor, we would not | |||
17846 | // implicitly destroy the elements, so disallow it for now. | |||
17847 | // | |||
17848 | // FIXME: GCC allows this. We should probably either implicitly delete | |||
17849 | // the destructor of the containing class, or just allow this. | |||
17850 | QualType BaseElem = Context.getBaseElementType(FD->getType()); | |||
17851 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { | |||
17852 | Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) | |||
17853 | << FD->getDeclName() << FD->getType(); | |||
17854 | FD->setInvalidDecl(); | |||
17855 | EnclosingDecl->setInvalidDecl(); | |||
17856 | continue; | |||
17857 | } | |||
17858 | // Okay, we have a legal flexible array member at the end of the struct. | |||
17859 | Record->setHasFlexibleArrayMember(true); | |||
17860 | } else { | |||
17861 | // In ObjCContainerDecl ivars with incomplete array type are accepted, | |||
17862 | // unless they are followed by another ivar. That check is done | |||
17863 | // elsewhere, after synthesized ivars are known. | |||
17864 | } | |||
17865 | } else if (!FDTy->isDependentType() && | |||
17866 | RequireCompleteSizedType( | |||
17867 | FD->getLocation(), FD->getType(), | |||
17868 | diag::err_field_incomplete_or_sizeless)) { | |||
17869 | // Incomplete type | |||
17870 | FD->setInvalidDecl(); | |||
17871 | EnclosingDecl->setInvalidDecl(); | |||
17872 | continue; | |||
17873 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { | |||
17874 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { | |||
17875 | // A type which contains a flexible array member is considered to be a | |||
17876 | // flexible array member. | |||
17877 | Record->setHasFlexibleArrayMember(true); | |||
17878 | if (!Record->isUnion()) { | |||
17879 | // If this is a struct/class and this is not the last element, reject | |||
17880 | // it. Note that GCC supports variable sized arrays in the middle of | |||
17881 | // structures. | |||
17882 | if (!IsLastField) | |||
17883 | Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) | |||
17884 | << FD->getDeclName() << FD->getType(); | |||
17885 | else { | |||
17886 | // We support flexible arrays at the end of structs in | |||
17887 | // other structs as an extension. | |||
17888 | Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) | |||
17889 | << FD->getDeclName(); | |||
17890 | } | |||
17891 | } | |||
17892 | } | |||
17893 | if (isa<ObjCContainerDecl>(EnclosingDecl) && | |||
17894 | RequireNonAbstractType(FD->getLocation(), FD->getType(), | |||
17895 | diag::err_abstract_type_in_decl, | |||
17896 | AbstractIvarType)) { | |||
17897 | // Ivars can not have abstract class types | |||
17898 | FD->setInvalidDecl(); | |||
17899 | } | |||
17900 | if (Record && FDTTy->getDecl()->hasObjectMember()) | |||
17901 | Record->setHasObjectMember(true); | |||
17902 | if (Record && FDTTy->getDecl()->hasVolatileMember()) | |||
17903 | Record->setHasVolatileMember(true); | |||
17904 | } else if (FDTy->isObjCObjectType()) { | |||
17905 | /// A field cannot be an Objective-c object | |||
17906 | Diag(FD->getLocation(), diag::err_statically_allocated_object) | |||
17907 | << FixItHint::CreateInsertion(FD->getLocation(), "*"); | |||
17908 | QualType T = Context.getObjCObjectPointerType(FD->getType()); | |||
17909 | FD->setType(T); | |||
17910 | } else if (Record && Record->isUnion() && | |||
17911 | FD->getType().hasNonTrivialObjCLifetime() && | |||
17912 | getSourceManager().isInSystemHeader(FD->getLocation()) && | |||
17913 | !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && | |||
17914 | (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || | |||
17915 | !Context.hasDirectOwnershipQualifier(FD->getType()))) { | |||
17916 | // For backward compatibility, fields of C unions declared in system | |||
17917 | // headers that have non-trivial ObjC ownership qualifications are marked | |||
17918 | // as unavailable unless the qualifier is explicit and __strong. This can | |||
17919 | // break ABI compatibility between programs compiled with ARC and MRR, but | |||
17920 | // is a better option than rejecting programs using those unions under | |||
17921 | // ARC. | |||
17922 | FD->addAttr(UnavailableAttr::CreateImplicit( | |||
17923 | Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, | |||
17924 | FD->getLocation())); | |||
17925 | } else if (getLangOpts().ObjC && | |||
17926 | getLangOpts().getGC() != LangOptions::NonGC && Record && | |||
17927 | !Record->hasObjectMember()) { | |||
17928 | if (FD->getType()->isObjCObjectPointerType() || | |||
17929 | FD->getType().isObjCGCStrong()) | |||
17930 | Record->setHasObjectMember(true); | |||
17931 | else if (Context.getAsArrayType(FD->getType())) { | |||
17932 | QualType BaseType = Context.getBaseElementType(FD->getType()); | |||
17933 | if (BaseType->isRecordType() && | |||
17934 | BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) | |||
17935 | Record->setHasObjectMember(true); | |||
17936 | else if (BaseType->isObjCObjectPointerType() || | |||
17937 | BaseType.isObjCGCStrong()) | |||
17938 | Record->setHasObjectMember(true); | |||
17939 | } | |||
17940 | } | |||
17941 | ||||
17942 | if (Record && !getLangOpts().CPlusPlus && | |||
17943 | !shouldIgnoreForRecordTriviality(FD)) { | |||
17944 | QualType FT = FD->getType(); | |||
17945 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { | |||
17946 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); | |||
17947 | if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | |||
17948 | Record->isUnion()) | |||
17949 | Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); | |||
17950 | } | |||
17951 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); | |||
17952 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { | |||
17953 | Record->setNonTrivialToPrimitiveCopy(true); | |||
17954 | if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) | |||
17955 | Record->setHasNonTrivialToPrimitiveCopyCUnion(true); | |||
17956 | } | |||
17957 | if (FT.isDestructedType()) { | |||
17958 | Record->setNonTrivialToPrimitiveDestroy(true); | |||
17959 | Record->setParamDestroyedInCallee(true); | |||
17960 | if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) | |||
17961 | Record->setHasNonTrivialToPrimitiveDestructCUnion(true); | |||
17962 | } | |||
17963 | ||||
17964 | if (const auto *RT = FT->getAs<RecordType>()) { | |||
17965 | if (RT->getDecl()->getArgPassingRestrictions() == | |||
17966 | RecordDecl::APK_CanNeverPassInRegs) | |||
17967 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | |||
17968 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) | |||
17969 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | |||
17970 | } | |||
17971 | ||||
17972 | if (Record && FD->getType().isVolatileQualified()) | |||
17973 | Record->setHasVolatileMember(true); | |||
17974 | // Keep track of the number of named members. | |||
17975 | if (FD->getIdentifier()) | |||
17976 | ++NumNamedMembers; | |||
17977 | } | |||
17978 | ||||
17979 | // Okay, we successfully defined 'Record'. | |||
17980 | if (Record) { | |||
17981 | bool Completed = false; | |||
17982 | if (CXXRecord) { | |||
17983 | if (!CXXRecord->isInvalidDecl()) { | |||
17984 | // Set access bits correctly on the directly-declared conversions. | |||
17985 | for (CXXRecordDecl::conversion_iterator | |||
17986 | I = CXXRecord->conversion_begin(), | |||
17987 | E = CXXRecord->conversion_end(); I != E; ++I) | |||
17988 | I.setAccess((*I)->getAccess()); | |||
17989 | } | |||
17990 | ||||
17991 | // Add any implicitly-declared members to this class. | |||
17992 | AddImplicitlyDeclaredMembersToClass(CXXRecord); | |||
17993 | ||||
17994 | if (!CXXRecord->isDependentType()) { | |||
17995 | if (!CXXRecord->isInvalidDecl()) { | |||
17996 | // If we have virtual base classes, we may end up finding multiple | |||
17997 | // final overriders for a given virtual function. Check for this | |||
17998 | // problem now. | |||
17999 | if (CXXRecord->getNumVBases()) { | |||
18000 | CXXFinalOverriderMap FinalOverriders; | |||
18001 | CXXRecord->getFinalOverriders(FinalOverriders); | |||
18002 | ||||
18003 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | |||
18004 | MEnd = FinalOverriders.end(); | |||
18005 | M != MEnd; ++M) { | |||
18006 | for (OverridingMethods::iterator SO = M->second.begin(), | |||
18007 | SOEnd = M->second.end(); | |||
18008 | SO != SOEnd; ++SO) { | |||
18009 | assert(SO->second.size() > 0 &&(static_cast <bool> (SO->second.size() > 0 && "Virtual function without overriding functions?") ? void (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "clang/lib/Sema/SemaDecl.cpp", 18010, __extension__ __PRETTY_FUNCTION__ )) | |||
18010 | "Virtual function without overriding functions?")(static_cast <bool> (SO->second.size() > 0 && "Virtual function without overriding functions?") ? void (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "clang/lib/Sema/SemaDecl.cpp", 18010, __extension__ __PRETTY_FUNCTION__ )); | |||
18011 | if (SO->second.size() == 1) | |||
18012 | continue; | |||
18013 | ||||
18014 | // C++ [class.virtual]p2: | |||
18015 | // In a derived class, if a virtual member function of a base | |||
18016 | // class subobject has more than one final overrider the | |||
18017 | // program is ill-formed. | |||
18018 | Diag(Record->getLocation(), diag::err_multiple_final_overriders) | |||
18019 | << (const NamedDecl *)M->first << Record; | |||
18020 | Diag(M->first->getLocation(), | |||
18021 | diag::note_overridden_virtual_function); | |||
18022 | for (OverridingMethods::overriding_iterator | |||
18023 | OM = SO->second.begin(), | |||
18024 | OMEnd = SO->second.end(); | |||
18025 | OM != OMEnd; ++OM) | |||
18026 | Diag(OM->Method->getLocation(), diag::note_final_overrider) | |||
18027 | << (const NamedDecl *)M->first << OM->Method->getParent(); | |||
18028 | ||||
18029 | Record->setInvalidDecl(); | |||
18030 | } | |||
18031 | } | |||
18032 | CXXRecord->completeDefinition(&FinalOverriders); | |||
18033 | Completed = true; | |||
18034 | } | |||
18035 | } | |||
18036 | } | |||
18037 | } | |||
18038 | ||||
18039 | if (!Completed) | |||
18040 | Record->completeDefinition(); | |||
18041 | ||||
18042 | // Handle attributes before checking the layout. | |||
18043 | ProcessDeclAttributeList(S, Record, Attrs); | |||
18044 | ||||
18045 | // Maybe randomize the field order. | |||
18046 | if (!getLangOpts().CPlusPlus && Record->hasAttr<RandomizeLayoutAttr>() && | |||
18047 | !Record->isUnion() && !getLangOpts().RandstructSeed.empty() && | |||
18048 | !Record->isRandomized()) { | |||
18049 | SmallVector<Decl *, 32> OrigFieldOrdering(Record->fields()); | |||
18050 | SmallVector<Decl *, 32> NewFieldOrdering; | |||
18051 | if (randstruct::randomizeStructureLayout( | |||
18052 | Context, Record->getNameAsString(), OrigFieldOrdering, | |||
18053 | NewFieldOrdering)) | |||
18054 | Record->reorderFields(NewFieldOrdering); | |||
18055 | } | |||
18056 | ||||
18057 | // We may have deferred checking for a deleted destructor. Check now. | |||
18058 | if (CXXRecord) { | |||
18059 | auto *Dtor = CXXRecord->getDestructor(); | |||
18060 | if (Dtor && Dtor->isImplicit() && | |||
18061 | ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { | |||
18062 | CXXRecord->setImplicitDestructorIsDeleted(); | |||
18063 | SetDeclDeleted(Dtor, CXXRecord->getLocation()); | |||
18064 | } | |||
18065 | } | |||
18066 | ||||
18067 | if (Record->hasAttrs()) { | |||
18068 | CheckAlignasUnderalignment(Record); | |||
18069 | ||||
18070 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) | |||
18071 | checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), | |||
18072 | IA->getRange(), IA->getBestCase(), | |||
18073 | IA->getInheritanceModel()); | |||
18074 | } | |||
18075 | ||||
18076 | // Check if the structure/union declaration is a type that can have zero | |||
18077 | // size in C. For C this is a language extension, for C++ it may cause | |||
18078 | // compatibility problems. | |||
18079 | bool CheckForZeroSize; | |||
18080 | if (!getLangOpts().CPlusPlus) { | |||
18081 | CheckForZeroSize = true; | |||
18082 | } else { | |||
18083 | // For C++ filter out types that cannot be referenced in C code. | |||
18084 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); | |||
18085 | CheckForZeroSize = | |||
18086 | CXXRecord->getLexicalDeclContext()->isExternCContext() && | |||
18087 | !CXXRecord->isDependentType() && !inTemplateInstantiation() && | |||
18088 | CXXRecord->isCLike(); | |||
18089 | } | |||
18090 | if (CheckForZeroSize) { | |||
18091 | bool ZeroSize = true; | |||
18092 | bool IsEmpty = true; | |||
18093 | unsigned NonBitFields = 0; | |||
18094 | for (RecordDecl::field_iterator I = Record->field_begin(), | |||
18095 | E = Record->field_end(); | |||
18096 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { | |||
18097 | IsEmpty = false; | |||
18098 | if (I->isUnnamedBitfield()) { | |||
18099 | if (!I->isZeroLengthBitField(Context)) | |||
18100 | ZeroSize = false; | |||
18101 | } else { | |||
18102 | ++NonBitFields; | |||
18103 | QualType FieldType = I->getType(); | |||
18104 | if (FieldType->isIncompleteType() || | |||
18105 | !Context.getTypeSizeInChars(FieldType).isZero()) | |||
18106 | ZeroSize = false; | |||
18107 | } | |||
18108 | } | |||
18109 | ||||
18110 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are | |||
18111 | // allowed in C++, but warn if its declaration is inside | |||
18112 | // extern "C" block. | |||
18113 | if (ZeroSize) { | |||
18114 | Diag(RecLoc, getLangOpts().CPlusPlus ? | |||
18115 | diag::warn_zero_size_struct_union_in_extern_c : | |||
18116 | diag::warn_zero_size_struct_union_compat) | |||
18117 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); | |||
18118 | } | |||
18119 | ||||
18120 | // Structs without named members are extension in C (C99 6.7.2.1p7), | |||
18121 | // but are accepted by GCC. | |||
18122 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { | |||
18123 | Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : | |||
18124 | diag::ext_no_named_members_in_struct_union) | |||
18125 | << Record->isUnion(); | |||
18126 | } | |||
18127 | } | |||
18128 | } else { | |||
18129 | ObjCIvarDecl **ClsFields = | |||
18130 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); | |||
18131 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { | |||
18132 | ID->setEndOfDefinitionLoc(RBrac); | |||
18133 | // Add ivar's to class's DeclContext. | |||
18134 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | |||
18135 | ClsFields[i]->setLexicalDeclContext(ID); | |||
18136 | ID->addDecl(ClsFields[i]); | |||
18137 | } | |||
18138 | // Must enforce the rule that ivars in the base classes may not be | |||
18139 | // duplicates. | |||
18140 | if (ID->getSuperClass()) | |||
18141 | DiagnoseDuplicateIvars(ID, ID->getSuperClass()); | |||
18142 | } else if (ObjCImplementationDecl *IMPDecl = | |||
18143 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | |||
18144 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")(static_cast <bool> (IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ) ? void (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"" , "clang/lib/Sema/SemaDecl.cpp", 18144, __extension__ __PRETTY_FUNCTION__ )); | |||
18145 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) | |||
18146 | // Ivar declared in @implementation never belongs to the implementation. | |||
18147 | // Only it is in implementation's lexical context. | |||
18148 | ClsFields[I]->setLexicalDeclContext(IMPDecl); | |||
18149 | CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); | |||
18150 | IMPDecl->setIvarLBraceLoc(LBrac); | |||
18151 | IMPDecl->setIvarRBraceLoc(RBrac); | |||
18152 | } else if (ObjCCategoryDecl *CDecl = | |||
18153 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | |||
18154 | // case of ivars in class extension; all other cases have been | |||
18155 | // reported as errors elsewhere. | |||
18156 | // FIXME. Class extension does not have a LocEnd field. | |||
18157 | // CDecl->setLocEnd(RBrac); | |||
18158 | // Add ivar's to class extension's DeclContext. | |||
18159 | // Diagnose redeclaration of private ivars. | |||
18160 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); | |||
18161 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | |||
18162 | if (IDecl) { | |||
18163 | if (const ObjCIvarDecl *ClsIvar = | |||
18164 | IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { | |||
18165 | Diag(ClsFields[i]->getLocation(), | |||
18166 | diag::err_duplicate_ivar_declaration); | |||
18167 | Diag(ClsIvar->getLocation(), diag::note_previous_definition); | |||
18168 | continue; | |||
18169 | } | |||
18170 | for (const auto *Ext : IDecl->known_extensions()) { | |||
18171 | if (const ObjCIvarDecl *ClsExtIvar | |||
18172 | = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { | |||
18173 | Diag(ClsFields[i]->getLocation(), | |||
18174 | diag::err_duplicate_ivar_declaration); | |||
18175 | Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); | |||
18176 | continue; | |||
18177 | } | |||
18178 | } | |||
18179 | } | |||
18180 | ClsFields[i]->setLexicalDeclContext(CDecl); | |||
18181 | CDecl->addDecl(ClsFields[i]); | |||
18182 | } | |||
18183 | CDecl->setIvarLBraceLoc(LBrac); | |||
18184 | CDecl->setIvarRBraceLoc(RBrac); | |||
18185 | } | |||
18186 | } | |||
18187 | } | |||
18188 | ||||
18189 | /// Determine whether the given integral value is representable within | |||
18190 | /// the given type T. | |||
18191 | static bool isRepresentableIntegerValue(ASTContext &Context, | |||
18192 | llvm::APSInt &Value, | |||
18193 | QualType T) { | |||
18194 | assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(static_cast <bool> ((T->isIntegralType(Context) || T ->isEnumeralType()) && "Integral type required!") ? void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "clang/lib/Sema/SemaDecl.cpp", 18195, __extension__ __PRETTY_FUNCTION__ )) | |||
18195 | "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T ->isEnumeralType()) && "Integral type required!") ? void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "clang/lib/Sema/SemaDecl.cpp", 18195, __extension__ __PRETTY_FUNCTION__ )); | |||
18196 | unsigned BitWidth = Context.getIntWidth(T); | |||
18197 | ||||
18198 | if (Value.isUnsigned() || Value.isNonNegative()) { | |||
18199 | if (T->isSignedIntegerOrEnumerationType()) | |||
18200 | --BitWidth; | |||
18201 | return Value.getActiveBits() <= BitWidth; | |||
18202 | } | |||
18203 | return Value.getMinSignedBits() <= BitWidth; | |||
18204 | } | |||
18205 | ||||
18206 | // Given an integral type, return the next larger integral type | |||
18207 | // (or a NULL type of no such type exists). | |||
18208 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { | |||
18209 | // FIXME: Int128/UInt128 support, which also needs to be introduced into | |||
18210 | // enum checking below. | |||
18211 | assert((T->isIntegralType(Context) ||(static_cast <bool> ((T->isIntegralType(Context) || T ->isEnumeralType()) && "Integral type required!") ? void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "clang/lib/Sema/SemaDecl.cpp", 18212, __extension__ __PRETTY_FUNCTION__ )) | |||
18212 | T->isEnumeralType()) && "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T ->isEnumeralType()) && "Integral type required!") ? void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "clang/lib/Sema/SemaDecl.cpp", 18212, __extension__ __PRETTY_FUNCTION__ )); | |||
18213 | const unsigned NumTypes = 4; | |||
18214 | QualType SignedIntegralTypes[NumTypes] = { | |||
18215 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy | |||
18216 | }; | |||
18217 | QualType UnsignedIntegralTypes[NumTypes] = { | |||
18218 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, | |||
18219 | Context.UnsignedLongLongTy | |||
18220 | }; | |||
18221 | ||||
18222 | unsigned BitWidth = Context.getTypeSize(T); | |||
18223 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes | |||
18224 | : UnsignedIntegralTypes; | |||
18225 | for (unsigned I = 0; I != NumTypes; ++I) | |||
18226 | if (Context.getTypeSize(Types[I]) > BitWidth) | |||
18227 | return Types[I]; | |||
18228 | ||||
18229 | return QualType(); | |||
18230 | } | |||
18231 | ||||
18232 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, | |||
18233 | EnumConstantDecl *LastEnumConst, | |||
18234 | SourceLocation IdLoc, | |||
18235 | IdentifierInfo *Id, | |||
18236 | Expr *Val) { | |||
18237 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | |||
18238 | llvm::APSInt EnumVal(IntWidth); | |||
18239 | QualType EltTy; | |||
18240 | ||||
18241 | if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) | |||
18242 | Val = nullptr; | |||
18243 | ||||
18244 | if (Val) | |||
18245 | Val = DefaultLvalueConversion(Val).get(); | |||
18246 | ||||
18247 | if (Val) { | |||
18248 | if (Enum->isDependentType() || Val->isTypeDependent() || | |||
18249 | Val->containsErrors()) | |||
18250 | EltTy = Context.DependentTy; | |||
18251 | else { | |||
18252 | // FIXME: We don't allow folding in C++11 mode for an enum with a fixed | |||
18253 | // underlying type, but do allow it in all other contexts. | |||
18254 | if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { | |||
18255 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the | |||
18256 | // constant-expression in the enumerator-definition shall be a converted | |||
18257 | // constant expression of the underlying type. | |||
18258 | EltTy = Enum->getIntegerType(); | |||
18259 | ExprResult Converted = | |||
18260 | CheckConvertedConstantExpression(Val, EltTy, EnumVal, | |||
18261 | CCEK_Enumerator); | |||
18262 | if (Converted.isInvalid()) | |||
18263 | Val = nullptr; | |||
18264 | else | |||
18265 | Val = Converted.get(); | |||
18266 | } else if (!Val->isValueDependent() && | |||
18267 | !(Val = | |||
18268 | VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold) | |||
18269 | .get())) { | |||
18270 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. | |||
18271 | } else { | |||
18272 | if (Enum->isComplete()) { | |||
18273 | EltTy = Enum->getIntegerType(); | |||
18274 | ||||
18275 | // In Obj-C and Microsoft mode, require the enumeration value to be | |||
18276 | // representable in the underlying type of the enumeration. In C++11, | |||
18277 | // we perform a non-narrowing conversion as part of converted constant | |||
18278 | // expression checking. | |||
18279 | if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | |||
18280 | if (Context.getTargetInfo() | |||
18281 | .getTriple() | |||
18282 | .isWindowsMSVCEnvironment()) { | |||
18283 | Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; | |||
18284 | } else { | |||
18285 | Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; | |||
18286 | } | |||
18287 | } | |||
18288 | ||||
18289 | // Cast to the underlying type. | |||
18290 | Val = ImpCastExprToType(Val, EltTy, | |||
18291 | EltTy->isBooleanType() ? CK_IntegralToBoolean | |||
18292 | : CK_IntegralCast) | |||
18293 | .get(); | |||
18294 | } else if (getLangOpts().CPlusPlus) { | |||
18295 | // C++11 [dcl.enum]p5: | |||
18296 | // If the underlying type is not fixed, the type of each enumerator | |||
18297 | // is the type of its initializing value: | |||
18298 | // - If an initializer is specified for an enumerator, the | |||
18299 | // initializing value has the same type as the expression. | |||
18300 | EltTy = Val->getType(); | |||
18301 | } else { | |||
18302 | // C99 6.7.2.2p2: | |||
18303 | // The expression that defines the value of an enumeration constant | |||
18304 | // shall be an integer constant expression that has a value | |||
18305 | // representable as an int. | |||
18306 | ||||
18307 | // Complain if the value is not representable in an int. | |||
18308 | if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) | |||
18309 | Diag(IdLoc, diag::ext_enum_value_not_int) | |||
18310 | << toString(EnumVal, 10) << Val->getSourceRange() | |||
18311 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); | |||
18312 | else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { | |||
18313 | // Force the type of the expression to 'int'. | |||
18314 | Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); | |||
18315 | } | |||
18316 | EltTy = Val->getType(); | |||
18317 | } | |||
18318 | } | |||
18319 | } | |||
18320 | } | |||
18321 | ||||
18322 | if (!Val) { | |||
18323 | if (Enum->isDependentType()) | |||
18324 | EltTy = Context.DependentTy; | |||
18325 | else if (!LastEnumConst) { | |||
18326 | // C++0x [dcl.enum]p5: | |||
18327 | // If the underlying type is not fixed, the type of each enumerator | |||
18328 | // is the type of its initializing value: | |||
18329 | // - If no initializer is specified for the first enumerator, the | |||
18330 | // initializing value has an unspecified integral type. | |||
18331 | // | |||
18332 | // GCC uses 'int' for its unspecified integral type, as does | |||
18333 | // C99 6.7.2.2p3. | |||
18334 | if (Enum->isFixed()) { | |||
18335 | EltTy = Enum->getIntegerType(); | |||
18336 | } | |||
18337 | else { | |||
18338 | EltTy = Context.IntTy; | |||
18339 | } | |||
18340 | } else { | |||
18341 | // Assign the last value + 1. | |||
18342 | EnumVal = LastEnumConst->getInitVal(); | |||
18343 | ++EnumVal; | |||
18344 | EltTy = LastEnumConst->getType(); | |||
18345 | ||||
18346 | // Check for overflow on increment. | |||
18347 | if (EnumVal < LastEnumConst->getInitVal()) { | |||
18348 | // C++0x [dcl.enum]p5: | |||
18349 | // If the underlying type is not fixed, the type of each enumerator | |||
18350 | // is the type of its initializing value: | |||
18351 | // | |||
18352 | // - Otherwise the type of the initializing value is the same as | |||
18353 | // the type of the initializing value of the preceding enumerator | |||
18354 | // unless the incremented value is not representable in that type, | |||
18355 | // in which case the type is an unspecified integral type | |||
18356 | // sufficient to contain the incremented value. If no such type | |||
18357 | // exists, the program is ill-formed. | |||
18358 | QualType T = getNextLargerIntegralType(Context, EltTy); | |||
18359 | if (T.isNull() || Enum->isFixed()) { | |||
18360 | // There is no integral type larger enough to represent this | |||
18361 | // value. Complain, then allow the value to wrap around. | |||
18362 | EnumVal = LastEnumConst->getInitVal(); | |||
18363 | EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); | |||
18364 | ++EnumVal; | |||
18365 | if (Enum->isFixed()) | |||
18366 | // When the underlying type is fixed, this is ill-formed. | |||
18367 | Diag(IdLoc, diag::err_enumerator_wrapped) | |||
18368 | << toString(EnumVal, 10) | |||
18369 | << EltTy; | |||
18370 | else | |||
18371 | Diag(IdLoc, diag::ext_enumerator_increment_too_large) | |||
18372 | << toString(EnumVal, 10); | |||
18373 | } else { | |||
18374 | EltTy = T; | |||
18375 | } | |||
18376 | ||||
18377 | // Retrieve the last enumerator's value, extent that type to the | |||
18378 | // type that is supposed to be large enough to represent the incremented | |||
18379 | // value, then increment. | |||
18380 | EnumVal = LastEnumConst->getInitVal(); | |||
18381 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | |||
18382 | EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); | |||
18383 | ++EnumVal; | |||
18384 | ||||
18385 | // If we're not in C++, diagnose the overflow of enumerator values, | |||
18386 | // which in C99 means that the enumerator value is not representable in | |||
18387 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that | |||
18388 | // permits enumerator values that are representable in some larger | |||
18389 | // integral type. | |||
18390 | if (!getLangOpts().CPlusPlus && !T.isNull()) | |||
18391 | Diag(IdLoc, diag::warn_enum_value_overflow); | |||
18392 | } else if (!getLangOpts().CPlusPlus && | |||
18393 | !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | |||
18394 | // Enforce C99 6.7.2.2p2 even when we compute the next value. | |||
18395 | Diag(IdLoc, diag::ext_enum_value_not_int) | |||
18396 | << toString(EnumVal, 10) << 1; | |||
18397 | } | |||
18398 | } | |||
18399 | } | |||
18400 | ||||
18401 | if (!EltTy->isDependentType()) { | |||
18402 | // Make the enumerator value match the signedness and size of the | |||
18403 | // enumerator's type. | |||
18404 | EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); | |||
18405 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | |||
18406 | } | |||
18407 | ||||
18408 | return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, | |||
18409 | Val, EnumVal); | |||
18410 | } | |||
18411 | ||||
18412 | Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, | |||
18413 | SourceLocation IILoc) { | |||
18414 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || | |||
18415 | !getLangOpts().CPlusPlus) | |||
18416 | return SkipBodyInfo(); | |||
18417 | ||||
18418 | // We have an anonymous enum definition. Look up the first enumerator to | |||
18419 | // determine if we should merge the definition with an existing one and | |||
18420 | // skip the body. | |||
18421 | NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, | |||
18422 | forRedeclarationInCurContext()); | |||
18423 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); | |||
18424 | if (!PrevECD) | |||
18425 | return SkipBodyInfo(); | |||
18426 | ||||
18427 | EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); | |||
18428 | NamedDecl *Hidden; | |||
18429 | if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { | |||
18430 | SkipBodyInfo Skip; | |||
18431 | Skip.Previous = Hidden; | |||
18432 | return Skip; | |||
18433 | } | |||
18434 | ||||
18435 | return SkipBodyInfo(); | |||
18436 | } | |||
18437 | ||||
18438 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, | |||
18439 | SourceLocation IdLoc, IdentifierInfo *Id, | |||
18440 | const ParsedAttributesView &Attrs, | |||
18441 | SourceLocation EqualLoc, Expr *Val) { | |||
18442 | EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); | |||
18443 | EnumConstantDecl *LastEnumConst = | |||
18444 | cast_or_null<EnumConstantDecl>(lastEnumConst); | |||
18445 | ||||
18446 | // The scope passed in may not be a decl scope. Zip up the scope tree until | |||
18447 | // we find one that is. | |||
18448 | S = getNonFieldDeclScope(S); | |||
18449 | ||||
18450 | // Verify that there isn't already something declared with this name in this | |||
18451 | // scope. | |||
18452 | LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); | |||
18453 | LookupName(R, S); | |||
18454 | NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); | |||
18455 | ||||
18456 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | |||
18457 | // Maybe we will complain about the shadowed template parameter. | |||
18458 | DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); | |||
18459 | // Just pretend that we didn't see the previous declaration. | |||
18460 | PrevDecl = nullptr; | |||
18461 | } | |||
18462 | ||||
18463 | // C++ [class.mem]p15: | |||
18464 | // If T is the name of a class, then each of the following shall have a name | |||
18465 | // different from T: | |||
18466 | // - every enumerator of every member of class T that is an unscoped | |||
18467 | // enumerated type | |||
18468 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) | |||
18469 | DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), | |||
18470 | DeclarationNameInfo(Id, IdLoc)); | |||
18471 | ||||
18472 | EnumConstantDecl *New = | |||
18473 | CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); | |||
18474 | if (!New) | |||
18475 | return nullptr; | |||
18476 | ||||
18477 | if (PrevDecl) { | |||
18478 | if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { | |||
18479 | // Check for other kinds of shadowing not already handled. | |||
18480 | CheckShadow(New, PrevDecl, R); | |||
18481 | } | |||
18482 | ||||
18483 | // When in C++, we may get a TagDecl with the same name; in this case the | |||
18484 | // enum constant will 'hide' the tag. | |||
18485 | assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(static_cast <bool> ((getLangOpts().CPlusPlus || !isa< TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!" ) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "clang/lib/Sema/SemaDecl.cpp", 18486, __extension__ __PRETTY_FUNCTION__ )) | |||
18486 | "Received TagDecl when not in C++!")(static_cast <bool> ((getLangOpts().CPlusPlus || !isa< TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!" ) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "clang/lib/Sema/SemaDecl.cpp", 18486, __extension__ __PRETTY_FUNCTION__ )); | |||
18487 | if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { | |||
18488 | if (isa<EnumConstantDecl>(PrevDecl)) | |||
18489 | Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; | |||
18490 | else | |||
18491 | Diag(IdLoc, diag::err_redefinition) << Id; | |||
18492 | notePreviousDefinition(PrevDecl, IdLoc); | |||
18493 | return nullptr; | |||
18494 | } | |||
18495 | } | |||
18496 | ||||
18497 | // Process attributes. | |||
18498 | ProcessDeclAttributeList(S, New, Attrs); | |||
18499 | AddPragmaAttributes(S, New); | |||
18500 | ||||
18501 | // Register this decl in the current scope stack. | |||
18502 | New->setAccess(TheEnumDecl->getAccess()); | |||
18503 | PushOnScopeChains(New, S); | |||
18504 | ||||
18505 | ActOnDocumentableDecl(New); | |||
18506 | ||||
18507 | return New; | |||
18508 | } | |||
18509 | ||||
18510 | // Returns true when the enum initial expression does not trigger the | |||
18511 | // duplicate enum warning. A few common cases are exempted as follows: | |||
18512 | // Element2 = Element1 | |||
18513 | // Element2 = Element1 + 1 | |||
18514 | // Element2 = Element1 - 1 | |||
18515 | // Where Element2 and Element1 are from the same enum. | |||
18516 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { | |||
18517 | Expr *InitExpr = ECD->getInitExpr(); | |||
18518 | if (!InitExpr) | |||
18519 | return true; | |||
18520 | InitExpr = InitExpr->IgnoreImpCasts(); | |||
18521 | ||||
18522 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { | |||
18523 | if (!BO->isAdditiveOp()) | |||
18524 | return true; | |||
18525 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); | |||
18526 | if (!IL) | |||
18527 | return true; | |||
18528 | if (IL->getValue() != 1) | |||
18529 | return true; | |||
18530 | ||||
18531 | InitExpr = BO->getLHS(); | |||
18532 | } | |||
18533 | ||||
18534 | // This checks if the elements are from the same enum. | |||
18535 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); | |||
18536 | if (!DRE) | |||
18537 | return true; | |||
18538 | ||||
18539 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); | |||
18540 | if (!EnumConstant) | |||
18541 | return true; | |||
18542 | ||||
18543 | if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != | |||
18544 | Enum) | |||
18545 | return true; | |||
18546 | ||||
18547 | return false; | |||
18548 | } | |||
18549 | ||||
18550 | // Emits a warning when an element is implicitly set a value that | |||
18551 | // a previous element has already been set to. | |||
18552 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, | |||
18553 | EnumDecl *Enum, QualType EnumType) { | |||
18554 | // Avoid anonymous enums | |||
18555 | if (!Enum->getIdentifier()) | |||
18556 | return; | |||
18557 | ||||
18558 | // Only check for small enums. | |||
18559 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) | |||
18560 | return; | |||
18561 | ||||
18562 | if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) | |||
18563 | return; | |||
18564 | ||||
18565 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; | |||
18566 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; | |||
18567 | ||||
18568 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; | |||
18569 | ||||
18570 | // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. | |||
18571 | typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; | |||
18572 | ||||
18573 | // Use int64_t as a key to avoid needing special handling for map keys. | |||
18574 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { | |||
18575 | llvm::APSInt Val = D->getInitVal(); | |||
18576 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); | |||
18577 | }; | |||
18578 | ||||
18579 | DuplicatesVector DupVector; | |||
18580 | ValueToVectorMap EnumMap; | |||
18581 | ||||
18582 | // Populate the EnumMap with all values represented by enum constants without | |||
18583 | // an initializer. | |||
18584 | for (auto *Element : Elements) { | |||
18585 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); | |||
18586 | ||||
18587 | // Null EnumConstantDecl means a previous diagnostic has been emitted for | |||
18588 | // this constant. Skip this enum since it may be ill-formed. | |||
18589 | if (!ECD) { | |||
18590 | return; | |||
18591 | } | |||
18592 | ||||
18593 | // Constants with initalizers are handled in the next loop. | |||
18594 | if (ECD->getInitExpr()) | |||
18595 | continue; | |||
18596 | ||||
18597 | // Duplicate values are handled in the next loop. | |||
18598 | EnumMap.insert({EnumConstantToKey(ECD), ECD}); | |||
18599 | } | |||
18600 | ||||
18601 | if (EnumMap.size() == 0) | |||
18602 | return; | |||
18603 | ||||
18604 | // Create vectors for any values that has duplicates. | |||
18605 | for (auto *Element : Elements) { | |||
18606 | // The last loop returned if any constant was null. | |||
18607 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); | |||
18608 | if (!ValidDuplicateEnum(ECD, Enum)) | |||
18609 | continue; | |||
18610 | ||||
18611 | auto Iter = EnumMap.find(EnumConstantToKey(ECD)); | |||
18612 | if (Iter == EnumMap.end()) | |||
18613 | continue; | |||
18614 | ||||
18615 | DeclOrVector& Entry = Iter->second; | |||
18616 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { | |||
18617 | // Ensure constants are different. | |||
18618 | if (D == ECD) | |||
18619 | continue; | |||
18620 | ||||
18621 | // Create new vector and push values onto it. | |||
18622 | auto Vec = std::make_unique<ECDVector>(); | |||
18623 | Vec->push_back(D); | |||
18624 | Vec->push_back(ECD); | |||
18625 | ||||
18626 | // Update entry to point to the duplicates vector. | |||
18627 | Entry = Vec.get(); | |||
18628 | ||||
18629 | // Store the vector somewhere we can consult later for quick emission of | |||
18630 | // diagnostics. | |||
18631 | DupVector.emplace_back(std::move(Vec)); | |||
18632 | continue; | |||
18633 | } | |||
18634 | ||||
18635 | ECDVector *Vec = Entry.get<ECDVector*>(); | |||
18636 | // Make sure constants are not added more than once. | |||
18637 | if (*Vec->begin() == ECD) | |||
18638 | continue; | |||
18639 | ||||
18640 | Vec->push_back(ECD); | |||
18641 | } | |||
18642 | ||||
18643 | // Emit diagnostics. | |||
18644 | for (const auto &Vec : DupVector) { | |||
18645 | assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")(static_cast <bool> (Vec->size() > 1 && "ECDVector should have at least 2 elements." ) ? void (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\"" , "clang/lib/Sema/SemaDecl.cpp", 18645, __extension__ __PRETTY_FUNCTION__ )); | |||
18646 | ||||
18647 | // Emit warning for one enum constant. | |||
18648 | auto *FirstECD = Vec->front(); | |||
18649 | S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) | |||
18650 | << FirstECD << toString(FirstECD->getInitVal(), 10) | |||
18651 | << FirstECD->getSourceRange(); | |||
18652 | ||||
18653 | // Emit one note for each of the remaining enum constants with | |||
18654 | // the same value. | |||
18655 | for (auto *ECD : llvm::drop_begin(*Vec)) | |||
18656 | S.Diag(ECD->getLocation(), diag::note_duplicate_element) | |||
18657 | << ECD << toString(ECD->getInitVal(), 10) | |||
18658 | << ECD->getSourceRange(); | |||
18659 | } | |||
18660 | } | |||
18661 | ||||
18662 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, | |||
18663 | bool AllowMask) const { | |||
18664 | assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")(static_cast <bool> (ED->isClosedFlag() && "looking for value in non-flag or open enum" ) ? void (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\"" , "clang/lib/Sema/SemaDecl.cpp", 18664, __extension__ __PRETTY_FUNCTION__ )); | |||
18665 | assert(ED->isCompleteDefinition() && "expected enum definition")(static_cast <bool> (ED->isCompleteDefinition() && "expected enum definition") ? void (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\"" , "clang/lib/Sema/SemaDecl.cpp", 18665, __extension__ __PRETTY_FUNCTION__ )); | |||
18666 | ||||
18667 | auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); | |||
18668 | llvm::APInt &FlagBits = R.first->second; | |||
18669 | ||||
18670 | if (R.second) { | |||
18671 | for (auto *E : ED->enumerators()) { | |||
18672 | const auto &EVal = E->getInitVal(); | |||
18673 | // Only single-bit enumerators introduce new flag values. | |||
18674 | if (EVal.isPowerOf2()) | |||
18675 | FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; | |||
18676 | } | |||
18677 | } | |||
18678 | ||||
18679 | // A value is in a flag enum if either its bits are a subset of the enum's | |||
18680 | // flag bits (the first condition) or we are allowing masks and the same is | |||
18681 | // true of its complement (the second condition). When masks are allowed, we | |||
18682 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. | |||
18683 | // | |||
18684 | // While it's true that any value could be used as a mask, the assumption is | |||
18685 | // that a mask will have all of the insignificant bits set. Anything else is | |||
18686 | // likely a logic error. | |||
18687 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); | |||
18688 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); | |||
18689 | } | |||
18690 | ||||
18691 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, | |||
18692 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, | |||
18693 | const ParsedAttributesView &Attrs) { | |||
18694 | EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); | |||
18695 | QualType EnumType = Context.getTypeDeclType(Enum); | |||
18696 | ||||
18697 | ProcessDeclAttributeList(S, Enum, Attrs); | |||
18698 | ||||
18699 | if (Enum->isDependentType()) { | |||
18700 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | |||
18701 | EnumConstantDecl *ECD = | |||
18702 | cast_or_null<EnumConstantDecl>(Elements[i]); | |||
18703 | if (!ECD) continue; | |||
18704 | ||||
18705 | ECD->setType(EnumType); | |||
18706 | } | |||
18707 | ||||
18708 | Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); | |||
18709 | return; | |||
18710 | } | |||
18711 | ||||
18712 | // TODO: If the result value doesn't fit in an int, it must be a long or long | |||
18713 | // long value. ISO C does not support this, but GCC does as an extension, | |||
18714 | // emit a warning. | |||
18715 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | |||
18716 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); | |||
18717 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); | |||
18718 | ||||
18719 | // Verify that all the values are okay, compute the size of the values, and | |||
18720 | // reverse the list. | |||
18721 | unsigned NumNegativeBits = 0; | |||
18722 | unsigned NumPositiveBits = 0; | |||
18723 | ||||
18724 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | |||
18725 | EnumConstantDecl *ECD = | |||
18726 | cast_or_null<EnumConstantDecl>(Elements[i]); | |||
18727 | if (!ECD) continue; // Already issued a diagnostic. | |||
18728 | ||||
18729 | const llvm::APSInt &InitVal = ECD->getInitVal(); | |||
18730 | ||||
18731 | // Keep track of the size of positive and negative values. | |||
18732 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) | |||
18733 | NumPositiveBits = std::max(NumPositiveBits, | |||
18734 | (unsigned)InitVal.getActiveBits()); | |||
18735 | else | |||
18736 | NumNegativeBits = std::max(NumNegativeBits, | |||
18737 | (unsigned)InitVal.getMinSignedBits()); | |||
18738 | } | |||
18739 | ||||
18740 | // Figure out the type that should be used for this enum. | |||
18741 | QualType BestType; | |||
18742 | unsigned BestWidth; | |||
18743 | ||||
18744 | // C++0x N3000 [conv.prom]p3: | |||
18745 | // An rvalue of an unscoped enumeration type whose underlying | |||
18746 | // type is not fixed can be converted to an rvalue of the first | |||
18747 | // of the following types that can represent all the values of | |||
18748 | // the enumeration: int, unsigned int, long int, unsigned long | |||
18749 | // int, long long int, or unsigned long long int. | |||
18750 | // C99 6.4.4.3p2: | |||
18751 | // An identifier declared as an enumeration constant has type int. | |||
18752 | // The C99 rule is modified by a gcc extension | |||
18753 | QualType BestPromotionType; | |||
18754 | ||||
18755 | bool Packed = Enum->hasAttr<PackedAttr>(); | |||
18756 | // -fshort-enums is the equivalent to specifying the packed attribute on all | |||
18757 | // enum definitions. | |||
18758 | if (LangOpts.ShortEnums) | |||
18759 | Packed = true; | |||
18760 | ||||
18761 | // If the enum already has a type because it is fixed or dictated by the | |||
18762 | // target, promote that type instead of analyzing the enumerators. | |||
18763 | if (Enum->isComplete()) { | |||
18764 | BestType = Enum->getIntegerType(); | |||
18765 | if (BestType->isPromotableIntegerType()) | |||
18766 | BestPromotionType = Context.getPromotedIntegerType(BestType); | |||
18767 | else | |||
18768 | BestPromotionType = BestType; | |||
18769 | ||||
18770 | BestWidth = Context.getIntWidth(BestType); | |||
18771 | } | |||
18772 | else if (NumNegativeBits) { | |||
18773 | // If there is a negative value, figure out the smallest integer type (of | |||
18774 | // int/long/longlong) that fits. | |||
18775 | // If it's packed, check also if it fits a char or a short. | |||
18776 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { | |||
18777 | BestType = Context.SignedCharTy; | |||
18778 | BestWidth = CharWidth; | |||
18779 | } else if (Packed && NumNegativeBits <= ShortWidth && | |||
18780 | NumPositiveBits < ShortWidth) { | |||
18781 | BestType = Context.ShortTy; | |||
18782 | BestWidth = ShortWidth; | |||
18783 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { | |||
18784 | BestType = Context.IntTy; | |||
18785 | BestWidth = IntWidth; | |||
18786 | } else { | |||
18787 | BestWidth = Context.getTargetInfo().getLongWidth(); | |||
18788 | ||||
18789 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { | |||
18790 | BestType = Context.LongTy; | |||
18791 | } else { | |||
18792 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | |||
18793 | ||||
18794 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) | |||
18795 | Diag(Enum->getLocation(), diag::ext_enum_too_large); | |||
18796 | BestType = Context.LongLongTy; | |||
18797 | } | |||
18798 | } | |||
18799 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); | |||
18800 | } else { | |||
18801 | // If there is no negative value, figure out the smallest type that fits | |||
18802 | // all of the enumerator values. | |||
18803 | // If it's packed, check also if it fits a char or a short. | |||
18804 | if (Packed && NumPositiveBits <= CharWidth) { | |||
18805 | BestType = Context.UnsignedCharTy; | |||
18806 | BestPromotionType = Context.IntTy; | |||
18807 | BestWidth = CharWidth; | |||
18808 | } else if (Packed && NumPositiveBits <= ShortWidth) { | |||
18809 | BestType = Context.UnsignedShortTy; | |||
18810 | BestPromotionType = Context.IntTy; | |||
18811 | BestWidth = ShortWidth; | |||
18812 | } else if (NumPositiveBits <= IntWidth) { | |||
18813 | BestType = Context.UnsignedIntTy; | |||
18814 | BestWidth = IntWidth; | |||
18815 | BestPromotionType | |||
18816 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
18817 | ? Context.UnsignedIntTy : Context.IntTy; | |||
18818 | } else if (NumPositiveBits <= | |||
18819 | (BestWidth = Context.getTargetInfo().getLongWidth())) { | |||
18820 | BestType = Context.UnsignedLongTy; | |||
18821 | BestPromotionType | |||
18822 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
18823 | ? Context.UnsignedLongTy : Context.LongTy; | |||
18824 | } else { | |||
18825 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | |||
18826 | assert(NumPositiveBits <= BestWidth &&(static_cast <bool> (NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?") ? void (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "clang/lib/Sema/SemaDecl.cpp", 18827, __extension__ __PRETTY_FUNCTION__ )) | |||
18827 | "How could an initializer get larger than ULL?")(static_cast <bool> (NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?") ? void (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "clang/lib/Sema/SemaDecl.cpp", 18827, __extension__ __PRETTY_FUNCTION__ )); | |||
18828 | BestType = Context.UnsignedLongLongTy; | |||
18829 | BestPromotionType | |||
18830 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | |||
18831 | ? Context.UnsignedLongLongTy : Context.LongLongTy; | |||
18832 | } | |||
18833 | } | |||
18834 | ||||
18835 | // Loop over all of the enumerator constants, changing their types to match | |||
18836 | // the type of the enum if needed. | |||
18837 | for (auto *D : Elements) { | |||
18838 | auto *ECD = cast_or_null<EnumConstantDecl>(D); | |||
18839 | if (!ECD) continue; // Already issued a diagnostic. | |||
18840 | ||||
18841 | // Standard C says the enumerators have int type, but we allow, as an | |||
18842 | // extension, the enumerators to be larger than int size. If each | |||
18843 | // enumerator value fits in an int, type it as an int, otherwise type it the | |||
18844 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" | |||
18845 | // that X has type 'int', not 'unsigned'. | |||
18846 | ||||
18847 | // Determine whether the value fits into an int. | |||
18848 | llvm::APSInt InitVal = ECD->getInitVal(); | |||
18849 | ||||
18850 | // If it fits into an integer type, force it. Otherwise force it to match | |||
18851 | // the enum decl type. | |||
18852 | QualType NewTy; | |||
18853 | unsigned NewWidth; | |||
18854 | bool NewSign; | |||
18855 | if (!getLangOpts().CPlusPlus && | |||
18856 | !Enum->isFixed() && | |||
18857 | isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { | |||
18858 | NewTy = Context.IntTy; | |||
18859 | NewWidth = IntWidth; | |||
18860 | NewSign = true; | |||
18861 | } else if (ECD->getType() == BestType) { | |||
18862 | // Already the right type! | |||
18863 | if (getLangOpts().CPlusPlus) | |||
18864 | // C++ [dcl.enum]p4: Following the closing brace of an | |||
18865 | // enum-specifier, each enumerator has the type of its | |||
18866 | // enumeration. | |||
18867 | ECD->setType(EnumType); | |||
18868 | continue; | |||
18869 | } else { | |||
18870 | NewTy = BestType; | |||
18871 | NewWidth = BestWidth; | |||
18872 | NewSign = BestType->isSignedIntegerOrEnumerationType(); | |||
18873 | } | |||
18874 | ||||
18875 | // Adjust the APSInt value. | |||
18876 | InitVal = InitVal.extOrTrunc(NewWidth); | |||
18877 | InitVal.setIsSigned(NewSign); | |||
18878 | ECD->setInitVal(InitVal); | |||
18879 | ||||
18880 | // Adjust the Expr initializer and type. | |||
18881 | if (ECD->getInitExpr() && | |||
18882 | !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) | |||
18883 | ECD->setInitExpr(ImplicitCastExpr::Create( | |||
18884 | Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), | |||
18885 | /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride())); | |||
18886 | if (getLangOpts().CPlusPlus) | |||
18887 | // C++ [dcl.enum]p4: Following the closing brace of an | |||
18888 | // enum-specifier, each enumerator has the type of its | |||
18889 | // enumeration. | |||
18890 | ECD->setType(EnumType); | |||
18891 | else | |||
18892 | ECD->setType(NewTy); | |||
18893 | } | |||
18894 | ||||
18895 | Enum->completeDefinition(BestType, BestPromotionType, | |||
18896 | NumPositiveBits, NumNegativeBits); | |||
18897 | ||||
18898 | CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); | |||
18899 | ||||
18900 | if (Enum->isClosedFlag()) { | |||
18901 | for (Decl *D : Elements) { | |||
18902 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); | |||
18903 | if (!ECD) continue; // Already issued a diagnostic. | |||
18904 | ||||
18905 | llvm::APSInt InitVal = ECD->getInitVal(); | |||
18906 | if (InitVal != 0 && !InitVal.isPowerOf2() && | |||
18907 | !IsValueInFlagEnum(Enum, InitVal, true)) | |||
18908 | Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) | |||
18909 | << ECD << Enum; | |||
18910 | } | |||
18911 | } | |||
18912 | ||||
18913 | // Now that the enum type is defined, ensure it's not been underaligned. | |||
18914 | if (Enum->hasAttrs()) | |||
18915 | CheckAlignasUnderalignment(Enum); | |||
18916 | } | |||
18917 | ||||
18918 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, | |||
18919 | SourceLocation StartLoc, | |||
18920 | SourceLocation EndLoc) { | |||
18921 | StringLiteral *AsmString = cast<StringLiteral>(expr); | |||
18922 | ||||
18923 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, | |||
18924 | AsmString, StartLoc, | |||
18925 | EndLoc); | |||
18926 | CurContext->addDecl(New); | |||
18927 | return New; | |||
18928 | } | |||
18929 | ||||
18930 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, | |||
18931 | IdentifierInfo* AliasName, | |||
18932 | SourceLocation PragmaLoc, | |||
18933 | SourceLocation NameLoc, | |||
18934 | SourceLocation AliasNameLoc) { | |||
18935 | NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, | |||
18936 | LookupOrdinaryName); | |||
18937 | AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), | |||
18938 | AttributeCommonInfo::AS_Pragma); | |||
18939 | AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( | |||
18940 | Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info); | |||
18941 | ||||
18942 | // If a declaration that: | |||
18943 | // 1) declares a function or a variable | |||
18944 | // 2) has external linkage | |||
18945 | // already exists, add a label attribute to it. | |||
18946 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | |||
18947 | if (isDeclExternC(PrevDecl)) | |||
18948 | PrevDecl->addAttr(Attr); | |||
18949 | else | |||
18950 | Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) | |||
18951 | << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; | |||
18952 | // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. | |||
18953 | } else | |||
18954 | (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); | |||
18955 | } | |||
18956 | ||||
18957 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, | |||
18958 | SourceLocation PragmaLoc, | |||
18959 | SourceLocation NameLoc) { | |||
18960 | Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); | |||
18961 | ||||
18962 | if (PrevDecl) { | |||
18963 | PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); | |||
18964 | } else { | |||
18965 | (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc)); | |||
18966 | } | |||
18967 | } | |||
18968 | ||||
18969 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, | |||
18970 | IdentifierInfo* AliasName, | |||
18971 | SourceLocation PragmaLoc, | |||
18972 | SourceLocation NameLoc, | |||
18973 | SourceLocation AliasNameLoc) { | |||
18974 | Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, | |||
18975 | LookupOrdinaryName); | |||
18976 | WeakInfo W = WeakInfo(Name, NameLoc); | |||
18977 | ||||
18978 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | |||
18979 | if (!PrevDecl->hasAttr<AliasAttr>()) | |||
18980 | if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) | |||
18981 | DeclApplyPragmaWeak(TUScope, ND, W); | |||
18982 | } else { | |||
18983 | (void)WeakUndeclaredIdentifiers[AliasName].insert(W); | |||
18984 | } | |||
18985 | } | |||
18986 | ||||
18987 | Decl *Sema::getObjCDeclContext() const { | |||
18988 | return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); | |||
18989 | } | |||
18990 | ||||
18991 | Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, | |||
18992 | bool Final) { | |||
18993 | assert(FD && "Expected non-null FunctionDecl")(static_cast <bool> (FD && "Expected non-null FunctionDecl" ) ? void (0) : __assert_fail ("FD && \"Expected non-null FunctionDecl\"" , "clang/lib/Sema/SemaDecl.cpp", 18993, __extension__ __PRETTY_FUNCTION__ )); | |||
18994 | ||||
18995 | // SYCL functions can be template, so we check if they have appropriate | |||
18996 | // attribute prior to checking if it is a template. | |||
18997 | if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) | |||
18998 | return FunctionEmissionStatus::Emitted; | |||
18999 | ||||
19000 | // Templates are emitted when they're instantiated. | |||
19001 | if (FD->isDependentContext()) | |||
19002 | return FunctionEmissionStatus::TemplateDiscarded; | |||
19003 | ||||
19004 | // Check whether this function is an externally visible definition. | |||
19005 | auto IsEmittedForExternalSymbol = [this, FD]() { | |||
19006 | // We have to check the GVA linkage of the function's *definition* -- if we | |||
19007 | // only have a declaration, we don't know whether or not the function will | |||
19008 | // be emitted, because (say) the definition could include "inline". | |||
19009 | FunctionDecl *Def = FD->getDefinition(); | |||
19010 | ||||
19011 | return Def && !isDiscardableGVALinkage( | |||
19012 | getASTContext().GetGVALinkageForFunction(Def)); | |||
19013 | }; | |||
19014 | ||||
19015 | if (LangOpts.OpenMPIsDevice) { | |||
19016 | // In OpenMP device mode we will not emit host only functions, or functions | |||
19017 | // we don't need due to their linkage. | |||
19018 | Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = | |||
19019 | OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); | |||
19020 | // DevTy may be changed later by | |||
19021 | // #pragma omp declare target to(*) device_type(*). | |||
19022 | // Therefore DevTy having no value does not imply host. The emission status | |||
19023 | // will be checked again at the end of compilation unit with Final = true. | |||
19024 | if (DevTy.hasValue()) | |||
19025 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) | |||
19026 | return FunctionEmissionStatus::OMPDiscarded; | |||
19027 | // If we have an explicit value for the device type, or we are in a target | |||
19028 | // declare context, we need to emit all extern and used symbols. | |||
19029 | if (isInOpenMPDeclareTargetContext() || DevTy.hasValue()) | |||
19030 | if (IsEmittedForExternalSymbol()) | |||
19031 | return FunctionEmissionStatus::Emitted; | |||
19032 | // Device mode only emits what it must, if it wasn't tagged yet and needed, | |||
19033 | // we'll omit it. | |||
19034 | if (Final) | |||
19035 | return FunctionEmissionStatus::OMPDiscarded; | |||
19036 | } else if (LangOpts.OpenMP > 45) { | |||
19037 | // In OpenMP host compilation prior to 5.0 everything was an emitted host | |||
19038 | // function. In 5.0, no_host was introduced which might cause a function to | |||
19039 | // be ommitted. | |||
19040 | Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = | |||
19041 | OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); | |||
19042 | if (DevTy.hasValue()) | |||
19043 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) | |||
19044 | return FunctionEmissionStatus::OMPDiscarded; | |||
19045 | } | |||
19046 | ||||
19047 | if (Final && LangOpts.OpenMP && !LangOpts.CUDA) | |||
19048 | return FunctionEmissionStatus::Emitted; | |||
19049 | ||||
19050 | if (LangOpts.CUDA) { | |||
19051 | // When compiling for device, host functions are never emitted. Similarly, | |||
19052 | // when compiling for host, device and global functions are never emitted. | |||
19053 | // (Technically, we do emit a host-side stub for global functions, but this | |||
19054 | // doesn't count for our purposes here.) | |||
19055 | Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); | |||
19056 | if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) | |||
19057 | return FunctionEmissionStatus::CUDADiscarded; | |||
19058 | if (!LangOpts.CUDAIsDevice && | |||
19059 | (T == Sema::CFT_Device || T == Sema::CFT_Global)) | |||
19060 | return FunctionEmissionStatus::CUDADiscarded; | |||
19061 | ||||
19062 | if (IsEmittedForExternalSymbol()) | |||
19063 | return FunctionEmissionStatus::Emitted; | |||
19064 | } | |||
19065 | ||||
19066 | // Otherwise, the function is known-emitted if it's in our set of | |||
19067 | // known-emitted functions. | |||
19068 | return FunctionEmissionStatus::Unknown; | |||
19069 | } | |||
19070 | ||||
19071 | bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { | |||
19072 | // Host-side references to a __global__ function refer to the stub, so the | |||
19073 | // function itself is never emitted and therefore should not be marked. | |||
19074 | // If we have host fn calls kernel fn calls host+device, the HD function | |||
19075 | // does not get instantiated on the host. We model this by omitting at the | |||
19076 | // call to the kernel from the callgraph. This ensures that, when compiling | |||
19077 | // for host, only HD functions actually called from the host get marked as | |||
19078 | // known-emitted. | |||
19079 | return LangOpts.CUDA && !LangOpts.CUDAIsDevice && | |||
19080 | IdentifyCUDATarget(Callee) == CFT_Global; | |||
19081 | } |