File: | clang/lib/Sema/SemaDecl.cpp |
Warning: | line 13941, column 54 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/ExprCXX.h" | ||||||
25 | #include "clang/AST/NonTrivialTypeVisitor.h" | ||||||
26 | #include "clang/AST/StmtCXX.h" | ||||||
27 | #include "clang/Basic/Builtins.h" | ||||||
28 | #include "clang/Basic/PartialDiagnostic.h" | ||||||
29 | #include "clang/Basic/SourceManager.h" | ||||||
30 | #include "clang/Basic/TargetInfo.h" | ||||||
31 | #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex | ||||||
32 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. | ||||||
33 | #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex | ||||||
34 | #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() | ||||||
35 | #include "clang/Sema/CXXFieldCollector.h" | ||||||
36 | #include "clang/Sema/DeclSpec.h" | ||||||
37 | #include "clang/Sema/DelayedDiagnostic.h" | ||||||
38 | #include "clang/Sema/Initialization.h" | ||||||
39 | #include "clang/Sema/Lookup.h" | ||||||
40 | #include "clang/Sema/ParsedTemplate.h" | ||||||
41 | #include "clang/Sema/Scope.h" | ||||||
42 | #include "clang/Sema/ScopeInfo.h" | ||||||
43 | #include "clang/Sema/SemaInternal.h" | ||||||
44 | #include "clang/Sema/Template.h" | ||||||
45 | #include "llvm/ADT/SmallString.h" | ||||||
46 | #include "llvm/ADT/Triple.h" | ||||||
47 | #include <algorithm> | ||||||
48 | #include <cstring> | ||||||
49 | #include <functional> | ||||||
50 | |||||||
51 | using namespace clang; | ||||||
52 | using namespace sema; | ||||||
53 | |||||||
54 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { | ||||||
55 | if (OwnedType) { | ||||||
56 | Decl *Group[2] = { OwnedType, Ptr }; | ||||||
57 | return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); | ||||||
58 | } | ||||||
59 | |||||||
60 | return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); | ||||||
61 | } | ||||||
62 | |||||||
63 | namespace { | ||||||
64 | |||||||
65 | class TypeNameValidatorCCC final : public CorrectionCandidateCallback { | ||||||
66 | public: | ||||||
67 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, | ||||||
68 | bool AllowTemplates = false, | ||||||
69 | bool AllowNonTemplates = true) | ||||||
70 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), | ||||||
71 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { | ||||||
72 | WantExpressionKeywords = false; | ||||||
73 | WantCXXNamedCasts = false; | ||||||
74 | WantRemainingKeywords = false; | ||||||
75 | } | ||||||
76 | |||||||
77 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||
78 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | ||||||
79 | if (!AllowInvalidDecl && ND->isInvalidDecl()) | ||||||
80 | return false; | ||||||
81 | |||||||
82 | if (getAsTypeTemplateDecl(ND)) | ||||||
83 | return AllowTemplates; | ||||||
84 | |||||||
85 | bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); | ||||||
86 | if (!IsType) | ||||||
87 | return false; | ||||||
88 | |||||||
89 | if (AllowNonTemplates) | ||||||
90 | return true; | ||||||
91 | |||||||
92 | // An injected-class-name of a class template (specialization) is valid | ||||||
93 | // as a template or as a non-template. | ||||||
94 | if (AllowTemplates) { | ||||||
95 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | ||||||
96 | if (!RD || !RD->isInjectedClassName()) | ||||||
97 | return false; | ||||||
98 | RD = cast<CXXRecordDecl>(RD->getDeclContext()); | ||||||
99 | return RD->getDescribedClassTemplate() || | ||||||
100 | isa<ClassTemplateSpecializationDecl>(RD); | ||||||
101 | } | ||||||
102 | |||||||
103 | return false; | ||||||
104 | } | ||||||
105 | |||||||
106 | return !WantClassName && candidate.isKeyword(); | ||||||
107 | } | ||||||
108 | |||||||
109 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||
110 | return std::make_unique<TypeNameValidatorCCC>(*this); | ||||||
111 | } | ||||||
112 | |||||||
113 | private: | ||||||
114 | bool AllowInvalidDecl; | ||||||
115 | bool WantClassName; | ||||||
116 | bool AllowTemplates; | ||||||
117 | bool AllowNonTemplates; | ||||||
118 | }; | ||||||
119 | |||||||
120 | } // end anonymous namespace | ||||||
121 | |||||||
122 | /// Determine whether the token kind starts a simple-type-specifier. | ||||||
123 | bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { | ||||||
124 | switch (Kind) { | ||||||
125 | // FIXME: Take into account the current language when deciding whether a | ||||||
126 | // token kind is a valid type specifier | ||||||
127 | case tok::kw_short: | ||||||
128 | case tok::kw_long: | ||||||
129 | case tok::kw___int64: | ||||||
130 | case tok::kw___int128: | ||||||
131 | case tok::kw_signed: | ||||||
132 | case tok::kw_unsigned: | ||||||
133 | case tok::kw_void: | ||||||
134 | case tok::kw_char: | ||||||
135 | case tok::kw_int: | ||||||
136 | case tok::kw_half: | ||||||
137 | case tok::kw_float: | ||||||
138 | case tok::kw_double: | ||||||
139 | case tok::kw__Float16: | ||||||
140 | case tok::kw___float128: | ||||||
141 | case tok::kw_wchar_t: | ||||||
142 | case tok::kw_bool: | ||||||
143 | case tok::kw___underlying_type: | ||||||
144 | case tok::kw___auto_type: | ||||||
145 | return true; | ||||||
146 | |||||||
147 | case tok::annot_typename: | ||||||
148 | case tok::kw_char16_t: | ||||||
149 | case tok::kw_char32_t: | ||||||
150 | case tok::kw_typeof: | ||||||
151 | case tok::annot_decltype: | ||||||
152 | case tok::kw_decltype: | ||||||
153 | return getLangOpts().CPlusPlus; | ||||||
154 | |||||||
155 | case tok::kw_char8_t: | ||||||
156 | return getLangOpts().Char8; | ||||||
157 | |||||||
158 | default: | ||||||
159 | break; | ||||||
160 | } | ||||||
161 | |||||||
162 | return false; | ||||||
163 | } | ||||||
164 | |||||||
165 | namespace { | ||||||
166 | enum class UnqualifiedTypeNameLookupResult { | ||||||
167 | NotFound, | ||||||
168 | FoundNonType, | ||||||
169 | FoundType | ||||||
170 | }; | ||||||
171 | } // end anonymous namespace | ||||||
172 | |||||||
173 | /// Tries to perform unqualified lookup of the type decls in bases for | ||||||
174 | /// dependent class. | ||||||
175 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a | ||||||
176 | /// type decl, \a FoundType if only type decls are found. | ||||||
177 | static UnqualifiedTypeNameLookupResult | ||||||
178 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, | ||||||
179 | SourceLocation NameLoc, | ||||||
180 | const CXXRecordDecl *RD) { | ||||||
181 | if (!RD->hasDefinition()) | ||||||
182 | return UnqualifiedTypeNameLookupResult::NotFound; | ||||||
183 | // Look for type decls in base classes. | ||||||
184 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||||
185 | UnqualifiedTypeNameLookupResult::NotFound; | ||||||
186 | for (const auto &Base : RD->bases()) { | ||||||
187 | const CXXRecordDecl *BaseRD = nullptr; | ||||||
188 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) | ||||||
189 | BaseRD = BaseTT->getAsCXXRecordDecl(); | ||||||
190 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { | ||||||
191 | // Look for type decls in dependent base classes that have known primary | ||||||
192 | // templates. | ||||||
193 | if (!TST || !TST->isDependentType()) | ||||||
194 | continue; | ||||||
195 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); | ||||||
196 | if (!TD) | ||||||
197 | continue; | ||||||
198 | if (auto *BasePrimaryTemplate = | ||||||
199 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { | ||||||
200 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||||
201 | BaseRD = BasePrimaryTemplate; | ||||||
202 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { | ||||||
203 | if (const ClassTemplatePartialSpecializationDecl *PS = | ||||||
204 | CTD->findPartialSpecialization(Base.getType())) | ||||||
205 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||||
206 | BaseRD = PS; | ||||||
207 | } | ||||||
208 | } | ||||||
209 | } | ||||||
210 | if (BaseRD) { | ||||||
211 | for (NamedDecl *ND : BaseRD->lookup(&II)) { | ||||||
212 | if (!isa<TypeDecl>(ND)) | ||||||
213 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||||
214 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||||
215 | } | ||||||
216 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { | ||||||
217 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { | ||||||
218 | case UnqualifiedTypeNameLookupResult::FoundNonType: | ||||||
219 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||||
220 | case UnqualifiedTypeNameLookupResult::FoundType: | ||||||
221 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||||
222 | break; | ||||||
223 | case UnqualifiedTypeNameLookupResult::NotFound: | ||||||
224 | break; | ||||||
225 | } | ||||||
226 | } | ||||||
227 | } | ||||||
228 | } | ||||||
229 | |||||||
230 | return FoundTypeDecl; | ||||||
231 | } | ||||||
232 | |||||||
233 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, | ||||||
234 | const IdentifierInfo &II, | ||||||
235 | SourceLocation NameLoc) { | ||||||
236 | // Lookup in the parent class template context, if any. | ||||||
237 | const CXXRecordDecl *RD = nullptr; | ||||||
238 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||||
239 | UnqualifiedTypeNameLookupResult::NotFound; | ||||||
240 | for (DeclContext *DC = S.CurContext; | ||||||
241 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; | ||||||
242 | DC = DC->getParent()) { | ||||||
243 | // Look for type decls in dependent base classes that have known primary | ||||||
244 | // templates. | ||||||
245 | RD = dyn_cast<CXXRecordDecl>(DC); | ||||||
246 | if (RD && RD->getDescribedClassTemplate()) | ||||||
247 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); | ||||||
248 | } | ||||||
249 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) | ||||||
250 | return nullptr; | ||||||
251 | |||||||
252 | // We found some types in dependent base classes. Recover as if the user | ||||||
253 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the | ||||||
254 | // lookup during template instantiation. | ||||||
255 | S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; | ||||||
256 | |||||||
257 | ASTContext &Context = S.Context; | ||||||
258 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, | ||||||
259 | cast<Type>(Context.getRecordType(RD))); | ||||||
260 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); | ||||||
261 | |||||||
262 | CXXScopeSpec SS; | ||||||
263 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
264 | |||||||
265 | TypeLocBuilder Builder; | ||||||
266 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||||
267 | DepTL.setNameLoc(NameLoc); | ||||||
268 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
269 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||
270 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
271 | } | ||||||
272 | |||||||
273 | /// If the identifier refers to a type name within this scope, | ||||||
274 | /// return the declaration of that type. | ||||||
275 | /// | ||||||
276 | /// This routine performs ordinary name lookup of the identifier II | ||||||
277 | /// within the given scope, with optional C++ scope specifier SS, to | ||||||
278 | /// determine whether the name refers to a type. If so, returns an | ||||||
279 | /// opaque pointer (actually a QualType) corresponding to that | ||||||
280 | /// type. Otherwise, returns NULL. | ||||||
281 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | ||||||
282 | Scope *S, CXXScopeSpec *SS, | ||||||
283 | bool isClassName, bool HasTrailingDot, | ||||||
284 | ParsedType ObjectTypePtr, | ||||||
285 | bool IsCtorOrDtorName, | ||||||
286 | bool WantNontrivialTypeSourceInfo, | ||||||
287 | bool IsClassTemplateDeductionContext, | ||||||
288 | IdentifierInfo **CorrectedII) { | ||||||
289 | // FIXME: Consider allowing this outside C++1z mode as an extension. | ||||||
290 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && | ||||||
291 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && | ||||||
292 | !isClassName && !HasTrailingDot; | ||||||
293 | |||||||
294 | // Determine where we will perform name lookup. | ||||||
295 | DeclContext *LookupCtx = nullptr; | ||||||
296 | if (ObjectTypePtr) { | ||||||
297 | QualType ObjectType = ObjectTypePtr.get(); | ||||||
298 | if (ObjectType->isRecordType()) | ||||||
299 | LookupCtx = computeDeclContext(ObjectType); | ||||||
300 | } else if (SS && SS->isNotEmpty()) { | ||||||
301 | LookupCtx = computeDeclContext(*SS, false); | ||||||
302 | |||||||
303 | if (!LookupCtx) { | ||||||
304 | if (isDependentScopeSpecifier(*SS)) { | ||||||
305 | // C++ [temp.res]p3: | ||||||
306 | // A qualified-id that refers to a type and in which the | ||||||
307 | // nested-name-specifier depends on a template-parameter (14.6.2) | ||||||
308 | // shall be prefixed by the keyword typename to indicate that the | ||||||
309 | // qualified-id denotes a type, forming an | ||||||
310 | // elaborated-type-specifier (7.1.5.3). | ||||||
311 | // | ||||||
312 | // We therefore do not perform any name lookup if the result would | ||||||
313 | // refer to a member of an unknown specialization. | ||||||
314 | if (!isClassName && !IsCtorOrDtorName) | ||||||
315 | return nullptr; | ||||||
316 | |||||||
317 | // We know from the grammar that this name refers to a type, | ||||||
318 | // so build a dependent node to describe the type. | ||||||
319 | if (WantNontrivialTypeSourceInfo) | ||||||
320 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); | ||||||
321 | |||||||
322 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); | ||||||
323 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, | ||||||
324 | II, NameLoc); | ||||||
325 | return ParsedType::make(T); | ||||||
326 | } | ||||||
327 | |||||||
328 | return nullptr; | ||||||
329 | } | ||||||
330 | |||||||
331 | if (!LookupCtx->isDependentContext() && | ||||||
332 | RequireCompleteDeclContext(*SS, LookupCtx)) | ||||||
333 | return nullptr; | ||||||
334 | } | ||||||
335 | |||||||
336 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of | ||||||
337 | // lookup for class-names. | ||||||
338 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : | ||||||
339 | LookupOrdinaryName; | ||||||
340 | LookupResult Result(*this, &II, NameLoc, Kind); | ||||||
341 | if (LookupCtx) { | ||||||
342 | // Perform "qualified" name lookup into the declaration context we | ||||||
343 | // computed, which is either the type of the base of a member access | ||||||
344 | // expression or the declaration context associated with a prior | ||||||
345 | // nested-name-specifier. | ||||||
346 | LookupQualifiedName(Result, LookupCtx); | ||||||
347 | |||||||
348 | if (ObjectTypePtr && Result.empty()) { | ||||||
349 | // C++ [basic.lookup.classref]p3: | ||||||
350 | // If the unqualified-id is ~type-name, the type-name is looked up | ||||||
351 | // in the context of the entire postfix-expression. If the type T of | ||||||
352 | // the object expression is of a class type C, the type-name is also | ||||||
353 | // looked up in the scope of class C. At least one of the lookups shall | ||||||
354 | // find a name that refers to (possibly cv-qualified) T. | ||||||
355 | LookupName(Result, S); | ||||||
356 | } | ||||||
357 | } else { | ||||||
358 | // Perform unqualified name lookup. | ||||||
359 | LookupName(Result, S); | ||||||
360 | |||||||
361 | // For unqualified lookup in a class template in MSVC mode, look into | ||||||
362 | // dependent base classes where the primary class template is known. | ||||||
363 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { | ||||||
364 | if (ParsedType TypeInBase = | ||||||
365 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) | ||||||
366 | return TypeInBase; | ||||||
367 | } | ||||||
368 | } | ||||||
369 | |||||||
370 | NamedDecl *IIDecl = nullptr; | ||||||
371 | switch (Result.getResultKind()) { | ||||||
372 | case LookupResult::NotFound: | ||||||
373 | case LookupResult::NotFoundInCurrentInstantiation: | ||||||
374 | if (CorrectedII) { | ||||||
375 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, | ||||||
376 | AllowDeducedTemplate); | ||||||
377 | TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, | ||||||
378 | S, SS, CCC, CTK_ErrorRecovery); | ||||||
379 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); | ||||||
380 | TemplateTy Template; | ||||||
381 | bool MemberOfUnknownSpecialization; | ||||||
382 | UnqualifiedId TemplateName; | ||||||
383 | TemplateName.setIdentifier(NewII, NameLoc); | ||||||
384 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); | ||||||
385 | CXXScopeSpec NewSS, *NewSSPtr = SS; | ||||||
386 | if (SS && NNS) { | ||||||
387 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
388 | NewSSPtr = &NewSS; | ||||||
389 | } | ||||||
390 | if (Correction && (NNS || NewII != &II) && | ||||||
391 | // Ignore a correction to a template type as the to-be-corrected | ||||||
392 | // identifier is not a template (typo correction for template names | ||||||
393 | // is handled elsewhere). | ||||||
394 | !(getLangOpts().CPlusPlus && NewSSPtr && | ||||||
395 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, | ||||||
396 | Template, MemberOfUnknownSpecialization))) { | ||||||
397 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, | ||||||
398 | isClassName, HasTrailingDot, ObjectTypePtr, | ||||||
399 | IsCtorOrDtorName, | ||||||
400 | WantNontrivialTypeSourceInfo, | ||||||
401 | IsClassTemplateDeductionContext); | ||||||
402 | if (Ty) { | ||||||
403 | diagnoseTypo(Correction, | ||||||
404 | PDiag(diag::err_unknown_type_or_class_name_suggest) | ||||||
405 | << Result.getLookupName() << isClassName); | ||||||
406 | if (SS && NNS) | ||||||
407 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
408 | *CorrectedII = NewII; | ||||||
409 | return Ty; | ||||||
410 | } | ||||||
411 | } | ||||||
412 | } | ||||||
413 | // If typo correction failed or was not performed, fall through | ||||||
414 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
415 | case LookupResult::FoundOverloaded: | ||||||
416 | case LookupResult::FoundUnresolvedValue: | ||||||
417 | Result.suppressDiagnostics(); | ||||||
418 | return nullptr; | ||||||
419 | |||||||
420 | case LookupResult::Ambiguous: | ||||||
421 | // Recover from type-hiding ambiguities by hiding the type. We'll | ||||||
422 | // do the lookup again when looking for an object, and we can | ||||||
423 | // diagnose the error then. If we don't do this, then the error | ||||||
424 | // about hiding the type will be immediately followed by an error | ||||||
425 | // that only makes sense if the identifier was treated like a type. | ||||||
426 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { | ||||||
427 | Result.suppressDiagnostics(); | ||||||
428 | return nullptr; | ||||||
429 | } | ||||||
430 | |||||||
431 | // Look to see if we have a type anywhere in the list of results. | ||||||
432 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); | ||||||
433 | Res != ResEnd; ++Res) { | ||||||
434 | if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || | ||||||
435 | (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { | ||||||
436 | if (!IIDecl || | ||||||
437 | (*Res)->getLocation().getRawEncoding() < | ||||||
438 | IIDecl->getLocation().getRawEncoding()) | ||||||
439 | IIDecl = *Res; | ||||||
440 | } | ||||||
441 | } | ||||||
442 | |||||||
443 | if (!IIDecl) { | ||||||
444 | // None of the entities we found is a type, so there is no way | ||||||
445 | // to even assume that the result is a type. In this case, don't | ||||||
446 | // complain about the ambiguity. The parser will either try to | ||||||
447 | // perform this lookup again (e.g., as an object name), which | ||||||
448 | // will produce the ambiguity, or will complain that it expected | ||||||
449 | // a type name. | ||||||
450 | Result.suppressDiagnostics(); | ||||||
451 | return nullptr; | ||||||
452 | } | ||||||
453 | |||||||
454 | // We found a type within the ambiguous lookup; diagnose the | ||||||
455 | // ambiguity and then return that type. This might be the right | ||||||
456 | // answer, or it might not be, but it suppresses any attempt to | ||||||
457 | // perform the name lookup again. | ||||||
458 | break; | ||||||
459 | |||||||
460 | case LookupResult::Found: | ||||||
461 | IIDecl = Result.getFoundDecl(); | ||||||
462 | break; | ||||||
463 | } | ||||||
464 | |||||||
465 | assert(IIDecl && "Didn't find decl")((IIDecl && "Didn't find decl") ? static_cast<void > (0) : __assert_fail ("IIDecl && \"Didn't find decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 465, __PRETTY_FUNCTION__)); | ||||||
466 | |||||||
467 | QualType T; | ||||||
468 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { | ||||||
469 | // C++ [class.qual]p2: A lookup that would find the injected-class-name | ||||||
470 | // instead names the constructors of the class, except when naming a class. | ||||||
471 | // This is ill-formed when we're not actually forming a ctor or dtor name. | ||||||
472 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); | ||||||
473 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); | ||||||
474 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && | ||||||
475 | FoundRD->isInjectedClassName() && | ||||||
476 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) | ||||||
477 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) | ||||||
478 | << &II << /*Type*/1; | ||||||
479 | |||||||
480 | DiagnoseUseOfDecl(IIDecl, NameLoc); | ||||||
481 | |||||||
482 | T = Context.getTypeDeclType(TD); | ||||||
483 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); | ||||||
484 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { | ||||||
485 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); | ||||||
486 | if (!HasTrailingDot) | ||||||
487 | T = Context.getObjCInterfaceType(IDecl); | ||||||
488 | } else if (AllowDeducedTemplate) { | ||||||
489 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) | ||||||
490 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), | ||||||
491 | QualType(), false); | ||||||
492 | } | ||||||
493 | |||||||
494 | if (T.isNull()) { | ||||||
495 | // If it's not plausibly a type, suppress diagnostics. | ||||||
496 | Result.suppressDiagnostics(); | ||||||
497 | return nullptr; | ||||||
498 | } | ||||||
499 | |||||||
500 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a | ||||||
501 | // constructor or destructor name (in such a case, the scope specifier | ||||||
502 | // will be attached to the enclosing Expr or Decl node). | ||||||
503 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && | ||||||
504 | !isa<ObjCInterfaceDecl>(IIDecl)) { | ||||||
505 | if (WantNontrivialTypeSourceInfo) { | ||||||
506 | // Construct a type with type-source information. | ||||||
507 | TypeLocBuilder Builder; | ||||||
508 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||||
509 | |||||||
510 | T = getElaboratedType(ETK_None, *SS, T); | ||||||
511 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||||
512 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
513 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); | ||||||
514 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
515 | } else { | ||||||
516 | T = getElaboratedType(ETK_None, *SS, T); | ||||||
517 | } | ||||||
518 | } | ||||||
519 | |||||||
520 | return ParsedType::make(T); | ||||||
521 | } | ||||||
522 | |||||||
523 | // Builds a fake NNS for the given decl context. | ||||||
524 | static NestedNameSpecifier * | ||||||
525 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { | ||||||
526 | for (;; DC = DC->getLookupParent()) { | ||||||
527 | DC = DC->getPrimaryContext(); | ||||||
528 | auto *ND = dyn_cast<NamespaceDecl>(DC); | ||||||
529 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) | ||||||
530 | return NestedNameSpecifier::Create(Context, nullptr, ND); | ||||||
531 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||||
532 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||||
533 | RD->getTypeForDecl()); | ||||||
534 | else if (isa<TranslationUnitDecl>(DC)) | ||||||
535 | return NestedNameSpecifier::GlobalSpecifier(Context); | ||||||
536 | } | ||||||
537 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 537); | ||||||
538 | } | ||||||
539 | |||||||
540 | /// Find the parent class with dependent bases of the innermost enclosing method | ||||||
541 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end | ||||||
542 | /// up allowing unqualified dependent type names at class-level, which MSVC | ||||||
543 | /// correctly rejects. | ||||||
544 | static const CXXRecordDecl * | ||||||
545 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { | ||||||
546 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { | ||||||
547 | DC = DC->getPrimaryContext(); | ||||||
548 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||||
549 | if (MD->getParent()->hasAnyDependentBases()) | ||||||
550 | return MD->getParent(); | ||||||
551 | } | ||||||
552 | return nullptr; | ||||||
553 | } | ||||||
554 | |||||||
555 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | ||||||
556 | SourceLocation NameLoc, | ||||||
557 | bool IsTemplateTypeArg) { | ||||||
558 | assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 558, __PRETTY_FUNCTION__)); | ||||||
559 | |||||||
560 | NestedNameSpecifier *NNS = nullptr; | ||||||
561 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { | ||||||
562 | // If we weren't able to parse a default template argument, delay lookup | ||||||
563 | // until instantiation time by making a non-dependent DependentTypeName. We | ||||||
564 | // pretend we saw a NestedNameSpecifier referring to the current scope, and | ||||||
565 | // lookup is retried. | ||||||
566 | // FIXME: This hurts our diagnostic quality, since we get errors like "no | ||||||
567 | // type named 'Foo' in 'current_namespace'" when the user didn't write any | ||||||
568 | // name specifiers. | ||||||
569 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); | ||||||
570 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; | ||||||
571 | } else if (const CXXRecordDecl *RD = | ||||||
572 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { | ||||||
573 | // Build a DependentNameType that will perform lookup into RD at | ||||||
574 | // instantiation time. | ||||||
575 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||||
576 | RD->getTypeForDecl()); | ||||||
577 | |||||||
578 | // Diagnose that this identifier was undeclared, and retry the lookup during | ||||||
579 | // template instantiation. | ||||||
580 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II | ||||||
581 | << RD; | ||||||
582 | } else { | ||||||
583 | // This is not a situation that we should recover from. | ||||||
584 | return ParsedType(); | ||||||
585 | } | ||||||
586 | |||||||
587 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); | ||||||
588 | |||||||
589 | // Build type location information. We synthesized the qualifier, so we have | ||||||
590 | // to build a fake NestedNameSpecifierLoc. | ||||||
591 | NestedNameSpecifierLocBuilder NNSLocBuilder; | ||||||
592 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
593 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); | ||||||
594 | |||||||
595 | TypeLocBuilder Builder; | ||||||
596 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||||
597 | DepTL.setNameLoc(NameLoc); | ||||||
598 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
599 | DepTL.setQualifierLoc(QualifierLoc); | ||||||
600 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
601 | } | ||||||
602 | |||||||
603 | /// isTagName() - This method is called *for error recovery purposes only* | ||||||
604 | /// to determine if the specified name is a valid tag name ("struct foo"). If | ||||||
605 | /// so, this returns the TST for the tag corresponding to it (TST_enum, | ||||||
606 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose | ||||||
607 | /// cases in C where the user forgot to specify the tag. | ||||||
608 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { | ||||||
609 | // Do a tag name lookup in this scope. | ||||||
610 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); | ||||||
611 | LookupName(R, S, false); | ||||||
612 | R.suppressDiagnostics(); | ||||||
613 | if (R.getResultKind() == LookupResult::Found) | ||||||
614 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { | ||||||
615 | switch (TD->getTagKind()) { | ||||||
616 | case TTK_Struct: return DeclSpec::TST_struct; | ||||||
617 | case TTK_Interface: return DeclSpec::TST_interface; | ||||||
618 | case TTK_Union: return DeclSpec::TST_union; | ||||||
619 | case TTK_Class: return DeclSpec::TST_class; | ||||||
620 | case TTK_Enum: return DeclSpec::TST_enum; | ||||||
621 | } | ||||||
622 | } | ||||||
623 | |||||||
624 | return DeclSpec::TST_unspecified; | ||||||
625 | } | ||||||
626 | |||||||
627 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, | ||||||
628 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes | ||||||
629 | /// then downgrade the missing typename error to a warning. | ||||||
630 | /// This is needed for MSVC compatibility; Example: | ||||||
631 | /// @code | ||||||
632 | /// template<class T> class A { | ||||||
633 | /// public: | ||||||
634 | /// typedef int TYPE; | ||||||
635 | /// }; | ||||||
636 | /// template<class T> class B : public A<T> { | ||||||
637 | /// public: | ||||||
638 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. | ||||||
639 | /// }; | ||||||
640 | /// @endcode | ||||||
641 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { | ||||||
642 | if (CurContext->isRecord()) { | ||||||
643 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) | ||||||
644 | return true; | ||||||
645 | |||||||
646 | const Type *Ty = SS->getScopeRep()->getAsType(); | ||||||
647 | |||||||
648 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); | ||||||
649 | for (const auto &Base : RD->bases()) | ||||||
650 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) | ||||||
651 | return true; | ||||||
652 | return S->isFunctionPrototypeScope(); | ||||||
653 | } | ||||||
654 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); | ||||||
655 | } | ||||||
656 | |||||||
657 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, | ||||||
658 | SourceLocation IILoc, | ||||||
659 | Scope *S, | ||||||
660 | CXXScopeSpec *SS, | ||||||
661 | ParsedType &SuggestedType, | ||||||
662 | bool IsTemplateName) { | ||||||
663 | // Don't report typename errors for editor placeholders. | ||||||
664 | if (II->isEditorPlaceholder()) | ||||||
665 | return; | ||||||
666 | // We don't have anything to suggest (yet). | ||||||
667 | SuggestedType = nullptr; | ||||||
668 | |||||||
669 | // There may have been a typo in the name of the type. Look up typo | ||||||
670 | // results, in case we have something that we can suggest. | ||||||
671 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, | ||||||
672 | /*AllowTemplates=*/IsTemplateName, | ||||||
673 | /*AllowNonTemplates=*/!IsTemplateName); | ||||||
674 | if (TypoCorrection Corrected = | ||||||
675 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, | ||||||
676 | CCC, CTK_ErrorRecovery)) { | ||||||
677 | // FIXME: Support error recovery for the template-name case. | ||||||
678 | bool CanRecover = !IsTemplateName; | ||||||
679 | if (Corrected.isKeyword()) { | ||||||
680 | // We corrected to a keyword. | ||||||
681 | diagnoseTypo(Corrected, | ||||||
682 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||||
683 | : diag::err_unknown_typename_suggest) | ||||||
684 | << II); | ||||||
685 | II = Corrected.getCorrectionAsIdentifierInfo(); | ||||||
686 | } else { | ||||||
687 | // We found a similarly-named type or interface; suggest that. | ||||||
688 | if (!SS || !SS->isSet()) { | ||||||
689 | diagnoseTypo(Corrected, | ||||||
690 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||||
691 | : diag::err_unknown_typename_suggest) | ||||||
692 | << II, CanRecover); | ||||||
693 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { | ||||||
694 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||
695 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||||
696 | II->getName().equals(CorrectedStr); | ||||||
697 | diagnoseTypo(Corrected, | ||||||
698 | PDiag(IsTemplateName | ||||||
699 | ? diag::err_no_member_template_suggest | ||||||
700 | : diag::err_unknown_nested_typename_suggest) | ||||||
701 | << II << DC << DroppedSpecifier << SS->getRange(), | ||||||
702 | CanRecover); | ||||||
703 | } else { | ||||||
704 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 704); | ||||||
705 | } | ||||||
706 | |||||||
707 | if (!CanRecover) | ||||||
708 | return; | ||||||
709 | |||||||
710 | CXXScopeSpec tmpSS; | ||||||
711 | if (Corrected.getCorrectionSpecifier()) | ||||||
712 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | ||||||
713 | SourceRange(IILoc)); | ||||||
714 | // FIXME: Support class template argument deduction here. | ||||||
715 | SuggestedType = | ||||||
716 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, | ||||||
717 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, | ||||||
718 | /*IsCtorOrDtorName=*/false, | ||||||
719 | /*WantNontrivialTypeSourceInfo=*/true); | ||||||
720 | } | ||||||
721 | return; | ||||||
722 | } | ||||||
723 | |||||||
724 | if (getLangOpts().CPlusPlus && !IsTemplateName) { | ||||||
725 | // See if II is a class template that the user forgot to pass arguments to. | ||||||
726 | UnqualifiedId Name; | ||||||
727 | Name.setIdentifier(II, IILoc); | ||||||
728 | CXXScopeSpec EmptySS; | ||||||
729 | TemplateTy TemplateResult; | ||||||
730 | bool MemberOfUnknownSpecialization; | ||||||
731 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, | ||||||
732 | Name, nullptr, true, TemplateResult, | ||||||
733 | MemberOfUnknownSpecialization) == TNK_Type_template) { | ||||||
734 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); | ||||||
735 | return; | ||||||
736 | } | ||||||
737 | } | ||||||
738 | |||||||
739 | // FIXME: Should we move the logic that tries to recover from a missing tag | ||||||
740 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? | ||||||
741 | |||||||
742 | if (!SS || (!SS->isSet() && !SS->isInvalid())) | ||||||
743 | Diag(IILoc, IsTemplateName ? diag::err_no_template | ||||||
744 | : diag::err_unknown_typename) | ||||||
745 | << II; | ||||||
746 | else if (DeclContext *DC = computeDeclContext(*SS, false)) | ||||||
747 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template | ||||||
748 | : diag::err_typename_nested_not_found) | ||||||
749 | << II << DC << SS->getRange(); | ||||||
750 | else if (isDependentScopeSpecifier(*SS)) { | ||||||
751 | unsigned DiagID = diag::err_typename_missing; | ||||||
752 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) | ||||||
753 | DiagID = diag::ext_typename_missing; | ||||||
754 | |||||||
755 | Diag(SS->getRange().getBegin(), DiagID) | ||||||
756 | << SS->getScopeRep() << II->getName() | ||||||
757 | << SourceRange(SS->getRange().getBegin(), IILoc) | ||||||
758 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); | ||||||
759 | SuggestedType = ActOnTypenameType(S, SourceLocation(), | ||||||
760 | *SS, *II, IILoc).get(); | ||||||
761 | } else { | ||||||
762 | assert(SS && SS->isInvalid() &&((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 763, __PRETTY_FUNCTION__)) | ||||||
763 | "Invalid scope specifier has already been diagnosed")((SS && SS->isInvalid() && "Invalid scope specifier has already been diagnosed" ) ? static_cast<void> (0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 763, __PRETTY_FUNCTION__)); | ||||||
764 | } | ||||||
765 | } | ||||||
766 | |||||||
767 | /// Determine whether the given result set contains either a type name | ||||||
768 | /// or | ||||||
769 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { | ||||||
770 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && | ||||||
771 | NextToken.is(tok::less); | ||||||
772 | |||||||
773 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { | ||||||
774 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) | ||||||
775 | return true; | ||||||
776 | |||||||
777 | if (CheckTemplate && isa<TemplateDecl>(*I)) | ||||||
778 | return true; | ||||||
779 | } | ||||||
780 | |||||||
781 | return false; | ||||||
782 | } | ||||||
783 | |||||||
784 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, | ||||||
785 | Scope *S, CXXScopeSpec &SS, | ||||||
786 | IdentifierInfo *&Name, | ||||||
787 | SourceLocation NameLoc) { | ||||||
788 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); | ||||||
789 | SemaRef.LookupParsedName(R, S, &SS); | ||||||
790 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { | ||||||
791 | StringRef FixItTagName; | ||||||
792 | switch (Tag->getTagKind()) { | ||||||
793 | case TTK_Class: | ||||||
794 | FixItTagName = "class "; | ||||||
795 | break; | ||||||
796 | |||||||
797 | case TTK_Enum: | ||||||
798 | FixItTagName = "enum "; | ||||||
799 | break; | ||||||
800 | |||||||
801 | case TTK_Struct: | ||||||
802 | FixItTagName = "struct "; | ||||||
803 | break; | ||||||
804 | |||||||
805 | case TTK_Interface: | ||||||
806 | FixItTagName = "__interface "; | ||||||
807 | break; | ||||||
808 | |||||||
809 | case TTK_Union: | ||||||
810 | FixItTagName = "union "; | ||||||
811 | break; | ||||||
812 | } | ||||||
813 | |||||||
814 | StringRef TagName = FixItTagName.drop_back(); | ||||||
815 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) | ||||||
816 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus | ||||||
817 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); | ||||||
818 | |||||||
819 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); | ||||||
820 | I != IEnd; ++I) | ||||||
821 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) | ||||||
822 | << Name << TagName; | ||||||
823 | |||||||
824 | // Replace lookup results with just the tag decl. | ||||||
825 | Result.clear(Sema::LookupTagName); | ||||||
826 | SemaRef.LookupParsedName(Result, S, &SS); | ||||||
827 | return true; | ||||||
828 | } | ||||||
829 | |||||||
830 | return false; | ||||||
831 | } | ||||||
832 | |||||||
833 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. | ||||||
834 | static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, | ||||||
835 | QualType T, SourceLocation NameLoc) { | ||||||
836 | ASTContext &Context = S.Context; | ||||||
837 | |||||||
838 | TypeLocBuilder Builder; | ||||||
839 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||||
840 | |||||||
841 | T = S.getElaboratedType(ETK_None, SS, T); | ||||||
842 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||||
843 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
844 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||
845 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
846 | } | ||||||
847 | |||||||
848 | Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, | ||||||
849 | IdentifierInfo *&Name, | ||||||
850 | SourceLocation NameLoc, | ||||||
851 | const Token &NextToken, | ||||||
852 | CorrectionCandidateCallback *CCC) { | ||||||
853 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||||
854 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||
855 | |||||||
856 | assert(NextToken.isNot(tok::coloncolon) &&((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName" ) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 857, __PRETTY_FUNCTION__)) | ||||||
857 | "parse nested name specifiers before calling ClassifyName")((NextToken.isNot(tok::coloncolon) && "parse nested name specifiers before calling ClassifyName" ) ? static_cast<void> (0) : __assert_fail ("NextToken.isNot(tok::coloncolon) && \"parse nested name specifiers before calling ClassifyName\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 857, __PRETTY_FUNCTION__)); | ||||||
858 | if (getLangOpts().CPlusPlus && SS.isSet() && | ||||||
859 | isCurrentClassName(*Name, S, &SS)) { | ||||||
860 | // Per [class.qual]p2, this names the constructors of SS, not the | ||||||
861 | // injected-class-name. We don't have a classification for that. | ||||||
862 | // There's not much point caching this result, since the parser | ||||||
863 | // will reject it later. | ||||||
864 | return NameClassification::Unknown(); | ||||||
865 | } | ||||||
866 | |||||||
867 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||||
868 | LookupParsedName(Result, S, &SS, !CurMethod); | ||||||
869 | |||||||
870 | if (SS.isInvalid()) | ||||||
871 | return NameClassification::Error(); | ||||||
872 | |||||||
873 | // For unqualified lookup in a class template in MSVC mode, look into | ||||||
874 | // dependent base classes where the primary class template is known. | ||||||
875 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||||
876 | if (ParsedType TypeInBase = | ||||||
877 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) | ||||||
878 | return TypeInBase; | ||||||
879 | } | ||||||
880 | |||||||
881 | // Perform lookup for Objective-C instance variables (including automatically | ||||||
882 | // synthesized instance variables), if we're in an Objective-C method. | ||||||
883 | // FIXME: This lookup really, really needs to be folded in to the normal | ||||||
884 | // unqualified lookup mechanism. | ||||||
885 | if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { | ||||||
886 | DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); | ||||||
887 | if (Ivar.isInvalid()) | ||||||
888 | return NameClassification::Error(); | ||||||
889 | if (Ivar.isUsable()) | ||||||
890 | return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); | ||||||
891 | |||||||
892 | // We defer builtin creation until after ivar lookup inside ObjC methods. | ||||||
893 | if (Result.empty()) | ||||||
894 | LookupBuiltin(Result); | ||||||
895 | } | ||||||
896 | |||||||
897 | bool SecondTry = false; | ||||||
898 | bool IsFilteredTemplateName = false; | ||||||
899 | |||||||
900 | Corrected: | ||||||
901 | switch (Result.getResultKind()) { | ||||||
902 | case LookupResult::NotFound: | ||||||
903 | // If an unqualified-id is followed by a '(', then we have a function | ||||||
904 | // call. | ||||||
905 | if (SS.isEmpty() && NextToken.is(tok::l_paren)) { | ||||||
906 | // In C++, this is an ADL-only call. | ||||||
907 | // FIXME: Reference? | ||||||
908 | if (getLangOpts().CPlusPlus) | ||||||
909 | return NameClassification::UndeclaredNonType(); | ||||||
910 | |||||||
911 | // C90 6.3.2.2: | ||||||
912 | // If the expression that precedes the parenthesized argument list in a | ||||||
913 | // function call consists solely of an identifier, and if no | ||||||
914 | // declaration is visible for this identifier, the identifier is | ||||||
915 | // implicitly declared exactly as if, in the innermost block containing | ||||||
916 | // the function call, the declaration | ||||||
917 | // | ||||||
918 | // extern int identifier (); | ||||||
919 | // | ||||||
920 | // appeared. | ||||||
921 | // | ||||||
922 | // We also allow this in C99 as an extension. | ||||||
923 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) | ||||||
924 | return NameClassification::NonType(D); | ||||||
925 | } | ||||||
926 | |||||||
927 | if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) { | ||||||
928 | // In C++20 onwards, this could be an ADL-only call to a function | ||||||
929 | // template, and we're required to assume that this is a template name. | ||||||
930 | // | ||||||
931 | // FIXME: Find a way to still do typo correction in this case. | ||||||
932 | TemplateName Template = | ||||||
933 | Context.getAssumedTemplateName(NameInfo.getName()); | ||||||
934 | return NameClassification::UndeclaredTemplate(Template); | ||||||
935 | } | ||||||
936 | |||||||
937 | // In C, we first see whether there is a tag type by the same name, in | ||||||
938 | // which case it's likely that the user just forgot to write "enum", | ||||||
939 | // "struct", or "union". | ||||||
940 | if (!getLangOpts().CPlusPlus && !SecondTry && | ||||||
941 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||||
942 | break; | ||||||
943 | } | ||||||
944 | |||||||
945 | // Perform typo correction to determine if there is another name that is | ||||||
946 | // close to this name. | ||||||
947 | if (!SecondTry && CCC) { | ||||||
948 | SecondTry = true; | ||||||
949 | if (TypoCorrection Corrected = | ||||||
950 | CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, | ||||||
951 | &SS, *CCC, CTK_ErrorRecovery)) { | ||||||
952 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; | ||||||
953 | unsigned QualifiedDiag = diag::err_no_member_suggest; | ||||||
954 | |||||||
955 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); | ||||||
956 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); | ||||||
957 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
958 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { | ||||||
959 | UnqualifiedDiag = diag::err_no_template_suggest; | ||||||
960 | QualifiedDiag = diag::err_no_member_template_suggest; | ||||||
961 | } else if (UnderlyingFirstDecl && | ||||||
962 | (isa<TypeDecl>(UnderlyingFirstDecl) || | ||||||
963 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || | ||||||
964 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { | ||||||
965 | UnqualifiedDiag = diag::err_unknown_typename_suggest; | ||||||
966 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; | ||||||
967 | } | ||||||
968 | |||||||
969 | if (SS.isEmpty()) { | ||||||
970 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); | ||||||
971 | } else {// FIXME: is this even reachable? Test it. | ||||||
972 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||
973 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||||
974 | Name->getName().equals(CorrectedStr); | ||||||
975 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) | ||||||
976 | << Name << computeDeclContext(SS, false) | ||||||
977 | << DroppedSpecifier << SS.getRange()); | ||||||
978 | } | ||||||
979 | |||||||
980 | // Update the name, so that the caller has the new name. | ||||||
981 | Name = Corrected.getCorrectionAsIdentifierInfo(); | ||||||
982 | |||||||
983 | // Typo correction corrected to a keyword. | ||||||
984 | if (Corrected.isKeyword()) | ||||||
985 | return Name; | ||||||
986 | |||||||
987 | // Also update the LookupResult... | ||||||
988 | // FIXME: This should probably go away at some point | ||||||
989 | Result.clear(); | ||||||
990 | Result.setLookupName(Corrected.getCorrection()); | ||||||
991 | if (FirstDecl) | ||||||
992 | Result.addDecl(FirstDecl); | ||||||
993 | |||||||
994 | // If we found an Objective-C instance variable, let | ||||||
995 | // LookupInObjCMethod build the appropriate expression to | ||||||
996 | // reference the ivar. | ||||||
997 | // FIXME: This is a gross hack. | ||||||
998 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { | ||||||
999 | DeclResult R = | ||||||
1000 | LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); | ||||||
1001 | if (R.isInvalid()) | ||||||
1002 | return NameClassification::Error(); | ||||||
1003 | if (R.isUsable()) | ||||||
1004 | return NameClassification::NonType(Ivar); | ||||||
1005 | } | ||||||
1006 | |||||||
1007 | goto Corrected; | ||||||
1008 | } | ||||||
1009 | } | ||||||
1010 | |||||||
1011 | // We failed to correct; just fall through and let the parser deal with it. | ||||||
1012 | Result.suppressDiagnostics(); | ||||||
1013 | return NameClassification::Unknown(); | ||||||
1014 | |||||||
1015 | case LookupResult::NotFoundInCurrentInstantiation: { | ||||||
1016 | // We performed name lookup into the current instantiation, and there were | ||||||
1017 | // dependent bases, so we treat this result the same way as any other | ||||||
1018 | // dependent nested-name-specifier. | ||||||
1019 | |||||||
1020 | // C++ [temp.res]p2: | ||||||
1021 | // A name used in a template declaration or definition and that is | ||||||
1022 | // dependent on a template-parameter is assumed not to name a type | ||||||
1023 | // unless the applicable name lookup finds a type name or the name is | ||||||
1024 | // qualified by the keyword typename. | ||||||
1025 | // | ||||||
1026 | // FIXME: If the next token is '<', we might want to ask the parser to | ||||||
1027 | // perform some heroics to see if we actually have a | ||||||
1028 | // template-argument-list, which would indicate a missing 'template' | ||||||
1029 | // keyword here. | ||||||
1030 | return NameClassification::DependentNonType(); | ||||||
1031 | } | ||||||
1032 | |||||||
1033 | case LookupResult::Found: | ||||||
1034 | case LookupResult::FoundOverloaded: | ||||||
1035 | case LookupResult::FoundUnresolvedValue: | ||||||
1036 | break; | ||||||
1037 | |||||||
1038 | case LookupResult::Ambiguous: | ||||||
1039 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
1040 | hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, | ||||||
1041 | /*AllowDependent=*/false)) { | ||||||
1042 | // C++ [temp.local]p3: | ||||||
1043 | // A lookup that finds an injected-class-name (10.2) can result in an | ||||||
1044 | // ambiguity in certain cases (for example, if it is found in more than | ||||||
1045 | // one base class). If all of the injected-class-names that are found | ||||||
1046 | // refer to specializations of the same class template, and if the name | ||||||
1047 | // is followed by a template-argument-list, the reference refers to the | ||||||
1048 | // class template itself and not a specialization thereof, and is not | ||||||
1049 | // ambiguous. | ||||||
1050 | // | ||||||
1051 | // This filtering can make an ambiguous result into an unambiguous one, | ||||||
1052 | // so try again after filtering out template names. | ||||||
1053 | FilterAcceptableTemplateNames(Result); | ||||||
1054 | if (!Result.isAmbiguous()) { | ||||||
1055 | IsFilteredTemplateName = true; | ||||||
1056 | break; | ||||||
1057 | } | ||||||
1058 | } | ||||||
1059 | |||||||
1060 | // Diagnose the ambiguity and return an error. | ||||||
1061 | return NameClassification::Error(); | ||||||
1062 | } | ||||||
1063 | |||||||
1064 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
1065 | (IsFilteredTemplateName || | ||||||
1066 | hasAnyAcceptableTemplateNames( | ||||||
1067 | Result, /*AllowFunctionTemplates=*/true, | ||||||
1068 | /*AllowDependent=*/false, | ||||||
1069 | /*AllowNonTemplateFunctions*/ SS.isEmpty() && | ||||||
1070 | getLangOpts().CPlusPlus2a))) { | ||||||
1071 | // C++ [temp.names]p3: | ||||||
1072 | // After name lookup (3.4) finds that a name is a template-name or that | ||||||
1073 | // an operator-function-id or a literal- operator-id refers to a set of | ||||||
1074 | // overloaded functions any member of which is a function template if | ||||||
1075 | // this is followed by a <, the < is always taken as the delimiter of a | ||||||
1076 | // template-argument-list and never as the less-than operator. | ||||||
1077 | // C++2a [temp.names]p2: | ||||||
1078 | // A name is also considered to refer to a template if it is an | ||||||
1079 | // unqualified-id followed by a < and name lookup finds either one | ||||||
1080 | // or more functions or finds nothing. | ||||||
1081 | if (!IsFilteredTemplateName) | ||||||
1082 | FilterAcceptableTemplateNames(Result); | ||||||
1083 | |||||||
1084 | bool IsFunctionTemplate; | ||||||
1085 | bool IsVarTemplate; | ||||||
1086 | TemplateName Template; | ||||||
1087 | if (Result.end() - Result.begin() > 1) { | ||||||
1088 | IsFunctionTemplate = true; | ||||||
1089 | Template = Context.getOverloadedTemplateName(Result.begin(), | ||||||
1090 | Result.end()); | ||||||
1091 | } else if (!Result.empty()) { | ||||||
1092 | auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( | ||||||
1093 | *Result.begin(), /*AllowFunctionTemplates=*/true, | ||||||
1094 | /*AllowDependent=*/false)); | ||||||
1095 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); | ||||||
1096 | IsVarTemplate = isa<VarTemplateDecl>(TD); | ||||||
1097 | |||||||
1098 | if (SS.isNotEmpty()) | ||||||
1099 | Template = | ||||||
1100 | Context.getQualifiedTemplateName(SS.getScopeRep(), | ||||||
1101 | /*TemplateKeyword=*/false, TD); | ||||||
1102 | else | ||||||
1103 | Template = TemplateName(TD); | ||||||
1104 | } else { | ||||||
1105 | // All results were non-template functions. This is a function template | ||||||
1106 | // name. | ||||||
1107 | IsFunctionTemplate = true; | ||||||
1108 | Template = Context.getAssumedTemplateName(NameInfo.getName()); | ||||||
1109 | } | ||||||
1110 | |||||||
1111 | if (IsFunctionTemplate) { | ||||||
1112 | // Function templates always go through overload resolution, at which | ||||||
1113 | // point we'll perform the various checks (e.g., accessibility) we need | ||||||
1114 | // to based on which function we selected. | ||||||
1115 | Result.suppressDiagnostics(); | ||||||
1116 | |||||||
1117 | return NameClassification::FunctionTemplate(Template); | ||||||
1118 | } | ||||||
1119 | |||||||
1120 | return IsVarTemplate ? NameClassification::VarTemplate(Template) | ||||||
1121 | : NameClassification::TypeTemplate(Template); | ||||||
1122 | } | ||||||
1123 | |||||||
1124 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); | ||||||
1125 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { | ||||||
1126 | DiagnoseUseOfDecl(Type, NameLoc); | ||||||
1127 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | ||||||
1128 | QualType T = Context.getTypeDeclType(Type); | ||||||
1129 | if (SS.isNotEmpty()) | ||||||
1130 | return buildNestedType(*this, SS, T, NameLoc); | ||||||
1131 | return ParsedType::make(T); | ||||||
1132 | } | ||||||
1133 | |||||||
1134 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); | ||||||
1135 | if (!Class) { | ||||||
1136 | // FIXME: It's unfortunate that we don't have a Type node for handling this. | ||||||
1137 | if (ObjCCompatibleAliasDecl *Alias = | ||||||
1138 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) | ||||||
1139 | Class = Alias->getClassInterface(); | ||||||
1140 | } | ||||||
1141 | |||||||
1142 | if (Class) { | ||||||
1143 | DiagnoseUseOfDecl(Class, NameLoc); | ||||||
1144 | |||||||
1145 | if (NextToken.is(tok::period)) { | ||||||
1146 | // Interface. <something> is parsed as a property reference expression. | ||||||
1147 | // Just return "unknown" as a fall-through for now. | ||||||
1148 | Result.suppressDiagnostics(); | ||||||
1149 | return NameClassification::Unknown(); | ||||||
1150 | } | ||||||
1151 | |||||||
1152 | QualType T = Context.getObjCInterfaceType(Class); | ||||||
1153 | return ParsedType::make(T); | ||||||
1154 | } | ||||||
1155 | |||||||
1156 | // We can have a type template here if we're classifying a template argument. | ||||||
1157 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && | ||||||
1158 | !isa<VarTemplateDecl>(FirstDecl)) | ||||||
1159 | return NameClassification::TypeTemplate( | ||||||
1160 | TemplateName(cast<TemplateDecl>(FirstDecl))); | ||||||
1161 | |||||||
1162 | // Check for a tag type hidden by a non-type decl in a few cases where it | ||||||
1163 | // seems likely a type is wanted instead of the non-type that was found. | ||||||
1164 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); | ||||||
1165 | if ((NextToken.is(tok::identifier) || | ||||||
1166 | (NextIsOp && | ||||||
1167 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && | ||||||
1168 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||||
1169 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); | ||||||
1170 | DiagnoseUseOfDecl(Type, NameLoc); | ||||||
1171 | QualType T = Context.getTypeDeclType(Type); | ||||||
1172 | if (SS.isNotEmpty()) | ||||||
1173 | return buildNestedType(*this, SS, T, NameLoc); | ||||||
1174 | return ParsedType::make(T); | ||||||
1175 | } | ||||||
1176 | |||||||
1177 | // FIXME: This is context-dependent. We need to defer building the member | ||||||
1178 | // expression until the classification is consumed. | ||||||
1179 | if (FirstDecl->isCXXClassMember()) | ||||||
1180 | return NameClassification::ContextIndependentExpr( | ||||||
1181 | BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, | ||||||
1182 | S)); | ||||||
1183 | |||||||
1184 | // If we already know which single declaration is referenced, just annotate | ||||||
1185 | // that declaration directly. | ||||||
1186 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||||
1187 | if (Result.isSingleResult() && !ADL) | ||||||
1188 | return NameClassification::NonType(Result.getRepresentativeDecl()); | ||||||
1189 | |||||||
1190 | // Build an UnresolvedLookupExpr. Note that this doesn't depend on the | ||||||
1191 | // context in which we performed classification, so it's safe to do now. | ||||||
1192 | return NameClassification::ContextIndependentExpr( | ||||||
1193 | BuildDeclarationNameExpr(SS, Result, ADL)); | ||||||
1194 | } | ||||||
1195 | |||||||
1196 | ExprResult | ||||||
1197 | Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, | ||||||
1198 | SourceLocation NameLoc) { | ||||||
1199 | assert(getLangOpts().CPlusPlus && "ADL-only call in C?")((getLangOpts().CPlusPlus && "ADL-only call in C?") ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"ADL-only call in C?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1199, __PRETTY_FUNCTION__)); | ||||||
1200 | CXXScopeSpec SS; | ||||||
1201 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||||
1202 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); | ||||||
1203 | } | ||||||
1204 | |||||||
1205 | ExprResult | ||||||
1206 | Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, | ||||||
1207 | IdentifierInfo *Name, | ||||||
1208 | SourceLocation NameLoc, | ||||||
1209 | bool IsAddressOfOperand) { | ||||||
1210 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||||
1211 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||
1212 | NameInfo, IsAddressOfOperand, | ||||||
1213 | /*TemplateArgs=*/nullptr); | ||||||
1214 | } | ||||||
1215 | |||||||
1216 | ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, | ||||||
1217 | NamedDecl *Found, | ||||||
1218 | SourceLocation NameLoc, | ||||||
1219 | const Token &NextToken) { | ||||||
1220 | if (getCurMethodDecl() && SS.isEmpty()) | ||||||
1221 | if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) | ||||||
1222 | return BuildIvarRefExpr(S, NameLoc, Ivar); | ||||||
1223 | |||||||
1224 | // Reconstruct the lookup result. | ||||||
1225 | LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); | ||||||
1226 | Result.addDecl(Found); | ||||||
1227 | Result.resolveKind(); | ||||||
1228 | |||||||
1229 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||||
1230 | return BuildDeclarationNameExpr(SS, Result, ADL); | ||||||
1231 | } | ||||||
1232 | |||||||
1233 | Sema::TemplateNameKindForDiagnostics | ||||||
1234 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { | ||||||
1235 | auto *TD = Name.getAsTemplateDecl(); | ||||||
1236 | if (!TD) | ||||||
1237 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||||
1238 | if (isa<ClassTemplateDecl>(TD)) | ||||||
1239 | return TemplateNameKindForDiagnostics::ClassTemplate; | ||||||
1240 | if (isa<FunctionTemplateDecl>(TD)) | ||||||
1241 | return TemplateNameKindForDiagnostics::FunctionTemplate; | ||||||
1242 | if (isa<VarTemplateDecl>(TD)) | ||||||
1243 | return TemplateNameKindForDiagnostics::VarTemplate; | ||||||
1244 | if (isa<TypeAliasTemplateDecl>(TD)) | ||||||
1245 | return TemplateNameKindForDiagnostics::AliasTemplate; | ||||||
1246 | if (isa<TemplateTemplateParmDecl>(TD)) | ||||||
1247 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; | ||||||
1248 | if (isa<ConceptDecl>(TD)) | ||||||
1249 | return TemplateNameKindForDiagnostics::Concept; | ||||||
1250 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||||
1251 | } | ||||||
1252 | |||||||
1253 | // Determines the context to return to after temporarily entering a | ||||||
1254 | // context. This depends in an unnecessarily complicated way on the | ||||||
1255 | // exact ordering of callbacks from the parser. | ||||||
1256 | DeclContext *Sema::getContainingDC(DeclContext *DC) { | ||||||
1257 | |||||||
1258 | // Functions defined inline within classes aren't parsed until we've | ||||||
1259 | // finished parsing the top-level class, so the top-level class is | ||||||
1260 | // the context we'll need to return to. | ||||||
1261 | // A Lambda call operator whose parent is a class must not be treated | ||||||
1262 | // as an inline member function. A Lambda can be used legally | ||||||
1263 | // either as an in-class member initializer or a default argument. These | ||||||
1264 | // are parsed once the class has been marked complete and so the containing | ||||||
1265 | // context would be the nested class (when the lambda is defined in one); | ||||||
1266 | // If the class is not complete, then the lambda is being used in an | ||||||
1267 | // ill-formed fashion (such as to specify the width of a bit-field, or | ||||||
1268 | // in an array-bound) - in which case we still want to return the | ||||||
1269 | // lexically containing DC (which could be a nested class). | ||||||
1270 | if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { | ||||||
1271 | DC = DC->getLexicalParent(); | ||||||
1272 | |||||||
1273 | // A function not defined within a class will always return to its | ||||||
1274 | // lexical context. | ||||||
1275 | if (!isa<CXXRecordDecl>(DC)) | ||||||
1276 | return DC; | ||||||
1277 | |||||||
1278 | // A C++ inline method/friend is parsed *after* the topmost class | ||||||
1279 | // it was declared in is fully parsed ("complete"); the topmost | ||||||
1280 | // class is the context we need to return to. | ||||||
1281 | while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) | ||||||
1282 | DC = RD; | ||||||
1283 | |||||||
1284 | // Return the declaration context of the topmost class the inline method is | ||||||
1285 | // declared in. | ||||||
1286 | return DC; | ||||||
1287 | } | ||||||
1288 | |||||||
1289 | return DC->getLexicalParent(); | ||||||
1290 | } | ||||||
1291 | |||||||
1292 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { | ||||||
1293 | assert(getContainingDC(DC) == CurContext &&((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1294, __PRETTY_FUNCTION__)) | ||||||
1294 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(DC) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1294, __PRETTY_FUNCTION__)); | ||||||
1295 | CurContext = DC; | ||||||
1296 | S->setEntity(DC); | ||||||
1297 | } | ||||||
1298 | |||||||
1299 | void Sema::PopDeclContext() { | ||||||
1300 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1300, __PRETTY_FUNCTION__)); | ||||||
1301 | |||||||
1302 | CurContext = getContainingDC(CurContext); | ||||||
1303 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1303, __PRETTY_FUNCTION__)); | ||||||
1304 | } | ||||||
1305 | |||||||
1306 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, | ||||||
1307 | Decl *D) { | ||||||
1308 | // Unlike PushDeclContext, the context to which we return is not necessarily | ||||||
1309 | // the containing DC of TD, because the new context will be some pre-existing | ||||||
1310 | // TagDecl definition instead of a fresh one. | ||||||
1311 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); | ||||||
1312 | CurContext = cast<TagDecl>(D)->getDefinition(); | ||||||
1313 | assert(CurContext && "skipping definition of undefined tag")((CurContext && "skipping definition of undefined tag" ) ? static_cast<void> (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1313, __PRETTY_FUNCTION__)); | ||||||
1314 | // Start lookups from the parent of the current context; we don't want to look | ||||||
1315 | // into the pre-existing complete definition. | ||||||
1316 | S->setEntity(CurContext->getLookupParent()); | ||||||
1317 | return Result; | ||||||
1318 | } | ||||||
1319 | |||||||
1320 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { | ||||||
1321 | CurContext = static_cast<decltype(CurContext)>(Context); | ||||||
1322 | } | ||||||
1323 | |||||||
1324 | /// EnterDeclaratorContext - Used when we must lookup names in the context | ||||||
1325 | /// of a declarator's nested name specifier. | ||||||
1326 | /// | ||||||
1327 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { | ||||||
1328 | // C++0x [basic.lookup.unqual]p13: | ||||||
1329 | // A name used in the definition of a static data member of class | ||||||
1330 | // X (after the qualified-id of the static member) is looked up as | ||||||
1331 | // if the name was used in a member function of X. | ||||||
1332 | // C++0x [basic.lookup.unqual]p14: | ||||||
1333 | // If a variable member of a namespace is defined outside of the | ||||||
1334 | // scope of its namespace then any name used in the definition of | ||||||
1335 | // the variable member (after the declarator-id) is looked up as | ||||||
1336 | // if the definition of the variable member occurred in its | ||||||
1337 | // namespace. | ||||||
1338 | // Both of these imply that we should push a scope whose context | ||||||
1339 | // is the semantic context of the declaration. We can't use | ||||||
1340 | // PushDeclContext here because that context is not necessarily | ||||||
1341 | // lexically contained in the current context. Fortunately, | ||||||
1342 | // the containing scope should have the appropriate information. | ||||||
1343 | |||||||
1344 | assert(!S->getEntity() && "scope already has entity")((!S->getEntity() && "scope already has entity") ? static_cast<void> (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1344, __PRETTY_FUNCTION__)); | ||||||
1345 | |||||||
1346 | #ifndef NDEBUG | ||||||
1347 | Scope *Ancestor = S->getParent(); | ||||||
1348 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||||
1349 | assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((Ancestor->getEntity() == CurContext && "ancestor context mismatch" ) ? static_cast<void> (0) : __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1349, __PRETTY_FUNCTION__)); | ||||||
1350 | #endif | ||||||
1351 | |||||||
1352 | CurContext = DC; | ||||||
1353 | S->setEntity(DC); | ||||||
1354 | } | ||||||
1355 | |||||||
1356 | void Sema::ExitDeclaratorContext(Scope *S) { | ||||||
1357 | assert(S->getEntity() == CurContext && "Context imbalance!")((S->getEntity() == CurContext && "Context imbalance!" ) ? static_cast<void> (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1357, __PRETTY_FUNCTION__)); | ||||||
1358 | |||||||
1359 | // Switch back to the lexical context. The safety of this is | ||||||
1360 | // enforced by an assert in EnterDeclaratorContext. | ||||||
1361 | Scope *Ancestor = S->getParent(); | ||||||
1362 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||||
1363 | CurContext = Ancestor->getEntity(); | ||||||
1364 | |||||||
1365 | // We don't need to do anything with the scope, which is going to | ||||||
1366 | // disappear. | ||||||
1367 | } | ||||||
1368 | |||||||
1369 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { | ||||||
1370 | // We assume that the caller has already called | ||||||
1371 | // ActOnReenterTemplateScope so getTemplatedDecl() works. | ||||||
1372 | FunctionDecl *FD = D->getAsFunction(); | ||||||
1373 | if (!FD) | ||||||
1374 | return; | ||||||
1375 | |||||||
1376 | // Same implementation as PushDeclContext, but enters the context | ||||||
1377 | // from the lexical parent, rather than the top-level class. | ||||||
1378 | assert(CurContext == FD->getLexicalParent() &&((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1379, __PRETTY_FUNCTION__)) | ||||||
1379 | "The next DeclContext should be lexically contained in the current one.")((CurContext == FD->getLexicalParent() && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1379, __PRETTY_FUNCTION__)); | ||||||
1380 | CurContext = FD; | ||||||
1381 | S->setEntity(CurContext); | ||||||
1382 | |||||||
1383 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { | ||||||
1384 | ParmVarDecl *Param = FD->getParamDecl(P); | ||||||
1385 | // If the parameter has an identifier, then add it to the scope | ||||||
1386 | if (Param->getIdentifier()) { | ||||||
1387 | S->AddDecl(Param); | ||||||
1388 | IdResolver.AddDecl(Param); | ||||||
1389 | } | ||||||
1390 | } | ||||||
1391 | } | ||||||
1392 | |||||||
1393 | void Sema::ActOnExitFunctionContext() { | ||||||
1394 | // Same implementation as PopDeclContext, but returns to the lexical parent, | ||||||
1395 | // rather than the top-level class. | ||||||
1396 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1396, __PRETTY_FUNCTION__)); | ||||||
1397 | CurContext = CurContext->getLexicalParent(); | ||||||
1398 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1398, __PRETTY_FUNCTION__)); | ||||||
1399 | } | ||||||
1400 | |||||||
1401 | /// Determine whether we allow overloading of the function | ||||||
1402 | /// PrevDecl with another declaration. | ||||||
1403 | /// | ||||||
1404 | /// This routine determines whether overloading is possible, not | ||||||
1405 | /// whether some new function is actually an overload. It will return | ||||||
1406 | /// true in C++ (where we can always provide overloads) or, as an | ||||||
1407 | /// extension, in C when the previous function is already an | ||||||
1408 | /// overloaded function declaration or has the "overloadable" | ||||||
1409 | /// attribute. | ||||||
1410 | static bool AllowOverloadingOfFunction(LookupResult &Previous, | ||||||
1411 | ASTContext &Context, | ||||||
1412 | const FunctionDecl *New) { | ||||||
1413 | if (Context.getLangOpts().CPlusPlus) | ||||||
1414 | return true; | ||||||
1415 | |||||||
1416 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) | ||||||
1417 | return true; | ||||||
1418 | |||||||
1419 | return Previous.getResultKind() == LookupResult::Found && | ||||||
1420 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || | ||||||
1421 | New->hasAttr<OverloadableAttr>()); | ||||||
1422 | } | ||||||
1423 | |||||||
1424 | /// Add this decl to the scope shadowed decl chains. | ||||||
1425 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { | ||||||
1426 | // Move up the scope chain until we find the nearest enclosing | ||||||
1427 | // non-transparent context. The declaration will be introduced into this | ||||||
1428 | // scope. | ||||||
1429 | while (S->getEntity() && S->getEntity()->isTransparentContext()) | ||||||
1430 | S = S->getParent(); | ||||||
1431 | |||||||
1432 | // Add scoped declarations into their context, so that they can be | ||||||
1433 | // found later. Declarations without a context won't be inserted | ||||||
1434 | // into any context. | ||||||
1435 | if (AddToContext) | ||||||
1436 | CurContext->addDecl(D); | ||||||
1437 | |||||||
1438 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they | ||||||
1439 | // are function-local declarations. | ||||||
1440 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && | ||||||
1441 | !D->getDeclContext()->getRedeclContext()->Equals( | ||||||
1442 | D->getLexicalDeclContext()->getRedeclContext()) && | ||||||
1443 | !D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||
1444 | return; | ||||||
1445 | |||||||
1446 | // Template instantiations should also not be pushed into scope. | ||||||
1447 | if (isa<FunctionDecl>(D) && | ||||||
1448 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) | ||||||
1449 | return; | ||||||
1450 | |||||||
1451 | // If this replaces anything in the current scope, | ||||||
1452 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), | ||||||
1453 | IEnd = IdResolver.end(); | ||||||
1454 | for (; I != IEnd; ++I) { | ||||||
1455 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { | ||||||
1456 | S->RemoveDecl(*I); | ||||||
1457 | IdResolver.RemoveDecl(*I); | ||||||
1458 | |||||||
1459 | // Should only need to replace one decl. | ||||||
1460 | break; | ||||||
1461 | } | ||||||
1462 | } | ||||||
1463 | |||||||
1464 | S->AddDecl(D); | ||||||
1465 | |||||||
1466 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { | ||||||
1467 | // Implicitly-generated labels may end up getting generated in an order that | ||||||
1468 | // isn't strictly lexical, which breaks name lookup. Be careful to insert | ||||||
1469 | // the label at the appropriate place in the identifier chain. | ||||||
1470 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { | ||||||
1471 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); | ||||||
1472 | if (IDC == CurContext) { | ||||||
1473 | if (!S->isDeclScope(*I)) | ||||||
1474 | continue; | ||||||
1475 | } else if (IDC->Encloses(CurContext)) | ||||||
1476 | break; | ||||||
1477 | } | ||||||
1478 | |||||||
1479 | IdResolver.InsertDeclAfter(I, D); | ||||||
1480 | } else { | ||||||
1481 | IdResolver.AddDecl(D); | ||||||
1482 | } | ||||||
1483 | } | ||||||
1484 | |||||||
1485 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, | ||||||
1486 | bool AllowInlineNamespace) { | ||||||
1487 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); | ||||||
1488 | } | ||||||
1489 | |||||||
1490 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { | ||||||
1491 | DeclContext *TargetDC = DC->getPrimaryContext(); | ||||||
1492 | do { | ||||||
1493 | if (DeclContext *ScopeDC = S->getEntity()) | ||||||
1494 | if (ScopeDC->getPrimaryContext() == TargetDC) | ||||||
1495 | return S; | ||||||
1496 | } while ((S = S->getParent())); | ||||||
1497 | |||||||
1498 | return nullptr; | ||||||
1499 | } | ||||||
1500 | |||||||
1501 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, | ||||||
1502 | DeclContext*, | ||||||
1503 | ASTContext&); | ||||||
1504 | |||||||
1505 | /// Filters out lookup results that don't fall within the given scope | ||||||
1506 | /// as determined by isDeclInScope. | ||||||
1507 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | ||||||
1508 | bool ConsiderLinkage, | ||||||
1509 | bool AllowInlineNamespace) { | ||||||
1510 | LookupResult::Filter F = R.makeFilter(); | ||||||
1511 | while (F.hasNext()) { | ||||||
1512 | NamedDecl *D = F.next(); | ||||||
1513 | |||||||
1514 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) | ||||||
1515 | continue; | ||||||
1516 | |||||||
1517 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) | ||||||
1518 | continue; | ||||||
1519 | |||||||
1520 | F.erase(); | ||||||
1521 | } | ||||||
1522 | |||||||
1523 | F.done(); | ||||||
1524 | } | ||||||
1525 | |||||||
1526 | /// We've determined that \p New is a redeclaration of \p Old. Check that they | ||||||
1527 | /// have compatible owning modules. | ||||||
1528 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { | ||||||
1529 | // FIXME: The Modules TS is not clear about how friend declarations are | ||||||
1530 | // to be treated. It's not meaningful to have different owning modules for | ||||||
1531 | // linkage in redeclarations of the same entity, so for now allow the | ||||||
1532 | // redeclaration and change the owning modules to match. | ||||||
1533 | if (New->getFriendObjectKind() && | ||||||
1534 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { | ||||||
1535 | New->setLocalOwningModule(Old->getOwningModule()); | ||||||
1536 | makeMergedDefinitionVisible(New); | ||||||
1537 | return false; | ||||||
1538 | } | ||||||
1539 | |||||||
1540 | Module *NewM = New->getOwningModule(); | ||||||
1541 | Module *OldM = Old->getOwningModule(); | ||||||
1542 | |||||||
1543 | if (NewM && NewM->Kind == Module::PrivateModuleFragment) | ||||||
1544 | NewM = NewM->Parent; | ||||||
1545 | if (OldM && OldM->Kind == Module::PrivateModuleFragment) | ||||||
1546 | OldM = OldM->Parent; | ||||||
1547 | |||||||
1548 | if (NewM == OldM) | ||||||
1549 | return false; | ||||||
1550 | |||||||
1551 | bool NewIsModuleInterface = NewM && NewM->isModulePurview(); | ||||||
1552 | bool OldIsModuleInterface = OldM && OldM->isModulePurview(); | ||||||
1553 | if (NewIsModuleInterface || OldIsModuleInterface) { | ||||||
1554 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: | ||||||
1555 | // if a declaration of D [...] appears in the purview of a module, all | ||||||
1556 | // other such declarations shall appear in the purview of the same module | ||||||
1557 | Diag(New->getLocation(), diag::err_mismatched_owning_module) | ||||||
1558 | << New | ||||||
1559 | << NewIsModuleInterface | ||||||
1560 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") | ||||||
1561 | << OldIsModuleInterface | ||||||
1562 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); | ||||||
1563 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
1564 | New->setInvalidDecl(); | ||||||
1565 | return true; | ||||||
1566 | } | ||||||
1567 | |||||||
1568 | return false; | ||||||
1569 | } | ||||||
1570 | |||||||
1571 | static bool isUsingDecl(NamedDecl *D) { | ||||||
1572 | return isa<UsingShadowDecl>(D) || | ||||||
1573 | isa<UnresolvedUsingTypenameDecl>(D) || | ||||||
1574 | isa<UnresolvedUsingValueDecl>(D); | ||||||
1575 | } | ||||||
1576 | |||||||
1577 | /// Removes using shadow declarations from the lookup results. | ||||||
1578 | static void RemoveUsingDecls(LookupResult &R) { | ||||||
1579 | LookupResult::Filter F = R.makeFilter(); | ||||||
1580 | while (F.hasNext()) | ||||||
1581 | if (isUsingDecl(F.next())) | ||||||
1582 | F.erase(); | ||||||
1583 | |||||||
1584 | F.done(); | ||||||
1585 | } | ||||||
1586 | |||||||
1587 | /// Check for this common pattern: | ||||||
1588 | /// @code | ||||||
1589 | /// class S { | ||||||
1590 | /// S(const S&); // DO NOT IMPLEMENT | ||||||
1591 | /// void operator=(const S&); // DO NOT IMPLEMENT | ||||||
1592 | /// }; | ||||||
1593 | /// @endcode | ||||||
1594 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { | ||||||
1595 | // FIXME: Should check for private access too but access is set after we get | ||||||
1596 | // the decl here. | ||||||
1597 | if (D->doesThisDeclarationHaveABody()) | ||||||
1598 | return false; | ||||||
1599 | |||||||
1600 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) | ||||||
1601 | return CD->isCopyConstructor(); | ||||||
1602 | return D->isCopyAssignmentOperator(); | ||||||
1603 | } | ||||||
1604 | |||||||
1605 | // We need this to handle | ||||||
1606 | // | ||||||
1607 | // typedef struct { | ||||||
1608 | // void *foo() { return 0; } | ||||||
1609 | // } A; | ||||||
1610 | // | ||||||
1611 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' | ||||||
1612 | // for example. If 'A', foo will have external linkage. If we have '*A', | ||||||
1613 | // foo will have no linkage. Since we can't know until we get to the end | ||||||
1614 | // of the typedef, this function finds out if D might have non-external linkage. | ||||||
1615 | // Callers should verify at the end of the TU if it D has external linkage or | ||||||
1616 | // not. | ||||||
1617 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { | ||||||
1618 | const DeclContext *DC = D->getDeclContext(); | ||||||
1619 | while (!DC->isTranslationUnit()) { | ||||||
1620 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ | ||||||
1621 | if (!RD->hasNameForLinkage()) | ||||||
1622 | return true; | ||||||
1623 | } | ||||||
1624 | DC = DC->getParent(); | ||||||
1625 | } | ||||||
1626 | |||||||
1627 | return !D->isExternallyVisible(); | ||||||
1628 | } | ||||||
1629 | |||||||
1630 | // FIXME: This needs to be refactored; some other isInMainFile users want | ||||||
1631 | // these semantics. | ||||||
1632 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { | ||||||
1633 | if (S.TUKind != TU_Complete) | ||||||
1634 | return false; | ||||||
1635 | return S.SourceMgr.isInMainFile(Loc); | ||||||
1636 | } | ||||||
1637 | |||||||
1638 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { | ||||||
1639 | assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1639, __PRETTY_FUNCTION__)); | ||||||
1640 | |||||||
1641 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) | ||||||
1642 | return false; | ||||||
1643 | |||||||
1644 | // Ignore all entities declared within templates, and out-of-line definitions | ||||||
1645 | // of members of class templates. | ||||||
1646 | if (D->getDeclContext()->isDependentContext() || | ||||||
1647 | D->getLexicalDeclContext()->isDependentContext()) | ||||||
1648 | return false; | ||||||
1649 | |||||||
1650 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||
1651 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||||
1652 | return false; | ||||||
1653 | // A non-out-of-line declaration of a member specialization was implicitly | ||||||
1654 | // instantiated; it's the out-of-line declaration that we're interested in. | ||||||
1655 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||||
1656 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) | ||||||
1657 | return false; | ||||||
1658 | |||||||
1659 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
1660 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) | ||||||
1661 | return false; | ||||||
1662 | } else { | ||||||
1663 | // 'static inline' functions are defined in headers; don't warn. | ||||||
1664 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) | ||||||
1665 | return false; | ||||||
1666 | } | ||||||
1667 | |||||||
1668 | if (FD->doesThisDeclarationHaveABody() && | ||||||
1669 | Context.DeclMustBeEmitted(FD)) | ||||||
1670 | return false; | ||||||
1671 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1672 | // Constants and utility variables are defined in headers with internal | ||||||
1673 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker | ||||||
1674 | // like "inline".) | ||||||
1675 | if (!isMainFileLoc(*this, VD->getLocation())) | ||||||
1676 | return false; | ||||||
1677 | |||||||
1678 | if (Context.DeclMustBeEmitted(VD)) | ||||||
1679 | return false; | ||||||
1680 | |||||||
1681 | if (VD->isStaticDataMember() && | ||||||
1682 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||||
1683 | return false; | ||||||
1684 | if (VD->isStaticDataMember() && | ||||||
1685 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||||
1686 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) | ||||||
1687 | return false; | ||||||
1688 | |||||||
1689 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) | ||||||
1690 | return false; | ||||||
1691 | } else { | ||||||
1692 | return false; | ||||||
1693 | } | ||||||
1694 | |||||||
1695 | // Only warn for unused decls internal to the translation unit. | ||||||
1696 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function | ||||||
1697 | // for inline functions defined in the main source file, for instance. | ||||||
1698 | return mightHaveNonExternalLinkage(D); | ||||||
1699 | } | ||||||
1700 | |||||||
1701 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { | ||||||
1702 | if (!D) | ||||||
1703 | return; | ||||||
1704 | |||||||
1705 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||
1706 | const FunctionDecl *First = FD->getFirstDecl(); | ||||||
1707 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||||
1708 | return; // First should already be in the vector. | ||||||
1709 | } | ||||||
1710 | |||||||
1711 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1712 | const VarDecl *First = VD->getFirstDecl(); | ||||||
1713 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||||
1714 | return; // First should already be in the vector. | ||||||
1715 | } | ||||||
1716 | |||||||
1717 | if (ShouldWarnIfUnusedFileScopedDecl(D)) | ||||||
1718 | UnusedFileScopedDecls.push_back(D); | ||||||
1719 | } | ||||||
1720 | |||||||
1721 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { | ||||||
1722 | if (D->isInvalidDecl()) | ||||||
1723 | return false; | ||||||
1724 | |||||||
1725 | bool Referenced = false; | ||||||
1726 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { | ||||||
1727 | // For a decomposition declaration, warn if none of the bindings are | ||||||
1728 | // referenced, instead of if the variable itself is referenced (which | ||||||
1729 | // it is, by the bindings' expressions). | ||||||
1730 | for (auto *BD : DD->bindings()) { | ||||||
1731 | if (BD->isReferenced()) { | ||||||
1732 | Referenced = true; | ||||||
1733 | break; | ||||||
1734 | } | ||||||
1735 | } | ||||||
1736 | } else if (!D->getDeclName()) { | ||||||
1737 | return false; | ||||||
1738 | } else if (D->isReferenced() || D->isUsed()) { | ||||||
1739 | Referenced = true; | ||||||
1740 | } | ||||||
1741 | |||||||
1742 | if (Referenced || D->hasAttr<UnusedAttr>() || | ||||||
1743 | D->hasAttr<ObjCPreciseLifetimeAttr>()) | ||||||
1744 | return false; | ||||||
1745 | |||||||
1746 | if (isa<LabelDecl>(D)) | ||||||
1747 | return true; | ||||||
1748 | |||||||
1749 | // Except for labels, we only care about unused decls that are local to | ||||||
1750 | // functions. | ||||||
1751 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); | ||||||
1752 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) | ||||||
1753 | // For dependent types, the diagnostic is deferred. | ||||||
1754 | WithinFunction = | ||||||
1755 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); | ||||||
1756 | if (!WithinFunction) | ||||||
1757 | return false; | ||||||
1758 | |||||||
1759 | if (isa<TypedefNameDecl>(D)) | ||||||
1760 | return true; | ||||||
1761 | |||||||
1762 | // White-list anything that isn't a local variable. | ||||||
1763 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) | ||||||
1764 | return false; | ||||||
1765 | |||||||
1766 | // Types of valid local variables should be complete, so this should succeed. | ||||||
1767 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1768 | |||||||
1769 | // White-list anything with an __attribute__((unused)) type. | ||||||
1770 | const auto *Ty = VD->getType().getTypePtr(); | ||||||
1771 | |||||||
1772 | // Only look at the outermost level of typedef. | ||||||
1773 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { | ||||||
1774 | if (TT->getDecl()->hasAttr<UnusedAttr>()) | ||||||
1775 | return false; | ||||||
1776 | } | ||||||
1777 | |||||||
1778 | // If we failed to complete the type for some reason, or if the type is | ||||||
1779 | // dependent, don't diagnose the variable. | ||||||
1780 | if (Ty->isIncompleteType() || Ty->isDependentType()) | ||||||
1781 | return false; | ||||||
1782 | |||||||
1783 | // Look at the element type to ensure that the warning behaviour is | ||||||
1784 | // consistent for both scalars and arrays. | ||||||
1785 | Ty = Ty->getBaseElementTypeUnsafe(); | ||||||
1786 | |||||||
1787 | if (const TagType *TT = Ty->getAs<TagType>()) { | ||||||
1788 | const TagDecl *Tag = TT->getDecl(); | ||||||
1789 | if (Tag->hasAttr<UnusedAttr>()) | ||||||
1790 | return false; | ||||||
1791 | |||||||
1792 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | ||||||
1793 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) | ||||||
1794 | return false; | ||||||
1795 | |||||||
1796 | if (const Expr *Init = VD->getInit()) { | ||||||
1797 | if (const ExprWithCleanups *Cleanups = | ||||||
1798 | dyn_cast<ExprWithCleanups>(Init)) | ||||||
1799 | Init = Cleanups->getSubExpr(); | ||||||
1800 | const CXXConstructExpr *Construct = | ||||||
1801 | dyn_cast<CXXConstructExpr>(Init); | ||||||
1802 | if (Construct && !Construct->isElidable()) { | ||||||
1803 | CXXConstructorDecl *CD = Construct->getConstructor(); | ||||||
1804 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && | ||||||
1805 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) | ||||||
1806 | return false; | ||||||
1807 | } | ||||||
1808 | |||||||
1809 | // Suppress the warning if we don't know how this is constructed, and | ||||||
1810 | // it could possibly be non-trivial constructor. | ||||||
1811 | if (Init->isTypeDependent()) | ||||||
1812 | for (const CXXConstructorDecl *Ctor : RD->ctors()) | ||||||
1813 | if (!Ctor->isTrivial()) | ||||||
1814 | return false; | ||||||
1815 | } | ||||||
1816 | } | ||||||
1817 | } | ||||||
1818 | |||||||
1819 | // TODO: __attribute__((unused)) templates? | ||||||
1820 | } | ||||||
1821 | |||||||
1822 | return true; | ||||||
1823 | } | ||||||
1824 | |||||||
1825 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, | ||||||
1826 | FixItHint &Hint) { | ||||||
1827 | if (isa<LabelDecl>(D)) { | ||||||
1828 | SourceLocation AfterColon = Lexer::findLocationAfterToken( | ||||||
1829 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), | ||||||
1830 | true); | ||||||
1831 | if (AfterColon.isInvalid()) | ||||||
1832 | return; | ||||||
1833 | Hint = FixItHint::CreateRemoval( | ||||||
1834 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); | ||||||
1835 | } | ||||||
1836 | } | ||||||
1837 | |||||||
1838 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { | ||||||
1839 | if (D->getTypeForDecl()->isDependentType()) | ||||||
1840 | return; | ||||||
1841 | |||||||
1842 | for (auto *TmpD : D->decls()) { | ||||||
1843 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) | ||||||
1844 | DiagnoseUnusedDecl(T); | ||||||
1845 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) | ||||||
1846 | DiagnoseUnusedNestedTypedefs(R); | ||||||
1847 | } | ||||||
1848 | } | ||||||
1849 | |||||||
1850 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used | ||||||
1851 | /// unless they are marked attr(unused). | ||||||
1852 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { | ||||||
1853 | if (!ShouldDiagnoseUnusedDecl(D)) | ||||||
1854 | return; | ||||||
1855 | |||||||
1856 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { | ||||||
1857 | // typedefs can be referenced later on, so the diagnostics are emitted | ||||||
1858 | // at end-of-translation-unit. | ||||||
1859 | UnusedLocalTypedefNameCandidates.insert(TD); | ||||||
1860 | return; | ||||||
1861 | } | ||||||
1862 | |||||||
1863 | FixItHint Hint; | ||||||
1864 | GenerateFixForUnusedDecl(D, Context, Hint); | ||||||
1865 | |||||||
1866 | unsigned DiagID; | ||||||
1867 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) | ||||||
1868 | DiagID = diag::warn_unused_exception_param; | ||||||
1869 | else if (isa<LabelDecl>(D)) | ||||||
1870 | DiagID = diag::warn_unused_label; | ||||||
1871 | else | ||||||
1872 | DiagID = diag::warn_unused_variable; | ||||||
1873 | |||||||
1874 | Diag(D->getLocation(), DiagID) << D << Hint; | ||||||
1875 | } | ||||||
1876 | |||||||
1877 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { | ||||||
1878 | // Verify that we have no forward references left. If so, there was a goto | ||||||
1879 | // or address of a label taken, but no definition of it. Label fwd | ||||||
1880 | // definitions are indicated with a null substmt which is also not a resolved | ||||||
1881 | // MS inline assembly label name. | ||||||
1882 | bool Diagnose = false; | ||||||
1883 | if (L->isMSAsmLabel()) | ||||||
1884 | Diagnose = !L->isResolvedMSAsmLabel(); | ||||||
1885 | else | ||||||
1886 | Diagnose = L->getStmt() == nullptr; | ||||||
1887 | if (Diagnose) | ||||||
1888 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); | ||||||
1889 | } | ||||||
1890 | |||||||
1891 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { | ||||||
1892 | S->mergeNRVOIntoParent(); | ||||||
1893 | |||||||
1894 | if (S->decl_empty()) return; | ||||||
1895 | assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1896, __PRETTY_FUNCTION__)) | ||||||
1896 | "Scope shouldn't contain decls!")(((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope )) && "Scope shouldn't contain decls!") ? static_cast <void> (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1896, __PRETTY_FUNCTION__)); | ||||||
1897 | |||||||
1898 | for (auto *TmpD : S->decls()) { | ||||||
1899 | assert(TmpD && "This decl didn't get pushed??")((TmpD && "This decl didn't get pushed??") ? static_cast <void> (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1899, __PRETTY_FUNCTION__)); | ||||||
1900 | |||||||
1901 | assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?" ) ? static_cast<void> (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 1901, __PRETTY_FUNCTION__)); | ||||||
1902 | NamedDecl *D = cast<NamedDecl>(TmpD); | ||||||
1903 | |||||||
1904 | // Diagnose unused variables in this scope. | ||||||
1905 | if (!S->hasUnrecoverableErrorOccurred()) { | ||||||
1906 | DiagnoseUnusedDecl(D); | ||||||
1907 | if (const auto *RD = dyn_cast<RecordDecl>(D)) | ||||||
1908 | DiagnoseUnusedNestedTypedefs(RD); | ||||||
1909 | } | ||||||
1910 | |||||||
1911 | if (!D->getDeclName()) continue; | ||||||
1912 | |||||||
1913 | // If this was a forward reference to a label, verify it was defined. | ||||||
1914 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) | ||||||
1915 | CheckPoppedLabel(LD, *this); | ||||||
1916 | |||||||
1917 | // Remove this name from our lexical scope, and warn on it if we haven't | ||||||
1918 | // already. | ||||||
1919 | IdResolver.RemoveDecl(D); | ||||||
1920 | auto ShadowI = ShadowingDecls.find(D); | ||||||
1921 | if (ShadowI != ShadowingDecls.end()) { | ||||||
1922 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { | ||||||
1923 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) | ||||||
1924 | << D << FD << FD->getParent(); | ||||||
1925 | Diag(FD->getLocation(), diag::note_previous_declaration); | ||||||
1926 | } | ||||||
1927 | ShadowingDecls.erase(ShadowI); | ||||||
1928 | } | ||||||
1929 | } | ||||||
1930 | } | ||||||
1931 | |||||||
1932 | /// Look for an Objective-C class in the translation unit. | ||||||
1933 | /// | ||||||
1934 | /// \param Id The name of the Objective-C class we're looking for. If | ||||||
1935 | /// typo-correction fixes this name, the Id will be updated | ||||||
1936 | /// to the fixed name. | ||||||
1937 | /// | ||||||
1938 | /// \param IdLoc The location of the name in the translation unit. | ||||||
1939 | /// | ||||||
1940 | /// \param DoTypoCorrection If true, this routine will attempt typo correction | ||||||
1941 | /// if there is no class with the given name. | ||||||
1942 | /// | ||||||
1943 | /// \returns The declaration of the named Objective-C class, or NULL if the | ||||||
1944 | /// class could not be found. | ||||||
1945 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, | ||||||
1946 | SourceLocation IdLoc, | ||||||
1947 | bool DoTypoCorrection) { | ||||||
1948 | // The third "scope" argument is 0 since we aren't enabling lazy built-in | ||||||
1949 | // creation from this context. | ||||||
1950 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); | ||||||
1951 | |||||||
1952 | if (!IDecl && DoTypoCorrection) { | ||||||
1953 | // Perform typo correction at the given location, but only if we | ||||||
1954 | // find an Objective-C class name. | ||||||
1955 | DeclFilterCCC<ObjCInterfaceDecl> CCC{}; | ||||||
1956 | if (TypoCorrection C = | ||||||
1957 | CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, | ||||||
1958 | TUScope, nullptr, CCC, CTK_ErrorRecovery)) { | ||||||
1959 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); | ||||||
1960 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); | ||||||
1961 | Id = IDecl->getIdentifier(); | ||||||
1962 | } | ||||||
1963 | } | ||||||
1964 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); | ||||||
1965 | // This routine must always return a class definition, if any. | ||||||
1966 | if (Def && Def->getDefinition()) | ||||||
1967 | Def = Def->getDefinition(); | ||||||
1968 | return Def; | ||||||
1969 | } | ||||||
1970 | |||||||
1971 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting | ||||||
1972 | /// from S, where a non-field would be declared. This routine copes | ||||||
1973 | /// with the difference between C and C++ scoping rules in structs and | ||||||
1974 | /// unions. For example, the following code is well-formed in C but | ||||||
1975 | /// ill-formed in C++: | ||||||
1976 | /// @code | ||||||
1977 | /// struct S6 { | ||||||
1978 | /// enum { BAR } e; | ||||||
1979 | /// }; | ||||||
1980 | /// | ||||||
1981 | /// void test_S6() { | ||||||
1982 | /// struct S6 a; | ||||||
1983 | /// a.e = BAR; | ||||||
1984 | /// } | ||||||
1985 | /// @endcode | ||||||
1986 | /// For the declaration of BAR, this routine will return a different | ||||||
1987 | /// scope. The scope S will be the scope of the unnamed enumeration | ||||||
1988 | /// within S6. In C++, this routine will return the scope associated | ||||||
1989 | /// with S6, because the enumeration's scope is a transparent | ||||||
1990 | /// context but structures can contain non-field names. In C, this | ||||||
1991 | /// routine will return the translation unit scope, since the | ||||||
1992 | /// enumeration's scope is a transparent context and structures cannot | ||||||
1993 | /// contain non-field names. | ||||||
1994 | Scope *Sema::getNonFieldDeclScope(Scope *S) { | ||||||
1995 | while (((S->getFlags() & Scope::DeclScope) == 0) || | ||||||
1996 | (S->getEntity() && S->getEntity()->isTransparentContext()) || | ||||||
1997 | (S->isClassScope() && !getLangOpts().CPlusPlus)) | ||||||
1998 | S = S->getParent(); | ||||||
1999 | return S; | ||||||
2000 | } | ||||||
2001 | |||||||
2002 | /// Looks up the declaration of "struct objc_super" and | ||||||
2003 | /// saves it for later use in building builtin declaration of | ||||||
2004 | /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such | ||||||
2005 | /// pre-existing declaration exists no action takes place. | ||||||
2006 | static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, | ||||||
2007 | IdentifierInfo *II) { | ||||||
2008 | if (!II->isStr("objc_msgSendSuper")) | ||||||
2009 | return; | ||||||
2010 | ASTContext &Context = ThisSema.Context; | ||||||
2011 | |||||||
2012 | LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), | ||||||
2013 | SourceLocation(), Sema::LookupTagName); | ||||||
2014 | ThisSema.LookupName(Result, S); | ||||||
2015 | if (Result.getResultKind() == LookupResult::Found) | ||||||
2016 | if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) | ||||||
2017 | Context.setObjCSuperType(Context.getTagDeclType(TD)); | ||||||
2018 | } | ||||||
2019 | |||||||
2020 | static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, | ||||||
2021 | ASTContext::GetBuiltinTypeError Error) { | ||||||
2022 | switch (Error) { | ||||||
2023 | case ASTContext::GE_None: | ||||||
2024 | return ""; | ||||||
2025 | case ASTContext::GE_Missing_type: | ||||||
2026 | return BuiltinInfo.getHeaderName(ID); | ||||||
2027 | case ASTContext::GE_Missing_stdio: | ||||||
2028 | return "stdio.h"; | ||||||
2029 | case ASTContext::GE_Missing_setjmp: | ||||||
2030 | return "setjmp.h"; | ||||||
2031 | case ASTContext::GE_Missing_ucontext: | ||||||
2032 | return "ucontext.h"; | ||||||
2033 | } | ||||||
2034 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 2034); | ||||||
2035 | } | ||||||
2036 | |||||||
2037 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at | ||||||
2038 | /// file scope. lazily create a decl for it. ForRedeclaration is true | ||||||
2039 | /// if we're creating this built-in in anticipation of redeclaring the | ||||||
2040 | /// built-in. | ||||||
2041 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | ||||||
2042 | Scope *S, bool ForRedeclaration, | ||||||
2043 | SourceLocation Loc) { | ||||||
2044 | LookupPredefedObjCSuperType(*this, S, II); | ||||||
2045 | |||||||
2046 | ASTContext::GetBuiltinTypeError Error; | ||||||
2047 | QualType R = Context.GetBuiltinType(ID, Error); | ||||||
2048 | if (Error) { | ||||||
2049 | if (!ForRedeclaration) | ||||||
2050 | return nullptr; | ||||||
2051 | |||||||
2052 | // If we have a builtin without an associated type we should not emit a | ||||||
2053 | // warning when we were not able to find a type for it. | ||||||
2054 | if (Error == ASTContext::GE_Missing_type) | ||||||
2055 | return nullptr; | ||||||
2056 | |||||||
2057 | // If we could not find a type for setjmp it is because the jmp_buf type was | ||||||
2058 | // not defined prior to the setjmp declaration. | ||||||
2059 | if (Error == ASTContext::GE_Missing_setjmp) { | ||||||
2060 | Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) | ||||||
2061 | << Context.BuiltinInfo.getName(ID); | ||||||
2062 | return nullptr; | ||||||
2063 | } | ||||||
2064 | |||||||
2065 | // Generally, we emit a warning that the declaration requires the | ||||||
2066 | // appropriate header. | ||||||
2067 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) | ||||||
2068 | << getHeaderName(Context.BuiltinInfo, ID, Error) | ||||||
2069 | << Context.BuiltinInfo.getName(ID); | ||||||
2070 | return nullptr; | ||||||
2071 | } | ||||||
2072 | |||||||
2073 | if (!ForRedeclaration && | ||||||
2074 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || | ||||||
2075 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { | ||||||
2076 | Diag(Loc, diag::ext_implicit_lib_function_decl) | ||||||
2077 | << Context.BuiltinInfo.getName(ID) << R; | ||||||
2078 | if (Context.BuiltinInfo.getHeaderName(ID) && | ||||||
2079 | !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) | ||||||
2080 | Diag(Loc, diag::note_include_header_or_declare) | ||||||
2081 | << Context.BuiltinInfo.getHeaderName(ID) | ||||||
2082 | << Context.BuiltinInfo.getName(ID); | ||||||
2083 | } | ||||||
2084 | |||||||
2085 | if (R.isNull()) | ||||||
2086 | return nullptr; | ||||||
2087 | |||||||
2088 | DeclContext *Parent = Context.getTranslationUnitDecl(); | ||||||
2089 | if (getLangOpts().CPlusPlus) { | ||||||
2090 | LinkageSpecDecl *CLinkageDecl = | ||||||
2091 | LinkageSpecDecl::Create(Context, Parent, Loc, Loc, | ||||||
2092 | LinkageSpecDecl::lang_c, false); | ||||||
2093 | CLinkageDecl->setImplicit(); | ||||||
2094 | Parent->addDecl(CLinkageDecl); | ||||||
2095 | Parent = CLinkageDecl; | ||||||
2096 | } | ||||||
2097 | |||||||
2098 | FunctionDecl *New = FunctionDecl::Create(Context, | ||||||
2099 | Parent, | ||||||
2100 | Loc, Loc, II, R, /*TInfo=*/nullptr, | ||||||
2101 | SC_Extern, | ||||||
2102 | false, | ||||||
2103 | R->isFunctionProtoType()); | ||||||
2104 | New->setImplicit(); | ||||||
2105 | |||||||
2106 | // Create Decl objects for each parameter, adding them to the | ||||||
2107 | // FunctionDecl. | ||||||
2108 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { | ||||||
2109 | SmallVector<ParmVarDecl*, 16> Params; | ||||||
2110 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||||
2111 | ParmVarDecl *parm = | ||||||
2112 | ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), | ||||||
2113 | nullptr, FT->getParamType(i), /*TInfo=*/nullptr, | ||||||
2114 | SC_None, nullptr); | ||||||
2115 | parm->setScopeInfo(0, i); | ||||||
2116 | Params.push_back(parm); | ||||||
2117 | } | ||||||
2118 | New->setParams(Params); | ||||||
2119 | } | ||||||
2120 | |||||||
2121 | AddKnownFunctionAttributes(New); | ||||||
2122 | RegisterLocallyScopedExternCDecl(New, S); | ||||||
2123 | |||||||
2124 | // TUScope is the translation-unit scope to insert this function into. | ||||||
2125 | // FIXME: This is hideous. We need to teach PushOnScopeChains to | ||||||
2126 | // relate Scopes to DeclContexts, and probably eliminate CurContext | ||||||
2127 | // entirely, but we're not there yet. | ||||||
2128 | DeclContext *SavedContext = CurContext; | ||||||
2129 | CurContext = Parent; | ||||||
2130 | PushOnScopeChains(New, TUScope); | ||||||
2131 | CurContext = SavedContext; | ||||||
2132 | return New; | ||||||
2133 | } | ||||||
2134 | |||||||
2135 | /// Typedef declarations don't have linkage, but they still denote the same | ||||||
2136 | /// entity if their types are the same. | ||||||
2137 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's | ||||||
2138 | /// isSameEntity. | ||||||
2139 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, | ||||||
2140 | TypedefNameDecl *Decl, | ||||||
2141 | LookupResult &Previous) { | ||||||
2142 | // This is only interesting when modules are enabled. | ||||||
2143 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) | ||||||
2144 | return; | ||||||
2145 | |||||||
2146 | // Empty sets are uninteresting. | ||||||
2147 | if (Previous.empty()) | ||||||
2148 | return; | ||||||
2149 | |||||||
2150 | LookupResult::Filter Filter = Previous.makeFilter(); | ||||||
2151 | while (Filter.hasNext()) { | ||||||
2152 | NamedDecl *Old = Filter.next(); | ||||||
2153 | |||||||
2154 | // Non-hidden declarations are never ignored. | ||||||
2155 | if (S.isVisible(Old)) | ||||||
2156 | continue; | ||||||
2157 | |||||||
2158 | // Declarations of the same entity are not ignored, even if they have | ||||||
2159 | // different linkages. | ||||||
2160 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2161 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), | ||||||
2162 | Decl->getUnderlyingType())) | ||||||
2163 | continue; | ||||||
2164 | |||||||
2165 | // If both declarations give a tag declaration a typedef name for linkage | ||||||
2166 | // purposes, then they declare the same entity. | ||||||
2167 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && | ||||||
2168 | Decl->getAnonDeclWithTypedefName()) | ||||||
2169 | continue; | ||||||
2170 | } | ||||||
2171 | |||||||
2172 | Filter.erase(); | ||||||
2173 | } | ||||||
2174 | |||||||
2175 | Filter.done(); | ||||||
2176 | } | ||||||
2177 | |||||||
2178 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { | ||||||
2179 | QualType OldType; | ||||||
2180 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) | ||||||
2181 | OldType = OldTypedef->getUnderlyingType(); | ||||||
2182 | else | ||||||
2183 | OldType = Context.getTypeDeclType(Old); | ||||||
2184 | QualType NewType = New->getUnderlyingType(); | ||||||
2185 | |||||||
2186 | if (NewType->isVariablyModifiedType()) { | ||||||
2187 | // Must not redefine a typedef with a variably-modified type. | ||||||
2188 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||||
2189 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) | ||||||
2190 | << Kind << NewType; | ||||||
2191 | if (Old->getLocation().isValid()) | ||||||
2192 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2193 | New->setInvalidDecl(); | ||||||
2194 | return true; | ||||||
2195 | } | ||||||
2196 | |||||||
2197 | if (OldType != NewType && | ||||||
2198 | !OldType->isDependentType() && | ||||||
2199 | !NewType->isDependentType() && | ||||||
2200 | !Context.hasSameType(OldType, NewType)) { | ||||||
2201 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||||
2202 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) | ||||||
2203 | << Kind << NewType << OldType; | ||||||
2204 | if (Old->getLocation().isValid()) | ||||||
2205 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2206 | New->setInvalidDecl(); | ||||||
2207 | return true; | ||||||
2208 | } | ||||||
2209 | return false; | ||||||
2210 | } | ||||||
2211 | |||||||
2212 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the | ||||||
2213 | /// same name and scope as a previous declaration 'Old'. Figure out | ||||||
2214 | /// how to resolve this situation, merging decls or emitting | ||||||
2215 | /// diagnostics as appropriate. If there was an error, set New to be invalid. | ||||||
2216 | /// | ||||||
2217 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | ||||||
2218 | LookupResult &OldDecls) { | ||||||
2219 | // If the new decl is known invalid already, don't bother doing any | ||||||
2220 | // merging checks. | ||||||
2221 | if (New->isInvalidDecl()) return; | ||||||
2222 | |||||||
2223 | // Allow multiple definitions for ObjC built-in typedefs. | ||||||
2224 | // FIXME: Verify the underlying types are equivalent! | ||||||
2225 | if (getLangOpts().ObjC) { | ||||||
2226 | const IdentifierInfo *TypeID = New->getIdentifier(); | ||||||
2227 | switch (TypeID->getLength()) { | ||||||
2228 | default: break; | ||||||
2229 | case 2: | ||||||
2230 | { | ||||||
2231 | if (!TypeID->isStr("id")) | ||||||
2232 | break; | ||||||
2233 | QualType T = New->getUnderlyingType(); | ||||||
2234 | if (!T->isPointerType()) | ||||||
2235 | break; | ||||||
2236 | if (!T->isVoidPointerType()) { | ||||||
2237 | QualType PT = T->castAs<PointerType>()->getPointeeType(); | ||||||
2238 | if (!PT->isStructureType()) | ||||||
2239 | break; | ||||||
2240 | } | ||||||
2241 | Context.setObjCIdRedefinitionType(T); | ||||||
2242 | // Install the built-in type for 'id', ignoring the current definition. | ||||||
2243 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); | ||||||
2244 | return; | ||||||
2245 | } | ||||||
2246 | case 5: | ||||||
2247 | if (!TypeID->isStr("Class")) | ||||||
2248 | break; | ||||||
2249 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); | ||||||
2250 | // Install the built-in type for 'Class', ignoring the current definition. | ||||||
2251 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); | ||||||
2252 | return; | ||||||
2253 | case 3: | ||||||
2254 | if (!TypeID->isStr("SEL")) | ||||||
2255 | break; | ||||||
2256 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); | ||||||
2257 | // Install the built-in type for 'SEL', ignoring the current definition. | ||||||
2258 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); | ||||||
2259 | return; | ||||||
2260 | } | ||||||
2261 | // Fall through - the typedef name was not a builtin type. | ||||||
2262 | } | ||||||
2263 | |||||||
2264 | // Verify the old decl was also a type. | ||||||
2265 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); | ||||||
2266 | if (!Old) { | ||||||
2267 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
2268 | << New->getDeclName(); | ||||||
2269 | |||||||
2270 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); | ||||||
2271 | if (OldD->getLocation().isValid()) | ||||||
2272 | notePreviousDefinition(OldD, New->getLocation()); | ||||||
2273 | |||||||
2274 | return New->setInvalidDecl(); | ||||||
2275 | } | ||||||
2276 | |||||||
2277 | // If the old declaration is invalid, just give up here. | ||||||
2278 | if (Old->isInvalidDecl()) | ||||||
2279 | return New->setInvalidDecl(); | ||||||
2280 | |||||||
2281 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2282 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); | ||||||
2283 | auto *NewTag = New->getAnonDeclWithTypedefName(); | ||||||
2284 | NamedDecl *Hidden = nullptr; | ||||||
2285 | if (OldTag && NewTag && | ||||||
2286 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && | ||||||
2287 | !hasVisibleDefinition(OldTag, &Hidden)) { | ||||||
2288 | // There is a definition of this tag, but it is not visible. Use it | ||||||
2289 | // instead of our tag. | ||||||
2290 | New->setTypeForDecl(OldTD->getTypeForDecl()); | ||||||
2291 | if (OldTD->isModed()) | ||||||
2292 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), | ||||||
2293 | OldTD->getUnderlyingType()); | ||||||
2294 | else | ||||||
2295 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); | ||||||
2296 | |||||||
2297 | // Make the old tag definition visible. | ||||||
2298 | makeMergedDefinitionVisible(Hidden); | ||||||
2299 | |||||||
2300 | // If this was an unscoped enumeration, yank all of its enumerators | ||||||
2301 | // out of the scope. | ||||||
2302 | if (isa<EnumDecl>(NewTag)) { | ||||||
2303 | Scope *EnumScope = getNonFieldDeclScope(S); | ||||||
2304 | for (auto *D : NewTag->decls()) { | ||||||
2305 | auto *ED = cast<EnumConstantDecl>(D); | ||||||
2306 | assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0 ) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 2306, __PRETTY_FUNCTION__)); | ||||||
2307 | EnumScope->RemoveDecl(ED); | ||||||
2308 | IdResolver.RemoveDecl(ED); | ||||||
2309 | ED->getLexicalDeclContext()->removeDecl(ED); | ||||||
2310 | } | ||||||
2311 | } | ||||||
2312 | } | ||||||
2313 | } | ||||||
2314 | |||||||
2315 | // If the typedef types are not identical, reject them in all languages and | ||||||
2316 | // with any extensions enabled. | ||||||
2317 | if (isIncompatibleTypedef(Old, New)) | ||||||
2318 | return; | ||||||
2319 | |||||||
2320 | // The types match. Link up the redeclaration chain and merge attributes if | ||||||
2321 | // the old declaration was a typedef. | ||||||
2322 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2323 | New->setPreviousDecl(Typedef); | ||||||
2324 | mergeDeclAttributes(New, Old); | ||||||
2325 | } | ||||||
2326 | |||||||
2327 | if (getLangOpts().MicrosoftExt) | ||||||
2328 | return; | ||||||
2329 | |||||||
2330 | if (getLangOpts().CPlusPlus) { | ||||||
2331 | // C++ [dcl.typedef]p2: | ||||||
2332 | // In a given non-class scope, a typedef specifier can be used to | ||||||
2333 | // redefine the name of any type declared in that scope to refer | ||||||
2334 | // to the type to which it already refers. | ||||||
2335 | if (!isa<CXXRecordDecl>(CurContext)) | ||||||
2336 | return; | ||||||
2337 | |||||||
2338 | // C++0x [dcl.typedef]p4: | ||||||
2339 | // In a given class scope, a typedef specifier can be used to redefine | ||||||
2340 | // any class-name declared in that scope that is not also a typedef-name | ||||||
2341 | // to refer to the type to which it already refers. | ||||||
2342 | // | ||||||
2343 | // This wording came in via DR424, which was a correction to the | ||||||
2344 | // wording in DR56, which accidentally banned code like: | ||||||
2345 | // | ||||||
2346 | // struct S { | ||||||
2347 | // typedef struct A { } A; | ||||||
2348 | // }; | ||||||
2349 | // | ||||||
2350 | // in the C++03 standard. We implement the C++0x semantics, which | ||||||
2351 | // allow the above but disallow | ||||||
2352 | // | ||||||
2353 | // struct S { | ||||||
2354 | // typedef int I; | ||||||
2355 | // typedef int I; | ||||||
2356 | // }; | ||||||
2357 | // | ||||||
2358 | // since that was the intent of DR56. | ||||||
2359 | if (!isa<TypedefNameDecl>(Old)) | ||||||
2360 | return; | ||||||
2361 | |||||||
2362 | Diag(New->getLocation(), diag::err_redefinition) | ||||||
2363 | << New->getDeclName(); | ||||||
2364 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2365 | return New->setInvalidDecl(); | ||||||
2366 | } | ||||||
2367 | |||||||
2368 | // Modules always permit redefinition of typedefs, as does C11. | ||||||
2369 | if (getLangOpts().Modules || getLangOpts().C11) | ||||||
2370 | return; | ||||||
2371 | |||||||
2372 | // If we have a redefinition of a typedef in C, emit a warning. This warning | ||||||
2373 | // is normally mapped to an error, but can be controlled with | ||||||
2374 | // -Wtypedef-redefinition. If either the original or the redefinition is | ||||||
2375 | // in a system header, don't emit this for compatibility with GCC. | ||||||
2376 | if (getDiagnostics().getSuppressSystemWarnings() && | ||||||
2377 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). | ||||||
2378 | (Old->isImplicit() || | ||||||
2379 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || | ||||||
2380 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) | ||||||
2381 | return; | ||||||
2382 | |||||||
2383 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) | ||||||
2384 | << New->getDeclName(); | ||||||
2385 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2386 | } | ||||||
2387 | |||||||
2388 | /// DeclhasAttr - returns true if decl Declaration already has the target | ||||||
2389 | /// attribute. | ||||||
2390 | static bool DeclHasAttr(const Decl *D, const Attr *A) { | ||||||
2391 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); | ||||||
2392 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); | ||||||
2393 | for (const auto *i : D->attrs()) | ||||||
2394 | if (i->getKind() == A->getKind()) { | ||||||
2395 | if (Ann) { | ||||||
2396 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) | ||||||
2397 | return true; | ||||||
2398 | continue; | ||||||
2399 | } | ||||||
2400 | // FIXME: Don't hardcode this check | ||||||
2401 | if (OA && isa<OwnershipAttr>(i)) | ||||||
2402 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); | ||||||
2403 | return true; | ||||||
2404 | } | ||||||
2405 | |||||||
2406 | return false; | ||||||
2407 | } | ||||||
2408 | |||||||
2409 | static bool isAttributeTargetADefinition(Decl *D) { | ||||||
2410 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||||
2411 | return VD->isThisDeclarationADefinition(); | ||||||
2412 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||||
2413 | return TD->isCompleteDefinition() || TD->isBeingDefined(); | ||||||
2414 | return true; | ||||||
2415 | } | ||||||
2416 | |||||||
2417 | /// Merge alignment attributes from \p Old to \p New, taking into account the | ||||||
2418 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. | ||||||
2419 | /// | ||||||
2420 | /// \return \c true if any attributes were added to \p New. | ||||||
2421 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { | ||||||
2422 | // Look for alignas attributes on Old, and pick out whichever attribute | ||||||
2423 | // specifies the strictest alignment requirement. | ||||||
2424 | AlignedAttr *OldAlignasAttr = nullptr; | ||||||
2425 | AlignedAttr *OldStrictestAlignAttr = nullptr; | ||||||
2426 | unsigned OldAlign = 0; | ||||||
2427 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { | ||||||
2428 | // FIXME: We have no way of representing inherited dependent alignments | ||||||
2429 | // in a case like: | ||||||
2430 | // template<int A, int B> struct alignas(A) X; | ||||||
2431 | // template<int A, int B> struct alignas(B) X {}; | ||||||
2432 | // For now, we just ignore any alignas attributes which are not on the | ||||||
2433 | // definition in such a case. | ||||||
2434 | if (I->isAlignmentDependent()) | ||||||
2435 | return false; | ||||||
2436 | |||||||
2437 | if (I->isAlignas()) | ||||||
2438 | OldAlignasAttr = I; | ||||||
2439 | |||||||
2440 | unsigned Align = I->getAlignment(S.Context); | ||||||
2441 | if (Align > OldAlign) { | ||||||
2442 | OldAlign = Align; | ||||||
2443 | OldStrictestAlignAttr = I; | ||||||
2444 | } | ||||||
2445 | } | ||||||
2446 | |||||||
2447 | // Look for alignas attributes on New. | ||||||
2448 | AlignedAttr *NewAlignasAttr = nullptr; | ||||||
2449 | unsigned NewAlign = 0; | ||||||
2450 | for (auto *I : New->specific_attrs<AlignedAttr>()) { | ||||||
2451 | if (I->isAlignmentDependent()) | ||||||
2452 | return false; | ||||||
2453 | |||||||
2454 | if (I->isAlignas()) | ||||||
2455 | NewAlignasAttr = I; | ||||||
2456 | |||||||
2457 | unsigned Align = I->getAlignment(S.Context); | ||||||
2458 | if (Align > NewAlign) | ||||||
2459 | NewAlign = Align; | ||||||
2460 | } | ||||||
2461 | |||||||
2462 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { | ||||||
2463 | // Both declarations have 'alignas' attributes. We require them to match. | ||||||
2464 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but | ||||||
2465 | // fall short. (If two declarations both have alignas, they must both match | ||||||
2466 | // every definition, and so must match each other if there is a definition.) | ||||||
2467 | |||||||
2468 | // If either declaration only contains 'alignas(0)' specifiers, then it | ||||||
2469 | // specifies the natural alignment for the type. | ||||||
2470 | if (OldAlign == 0 || NewAlign == 0) { | ||||||
2471 | QualType Ty; | ||||||
2472 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) | ||||||
2473 | Ty = VD->getType(); | ||||||
2474 | else | ||||||
2475 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); | ||||||
2476 | |||||||
2477 | if (OldAlign == 0) | ||||||
2478 | OldAlign = S.Context.getTypeAlign(Ty); | ||||||
2479 | if (NewAlign == 0) | ||||||
2480 | NewAlign = S.Context.getTypeAlign(Ty); | ||||||
2481 | } | ||||||
2482 | |||||||
2483 | if (OldAlign != NewAlign) { | ||||||
2484 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) | ||||||
2485 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() | ||||||
2486 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); | ||||||
2487 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); | ||||||
2488 | } | ||||||
2489 | } | ||||||
2490 | |||||||
2491 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { | ||||||
2492 | // C++11 [dcl.align]p6: | ||||||
2493 | // if any declaration of an entity has an alignment-specifier, | ||||||
2494 | // every defining declaration of that entity shall specify an | ||||||
2495 | // equivalent alignment. | ||||||
2496 | // C11 6.7.5/7: | ||||||
2497 | // If the definition of an object does not have an alignment | ||||||
2498 | // specifier, any other declaration of that object shall also | ||||||
2499 | // have no alignment specifier. | ||||||
2500 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) | ||||||
2501 | << OldAlignasAttr; | ||||||
2502 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) | ||||||
2503 | << OldAlignasAttr; | ||||||
2504 | } | ||||||
2505 | |||||||
2506 | bool AnyAdded = false; | ||||||
2507 | |||||||
2508 | // Ensure we have an attribute representing the strictest alignment. | ||||||
2509 | if (OldAlign > NewAlign) { | ||||||
2510 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); | ||||||
2511 | Clone->setInherited(true); | ||||||
2512 | New->addAttr(Clone); | ||||||
2513 | AnyAdded = true; | ||||||
2514 | } | ||||||
2515 | |||||||
2516 | // Ensure we have an alignas attribute if the old declaration had one. | ||||||
2517 | if (OldAlignasAttr && !NewAlignasAttr && | ||||||
2518 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { | ||||||
2519 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); | ||||||
2520 | Clone->setInherited(true); | ||||||
2521 | New->addAttr(Clone); | ||||||
2522 | AnyAdded = true; | ||||||
2523 | } | ||||||
2524 | |||||||
2525 | return AnyAdded; | ||||||
2526 | } | ||||||
2527 | |||||||
2528 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, | ||||||
2529 | const InheritableAttr *Attr, | ||||||
2530 | Sema::AvailabilityMergeKind AMK) { | ||||||
2531 | // This function copies an attribute Attr from a previous declaration to the | ||||||
2532 | // new declaration D if the new declaration doesn't itself have that attribute | ||||||
2533 | // yet or if that attribute allows duplicates. | ||||||
2534 | // If you're adding a new attribute that requires logic different from | ||||||
2535 | // "use explicit attribute on decl if present, else use attribute from | ||||||
2536 | // previous decl", for example if the attribute needs to be consistent | ||||||
2537 | // between redeclarations, you need to call a custom merge function here. | ||||||
2538 | InheritableAttr *NewAttr = nullptr; | ||||||
2539 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) | ||||||
2540 | NewAttr = S.mergeAvailabilityAttr( | ||||||
2541 | D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), | ||||||
2542 | AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), | ||||||
2543 | AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, | ||||||
2544 | AA->getPriority()); | ||||||
2545 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) | ||||||
2546 | NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||||
2547 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) | ||||||
2548 | NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||||
2549 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) | ||||||
2550 | NewAttr = S.mergeDLLImportAttr(D, *ImportA); | ||||||
2551 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) | ||||||
2552 | NewAttr = S.mergeDLLExportAttr(D, *ExportA); | ||||||
2553 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) | ||||||
2554 | NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), | ||||||
2555 | FA->getFirstArg()); | ||||||
2556 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) | ||||||
2557 | NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); | ||||||
2558 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) | ||||||
2559 | NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); | ||||||
2560 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) | ||||||
2561 | NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), | ||||||
2562 | IA->getInheritanceModel()); | ||||||
2563 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) | ||||||
2564 | NewAttr = S.mergeAlwaysInlineAttr(D, *AA, | ||||||
2565 | &S.Context.Idents.get(AA->getSpelling())); | ||||||
2566 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && | ||||||
2567 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || | ||||||
2568 | isa<CUDAGlobalAttr>(Attr))) { | ||||||
2569 | // CUDA target attributes are part of function signature for | ||||||
2570 | // overloading purposes and must not be merged. | ||||||
2571 | return false; | ||||||
2572 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) | ||||||
2573 | NewAttr = S.mergeMinSizeAttr(D, *MA); | ||||||
2574 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) | ||||||
2575 | NewAttr = S.mergeOptimizeNoneAttr(D, *OA); | ||||||
2576 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) | ||||||
2577 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); | ||||||
2578 | else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) | ||||||
2579 | NewAttr = S.mergeCommonAttr(D, *CommonA); | ||||||
2580 | else if (isa<AlignedAttr>(Attr)) | ||||||
2581 | // AlignedAttrs are handled separately, because we need to handle all | ||||||
2582 | // such attributes on a declaration at the same time. | ||||||
2583 | NewAttr = nullptr; | ||||||
2584 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && | ||||||
2585 | (AMK == Sema::AMK_Override || | ||||||
2586 | AMK == Sema::AMK_ProtocolImplementation)) | ||||||
2587 | NewAttr = nullptr; | ||||||
2588 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) | ||||||
2589 | NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); | ||||||
2590 | else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) | ||||||
2591 | NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); | ||||||
2592 | else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) | ||||||
2593 | NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); | ||||||
2594 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) | ||||||
2595 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); | ||||||
2596 | |||||||
2597 | if (NewAttr) { | ||||||
2598 | NewAttr->setInherited(true); | ||||||
2599 | D->addAttr(NewAttr); | ||||||
2600 | if (isa<MSInheritanceAttr>(NewAttr)) | ||||||
2601 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); | ||||||
2602 | return true; | ||||||
2603 | } | ||||||
2604 | |||||||
2605 | return false; | ||||||
2606 | } | ||||||
2607 | |||||||
2608 | static const NamedDecl *getDefinition(const Decl *D) { | ||||||
2609 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||||
2610 | return TD->getDefinition(); | ||||||
2611 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
2612 | const VarDecl *Def = VD->getDefinition(); | ||||||
2613 | if (Def) | ||||||
2614 | return Def; | ||||||
2615 | return VD->getActingDefinition(); | ||||||
2616 | } | ||||||
2617 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) | ||||||
2618 | return FD->getDefinition(); | ||||||
2619 | return nullptr; | ||||||
2620 | } | ||||||
2621 | |||||||
2622 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { | ||||||
2623 | for (const auto *Attribute : D->attrs()) | ||||||
2624 | if (Attribute->getKind() == Kind) | ||||||
2625 | return true; | ||||||
2626 | return false; | ||||||
2627 | } | ||||||
2628 | |||||||
2629 | /// checkNewAttributesAfterDef - If we already have a definition, check that | ||||||
2630 | /// there are no new attributes in this declaration. | ||||||
2631 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { | ||||||
2632 | if (!New->hasAttrs()) | ||||||
2633 | return; | ||||||
2634 | |||||||
2635 | const NamedDecl *Def = getDefinition(Old); | ||||||
2636 | if (!Def || Def == New) | ||||||
2637 | return; | ||||||
2638 | |||||||
2639 | AttrVec &NewAttributes = New->getAttrs(); | ||||||
2640 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { | ||||||
2641 | const Attr *NewAttribute = NewAttributes[I]; | ||||||
2642 | |||||||
2643 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { | ||||||
2644 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { | ||||||
2645 | Sema::SkipBodyInfo SkipBody; | ||||||
2646 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); | ||||||
2647 | |||||||
2648 | // If we're skipping this definition, drop the "alias" attribute. | ||||||
2649 | if (SkipBody.ShouldSkip) { | ||||||
2650 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2651 | --E; | ||||||
2652 | continue; | ||||||
2653 | } | ||||||
2654 | } else { | ||||||
2655 | VarDecl *VD = cast<VarDecl>(New); | ||||||
2656 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == | ||||||
2657 | VarDecl::TentativeDefinition | ||||||
2658 | ? diag::err_alias_after_tentative | ||||||
2659 | : diag::err_redefinition; | ||||||
2660 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); | ||||||
2661 | if (Diag == diag::err_redefinition) | ||||||
2662 | S.notePreviousDefinition(Def, VD->getLocation()); | ||||||
2663 | else | ||||||
2664 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
2665 | VD->setInvalidDecl(); | ||||||
2666 | } | ||||||
2667 | ++I; | ||||||
2668 | continue; | ||||||
2669 | } | ||||||
2670 | |||||||
2671 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { | ||||||
2672 | // Tentative definitions are only interesting for the alias check above. | ||||||
2673 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { | ||||||
2674 | ++I; | ||||||
2675 | continue; | ||||||
2676 | } | ||||||
2677 | } | ||||||
2678 | |||||||
2679 | if (hasAttribute(Def, NewAttribute->getKind())) { | ||||||
2680 | ++I; | ||||||
2681 | continue; // regular attr merging will take care of validating this. | ||||||
2682 | } | ||||||
2683 | |||||||
2684 | if (isa<C11NoReturnAttr>(NewAttribute)) { | ||||||
2685 | // C's _Noreturn is allowed to be added to a function after it is defined. | ||||||
2686 | ++I; | ||||||
2687 | continue; | ||||||
2688 | } else if (isa<UuidAttr>(NewAttribute)) { | ||||||
2689 | // msvc will allow a subsequent definition to add an uuid to a class | ||||||
2690 | ++I; | ||||||
2691 | continue; | ||||||
2692 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { | ||||||
2693 | if (AA->isAlignas()) { | ||||||
2694 | // C++11 [dcl.align]p6: | ||||||
2695 | // if any declaration of an entity has an alignment-specifier, | ||||||
2696 | // every defining declaration of that entity shall specify an | ||||||
2697 | // equivalent alignment. | ||||||
2698 | // C11 6.7.5/7: | ||||||
2699 | // If the definition of an object does not have an alignment | ||||||
2700 | // specifier, any other declaration of that object shall also | ||||||
2701 | // have no alignment specifier. | ||||||
2702 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) | ||||||
2703 | << AA; | ||||||
2704 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) | ||||||
2705 | << AA; | ||||||
2706 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2707 | --E; | ||||||
2708 | continue; | ||||||
2709 | } | ||||||
2710 | } else if (isa<SelectAnyAttr>(NewAttribute) && | ||||||
2711 | cast<VarDecl>(New)->isInline() && | ||||||
2712 | !cast<VarDecl>(New)->isInlineSpecified()) { | ||||||
2713 | // Don't warn about applying selectany to implicitly inline variables. | ||||||
2714 | // Older compilers and language modes would require the use of selectany | ||||||
2715 | // to make such variables inline, and it would have no effect if we | ||||||
2716 | // honored it. | ||||||
2717 | ++I; | ||||||
2718 | continue; | ||||||
2719 | } | ||||||
2720 | |||||||
2721 | S.Diag(NewAttribute->getLocation(), | ||||||
2722 | diag::warn_attribute_precede_definition); | ||||||
2723 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
2724 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2725 | --E; | ||||||
2726 | } | ||||||
2727 | } | ||||||
2728 | |||||||
2729 | static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, | ||||||
2730 | const ConstInitAttr *CIAttr, | ||||||
2731 | bool AttrBeforeInit) { | ||||||
2732 | SourceLocation InsertLoc = InitDecl->getInnerLocStart(); | ||||||
2733 | |||||||
2734 | // Figure out a good way to write this specifier on the old declaration. | ||||||
2735 | // FIXME: We should just use the spelling of CIAttr, but we don't preserve | ||||||
2736 | // enough of the attribute list spelling information to extract that without | ||||||
2737 | // heroics. | ||||||
2738 | std::string SuitableSpelling; | ||||||
2739 | if (S.getLangOpts().CPlusPlus2a) | ||||||
2740 | SuitableSpelling = | ||||||
2741 | S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}); | ||||||
2742 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||||
2743 | SuitableSpelling = S.PP.getLastMacroWithSpelling( | ||||||
2744 | InsertLoc, | ||||||
2745 | {tok::l_square, tok::l_square, S.PP.getIdentifierInfo("clang"), | ||||||
2746 | tok::coloncolon, | ||||||
2747 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||||
2748 | tok::r_square, tok::r_square}); | ||||||
2749 | if (SuitableSpelling.empty()) | ||||||
2750 | SuitableSpelling = S.PP.getLastMacroWithSpelling( | ||||||
2751 | InsertLoc, | ||||||
2752 | {tok::kw___attribute, tok::l_paren, tok::r_paren, | ||||||
2753 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||||
2754 | tok::r_paren, tok::r_paren}); | ||||||
2755 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) | ||||||
2756 | SuitableSpelling = "constinit"; | ||||||
2757 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||||
2758 | SuitableSpelling = "[[clang::require_constant_initialization]]"; | ||||||
2759 | if (SuitableSpelling.empty()) | ||||||
2760 | SuitableSpelling = "__attribute__((require_constant_initialization))"; | ||||||
2761 | SuitableSpelling += " "; | ||||||
2762 | |||||||
2763 | if (AttrBeforeInit) { | ||||||
2764 | // extern constinit int a; | ||||||
2765 | // int a = 0; // error (missing 'constinit'), accepted as extension | ||||||
2766 | assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((CIAttr->isConstinit() && "should not diagnose this for attribute" ) ? static_cast<void> (0) : __assert_fail ("CIAttr->isConstinit() && \"should not diagnose this for attribute\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 2766, __PRETTY_FUNCTION__)); | ||||||
2767 | S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) | ||||||
2768 | << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||||
2769 | S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); | ||||||
2770 | } else { | ||||||
2771 | // int a = 0; | ||||||
2772 | // constinit extern int a; // error (missing 'constinit') | ||||||
2773 | S.Diag(CIAttr->getLocation(), | ||||||
2774 | CIAttr->isConstinit() ? diag::err_constinit_added_too_late | ||||||
2775 | : diag::warn_require_const_init_added_too_late) | ||||||
2776 | << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); | ||||||
2777 | S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) | ||||||
2778 | << CIAttr->isConstinit() | ||||||
2779 | << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||||
2780 | } | ||||||
2781 | } | ||||||
2782 | |||||||
2783 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. | ||||||
2784 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, | ||||||
2785 | AvailabilityMergeKind AMK) { | ||||||
2786 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { | ||||||
2787 | UsedAttr *NewAttr = OldAttr->clone(Context); | ||||||
2788 | NewAttr->setInherited(true); | ||||||
2789 | New->addAttr(NewAttr); | ||||||
2790 | } | ||||||
2791 | |||||||
2792 | if (!Old->hasAttrs() && !New->hasAttrs()) | ||||||
2793 | return; | ||||||
2794 | |||||||
2795 | // [dcl.constinit]p1: | ||||||
2796 | // If the [constinit] specifier is applied to any declaration of a | ||||||
2797 | // variable, it shall be applied to the initializing declaration. | ||||||
2798 | const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); | ||||||
2799 | const auto *NewConstInit = New->getAttr<ConstInitAttr>(); | ||||||
2800 | if (bool(OldConstInit) != bool(NewConstInit)) { | ||||||
2801 | const auto *OldVD = cast<VarDecl>(Old); | ||||||
2802 | auto *NewVD = cast<VarDecl>(New); | ||||||
2803 | |||||||
2804 | // Find the initializing declaration. Note that we might not have linked | ||||||
2805 | // the new declaration into the redeclaration chain yet. | ||||||
2806 | const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); | ||||||
2807 | if (!InitDecl && | ||||||
2808 | (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) | ||||||
2809 | InitDecl = NewVD; | ||||||
2810 | |||||||
2811 | if (InitDecl == NewVD) { | ||||||
2812 | // This is the initializing declaration. If it would inherit 'constinit', | ||||||
2813 | // that's ill-formed. (Note that we do not apply this to the attribute | ||||||
2814 | // form). | ||||||
2815 | if (OldConstInit && OldConstInit->isConstinit()) | ||||||
2816 | diagnoseMissingConstinit(*this, NewVD, OldConstInit, | ||||||
2817 | /*AttrBeforeInit=*/true); | ||||||
2818 | } else if (NewConstInit) { | ||||||
2819 | // This is the first time we've been told that this declaration should | ||||||
2820 | // have a constant initializer. If we already saw the initializing | ||||||
2821 | // declaration, this is too late. | ||||||
2822 | if (InitDecl && InitDecl != NewVD) { | ||||||
2823 | diagnoseMissingConstinit(*this, InitDecl, NewConstInit, | ||||||
2824 | /*AttrBeforeInit=*/false); | ||||||
2825 | NewVD->dropAttr<ConstInitAttr>(); | ||||||
2826 | } | ||||||
2827 | } | ||||||
2828 | } | ||||||
2829 | |||||||
2830 | // Attributes declared post-definition are currently ignored. | ||||||
2831 | checkNewAttributesAfterDef(*this, New, Old); | ||||||
2832 | |||||||
2833 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { | ||||||
2834 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { | ||||||
2835 | if (!OldA->isEquivalent(NewA)) { | ||||||
2836 | // This redeclaration changes __asm__ label. | ||||||
2837 | Diag(New->getLocation(), diag::err_different_asm_label); | ||||||
2838 | Diag(OldA->getLocation(), diag::note_previous_declaration); | ||||||
2839 | } | ||||||
2840 | } else if (Old->isUsed()) { | ||||||
2841 | // This redeclaration adds an __asm__ label to a declaration that has | ||||||
2842 | // already been ODR-used. | ||||||
2843 | Diag(New->getLocation(), diag::err_late_asm_label_name) | ||||||
2844 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); | ||||||
2845 | } | ||||||
2846 | } | ||||||
2847 | |||||||
2848 | // Re-declaration cannot add abi_tag's. | ||||||
2849 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { | ||||||
2850 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { | ||||||
2851 | for (const auto &NewTag : NewAbiTagAttr->tags()) { | ||||||
2852 | if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), | ||||||
2853 | NewTag) == OldAbiTagAttr->tags_end()) { | ||||||
2854 | Diag(NewAbiTagAttr->getLocation(), | ||||||
2855 | diag::err_new_abi_tag_on_redeclaration) | ||||||
2856 | << NewTag; | ||||||
2857 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); | ||||||
2858 | } | ||||||
2859 | } | ||||||
2860 | } else { | ||||||
2861 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); | ||||||
2862 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2863 | } | ||||||
2864 | } | ||||||
2865 | |||||||
2866 | // This redeclaration adds a section attribute. | ||||||
2867 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { | ||||||
2868 | if (auto *VD = dyn_cast<VarDecl>(New)) { | ||||||
2869 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { | ||||||
2870 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); | ||||||
2871 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2872 | } | ||||||
2873 | } | ||||||
2874 | } | ||||||
2875 | |||||||
2876 | // Redeclaration adds code-seg attribute. | ||||||
2877 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | ||||||
2878 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && | ||||||
2879 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { | ||||||
2880 | Diag(New->getLocation(), diag::warn_mismatched_section) | ||||||
2881 | << 0 /*codeseg*/; | ||||||
2882 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2883 | } | ||||||
2884 | |||||||
2885 | if (!Old->hasAttrs()) | ||||||
2886 | return; | ||||||
2887 | |||||||
2888 | bool foundAny = New->hasAttrs(); | ||||||
2889 | |||||||
2890 | // Ensure that any moving of objects within the allocated map is done before | ||||||
2891 | // we process them. | ||||||
2892 | if (!foundAny) New->setAttrs(AttrVec()); | ||||||
2893 | |||||||
2894 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { | ||||||
2895 | // Ignore deprecated/unavailable/availability attributes if requested. | ||||||
2896 | AvailabilityMergeKind LocalAMK = AMK_None; | ||||||
2897 | if (isa<DeprecatedAttr>(I) || | ||||||
2898 | isa<UnavailableAttr>(I) || | ||||||
2899 | isa<AvailabilityAttr>(I)) { | ||||||
2900 | switch (AMK) { | ||||||
2901 | case AMK_None: | ||||||
2902 | continue; | ||||||
2903 | |||||||
2904 | case AMK_Redeclaration: | ||||||
2905 | case AMK_Override: | ||||||
2906 | case AMK_ProtocolImplementation: | ||||||
2907 | LocalAMK = AMK; | ||||||
2908 | break; | ||||||
2909 | } | ||||||
2910 | } | ||||||
2911 | |||||||
2912 | // Already handled. | ||||||
2913 | if (isa<UsedAttr>(I)) | ||||||
2914 | continue; | ||||||
2915 | |||||||
2916 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) | ||||||
2917 | foundAny = true; | ||||||
2918 | } | ||||||
2919 | |||||||
2920 | if (mergeAlignedAttrs(*this, New, Old)) | ||||||
2921 | foundAny = true; | ||||||
2922 | |||||||
2923 | if (!foundAny) New->dropAttrs(); | ||||||
2924 | } | ||||||
2925 | |||||||
2926 | /// mergeParamDeclAttributes - Copy attributes from the old parameter | ||||||
2927 | /// to the new one. | ||||||
2928 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, | ||||||
2929 | const ParmVarDecl *oldDecl, | ||||||
2930 | Sema &S) { | ||||||
2931 | // C++11 [dcl.attr.depend]p2: | ||||||
2932 | // The first declaration of a function shall specify the | ||||||
2933 | // carries_dependency attribute for its declarator-id if any declaration | ||||||
2934 | // of the function specifies the carries_dependency attribute. | ||||||
2935 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); | ||||||
2936 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { | ||||||
2937 | S.Diag(CDA->getLocation(), | ||||||
2938 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; | ||||||
2939 | // Find the first declaration of the parameter. | ||||||
2940 | // FIXME: Should we build redeclaration chains for function parameters? | ||||||
2941 | const FunctionDecl *FirstFD = | ||||||
2942 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); | ||||||
2943 | const ParmVarDecl *FirstVD = | ||||||
2944 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); | ||||||
2945 | S.Diag(FirstVD->getLocation(), | ||||||
2946 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; | ||||||
2947 | } | ||||||
2948 | |||||||
2949 | if (!oldDecl->hasAttrs()) | ||||||
2950 | return; | ||||||
2951 | |||||||
2952 | bool foundAny = newDecl->hasAttrs(); | ||||||
2953 | |||||||
2954 | // Ensure that any moving of objects within the allocated map is | ||||||
2955 | // done before we process them. | ||||||
2956 | if (!foundAny) newDecl->setAttrs(AttrVec()); | ||||||
2957 | |||||||
2958 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { | ||||||
2959 | if (!DeclHasAttr(newDecl, I)) { | ||||||
2960 | InheritableAttr *newAttr = | ||||||
2961 | cast<InheritableParamAttr>(I->clone(S.Context)); | ||||||
2962 | newAttr->setInherited(true); | ||||||
2963 | newDecl->addAttr(newAttr); | ||||||
2964 | foundAny = true; | ||||||
2965 | } | ||||||
2966 | } | ||||||
2967 | |||||||
2968 | if (!foundAny) newDecl->dropAttrs(); | ||||||
2969 | } | ||||||
2970 | |||||||
2971 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, | ||||||
2972 | const ParmVarDecl *OldParam, | ||||||
2973 | Sema &S) { | ||||||
2974 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { | ||||||
2975 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { | ||||||
2976 | if (*Oldnullability != *Newnullability) { | ||||||
2977 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) | ||||||
2978 | << DiagNullabilityKind( | ||||||
2979 | *Newnullability, | ||||||
2980 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||||
2981 | != 0)) | ||||||
2982 | << DiagNullabilityKind( | ||||||
2983 | *Oldnullability, | ||||||
2984 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||||
2985 | != 0)); | ||||||
2986 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); | ||||||
2987 | } | ||||||
2988 | } else { | ||||||
2989 | QualType NewT = NewParam->getType(); | ||||||
2990 | NewT = S.Context.getAttributedType( | ||||||
2991 | AttributedType::getNullabilityAttrKind(*Oldnullability), | ||||||
2992 | NewT, NewT); | ||||||
2993 | NewParam->setType(NewT); | ||||||
2994 | } | ||||||
2995 | } | ||||||
2996 | } | ||||||
2997 | |||||||
2998 | namespace { | ||||||
2999 | |||||||
3000 | /// Used in MergeFunctionDecl to keep track of function parameters in | ||||||
3001 | /// C. | ||||||
3002 | struct GNUCompatibleParamWarning { | ||||||
3003 | ParmVarDecl *OldParm; | ||||||
3004 | ParmVarDecl *NewParm; | ||||||
3005 | QualType PromotedType; | ||||||
3006 | }; | ||||||
3007 | |||||||
3008 | } // end anonymous namespace | ||||||
3009 | |||||||
3010 | // Determine whether the previous declaration was a definition, implicit | ||||||
3011 | // declaration, or a declaration. | ||||||
3012 | template <typename T> | ||||||
3013 | static std::pair<diag::kind, SourceLocation> | ||||||
3014 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { | ||||||
3015 | diag::kind PrevDiag; | ||||||
3016 | SourceLocation OldLocation = Old->getLocation(); | ||||||
3017 | if (Old->isThisDeclarationADefinition()) | ||||||
3018 | PrevDiag = diag::note_previous_definition; | ||||||
3019 | else if (Old->isImplicit()) { | ||||||
3020 | PrevDiag = diag::note_previous_implicit_declaration; | ||||||
3021 | if (OldLocation.isInvalid()) | ||||||
3022 | OldLocation = New->getLocation(); | ||||||
3023 | } else | ||||||
3024 | PrevDiag = diag::note_previous_declaration; | ||||||
3025 | return std::make_pair(PrevDiag, OldLocation); | ||||||
3026 | } | ||||||
3027 | |||||||
3028 | /// canRedefineFunction - checks if a function can be redefined. Currently, | ||||||
3029 | /// only extern inline functions can be redefined, and even then only in | ||||||
3030 | /// GNU89 mode. | ||||||
3031 | static bool canRedefineFunction(const FunctionDecl *FD, | ||||||
3032 | const LangOptions& LangOpts) { | ||||||
3033 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && | ||||||
3034 | !LangOpts.CPlusPlus && | ||||||
3035 | FD->isInlineSpecified() && | ||||||
3036 | FD->getStorageClass() == SC_Extern); | ||||||
3037 | } | ||||||
3038 | |||||||
3039 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { | ||||||
3040 | const AttributedType *AT = T->getAs<AttributedType>(); | ||||||
3041 | while (AT && !AT->isCallingConv()) | ||||||
3042 | AT = AT->getModifiedType()->getAs<AttributedType>(); | ||||||
3043 | return AT; | ||||||
3044 | } | ||||||
3045 | |||||||
3046 | template <typename T> | ||||||
3047 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { | ||||||
3048 | const DeclContext *DC = Old->getDeclContext(); | ||||||
3049 | if (DC->isRecord()) | ||||||
3050 | return false; | ||||||
3051 | |||||||
3052 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); | ||||||
3053 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) | ||||||
3054 | return true; | ||||||
3055 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) | ||||||
3056 | return true; | ||||||
3057 | return false; | ||||||
3058 | } | ||||||
3059 | |||||||
3060 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } | ||||||
3061 | static bool isExternC(VarTemplateDecl *) { return false; } | ||||||
3062 | |||||||
3063 | /// Check whether a redeclaration of an entity introduced by a | ||||||
3064 | /// using-declaration is valid, given that we know it's not an overload | ||||||
3065 | /// (nor a hidden tag declaration). | ||||||
3066 | template<typename ExpectedDecl> | ||||||
3067 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, | ||||||
3068 | ExpectedDecl *New) { | ||||||
3069 | // C++11 [basic.scope.declarative]p4: | ||||||
3070 | // Given a set of declarations in a single declarative region, each of | ||||||
3071 | // which specifies the same unqualified name, | ||||||
3072 | // -- they shall all refer to the same entity, or all refer to functions | ||||||
3073 | // and function templates; or | ||||||
3074 | // -- exactly one declaration shall declare a class name or enumeration | ||||||
3075 | // name that is not a typedef name and the other declarations shall all | ||||||
3076 | // refer to the same variable or enumerator, or all refer to functions | ||||||
3077 | // and function templates; in this case the class name or enumeration | ||||||
3078 | // name is hidden (3.3.10). | ||||||
3079 | |||||||
3080 | // C++11 [namespace.udecl]p14: | ||||||
3081 | // If a function declaration in namespace scope or block scope has the | ||||||
3082 | // same name and the same parameter-type-list as a function introduced | ||||||
3083 | // by a using-declaration, and the declarations do not declare the same | ||||||
3084 | // function, the program is ill-formed. | ||||||
3085 | |||||||
3086 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); | ||||||
3087 | if (Old && | ||||||
3088 | !Old->getDeclContext()->getRedeclContext()->Equals( | ||||||
3089 | New->getDeclContext()->getRedeclContext()) && | ||||||
3090 | !(isExternC(Old) && isExternC(New))) | ||||||
3091 | Old = nullptr; | ||||||
3092 | |||||||
3093 | if (!Old) { | ||||||
3094 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); | ||||||
3095 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); | ||||||
3096 | S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; | ||||||
3097 | return true; | ||||||
3098 | } | ||||||
3099 | return false; | ||||||
3100 | } | ||||||
3101 | |||||||
3102 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, | ||||||
3103 | const FunctionDecl *B) { | ||||||
3104 | assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast <void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 3104, __PRETTY_FUNCTION__)); | ||||||
3105 | |||||||
3106 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { | ||||||
3107 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); | ||||||
3108 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); | ||||||
3109 | if (AttrA == AttrB) | ||||||
3110 | return true; | ||||||
3111 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && | ||||||
3112 | AttrA->isDynamic() == AttrB->isDynamic(); | ||||||
3113 | }; | ||||||
3114 | |||||||
3115 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); | ||||||
3116 | } | ||||||
3117 | |||||||
3118 | /// If necessary, adjust the semantic declaration context for a qualified | ||||||
3119 | /// declaration to name the correct inline namespace within the qualifier. | ||||||
3120 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, | ||||||
3121 | DeclaratorDecl *OldD) { | ||||||
3122 | // The only case where we need to update the DeclContext is when | ||||||
3123 | // redeclaration lookup for a qualified name finds a declaration | ||||||
3124 | // in an inline namespace within the context named by the qualifier: | ||||||
3125 | // | ||||||
3126 | // inline namespace N { int f(); } | ||||||
3127 | // int ::f(); // Sema DC needs adjusting from :: to N::. | ||||||
3128 | // | ||||||
3129 | // For unqualified declarations, the semantic context *can* change | ||||||
3130 | // along the redeclaration chain (for local extern declarations, | ||||||
3131 | // extern "C" declarations, and friend declarations in particular). | ||||||
3132 | if (!NewD->getQualifier()) | ||||||
3133 | return; | ||||||
3134 | |||||||
3135 | // NewD is probably already in the right context. | ||||||
3136 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); | ||||||
3137 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); | ||||||
3138 | if (NamedDC->Equals(SemaDC)) | ||||||
3139 | return; | ||||||
3140 | |||||||
3141 | assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 3143, __PRETTY_FUNCTION__)) | ||||||
3142 | NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 3143, __PRETTY_FUNCTION__)) | ||||||
3143 | "unexpected context for redeclaration")(((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD-> isInvalidDecl() || OldD->isInvalidDecl()) && "unexpected context for redeclaration" ) ? static_cast<void> (0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 3143, __PRETTY_FUNCTION__)); | ||||||
3144 | |||||||
3145 | auto *LexDC = NewD->getLexicalDeclContext(); | ||||||
3146 | auto FixSemaDC = [=](NamedDecl *D) { | ||||||
3147 | if (!D) | ||||||
3148 | return; | ||||||
3149 | D->setDeclContext(SemaDC); | ||||||
3150 | D->setLexicalDeclContext(LexDC); | ||||||
3151 | }; | ||||||
3152 | |||||||
3153 | FixSemaDC(NewD); | ||||||
3154 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) | ||||||
3155 | FixSemaDC(FD->getDescribedFunctionTemplate()); | ||||||
3156 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) | ||||||
3157 | FixSemaDC(VD->getDescribedVarTemplate()); | ||||||
3158 | } | ||||||
3159 | |||||||
3160 | /// MergeFunctionDecl - We just parsed a function 'New' from | ||||||
3161 | /// declarator D which has the same name and scope as a previous | ||||||
3162 | /// declaration 'Old'. Figure out how to resolve this situation, | ||||||
3163 | /// merging decls or emitting diagnostics as appropriate. | ||||||
3164 | /// | ||||||
3165 | /// In C++, New and Old must be declarations that are not | ||||||
3166 | /// overloaded. Use IsOverload to determine whether New and Old are | ||||||
3167 | /// overloaded, and to select the Old declaration that New should be | ||||||
3168 | /// merged with. | ||||||
3169 | /// | ||||||
3170 | /// Returns true if there was an error, false otherwise. | ||||||
3171 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, | ||||||
3172 | Scope *S, bool MergeTypeWithOld) { | ||||||
3173 | // Verify the old decl was also a function. | ||||||
3174 | FunctionDecl *Old = OldD->getAsFunction(); | ||||||
3175 | if (!Old) { | ||||||
3176 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { | ||||||
3177 | if (New->getFriendObjectKind()) { | ||||||
3178 | Diag(New->getLocation(), diag::err_using_decl_friend); | ||||||
3179 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||||
3180 | diag::note_using_decl_target); | ||||||
3181 | Diag(Shadow->getUsingDecl()->getLocation(), | ||||||
3182 | diag::note_using_decl) << 0; | ||||||
3183 | return true; | ||||||
3184 | } | ||||||
3185 | |||||||
3186 | // Check whether the two declarations might declare the same function. | ||||||
3187 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) | ||||||
3188 | return true; | ||||||
3189 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); | ||||||
3190 | } else { | ||||||
3191 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
3192 | << New->getDeclName(); | ||||||
3193 | notePreviousDefinition(OldD, New->getLocation()); | ||||||
3194 | return true; | ||||||
3195 | } | ||||||
3196 | } | ||||||
3197 | |||||||
3198 | // If the old declaration is invalid, just give up here. | ||||||
3199 | if (Old->isInvalidDecl()) | ||||||
3200 | return true; | ||||||
3201 | |||||||
3202 | // Disallow redeclaration of some builtins. | ||||||
3203 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { | ||||||
3204 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); | ||||||
3205 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) | ||||||
3206 | << Old << Old->getType(); | ||||||
3207 | return true; | ||||||
3208 | } | ||||||
3209 | |||||||
3210 | diag::kind PrevDiag; | ||||||
3211 | SourceLocation OldLocation; | ||||||
3212 | std::tie(PrevDiag, OldLocation) = | ||||||
3213 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
3214 | |||||||
3215 | // Don't complain about this if we're in GNU89 mode and the old function | ||||||
3216 | // is an extern inline function. | ||||||
3217 | // Don't complain about specializations. They are not supposed to have | ||||||
3218 | // storage classes. | ||||||
3219 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && | ||||||
3220 | New->getStorageClass() == SC_Static && | ||||||
3221 | Old->hasExternalFormalLinkage() && | ||||||
3222 | !New->getTemplateSpecializationInfo() && | ||||||
3223 | !canRedefineFunction(Old, getLangOpts())) { | ||||||
3224 | if (getLangOpts().MicrosoftExt) { | ||||||
3225 | Diag(New->getLocation(), diag::ext_static_non_static) << New; | ||||||
3226 | Diag(OldLocation, PrevDiag); | ||||||
3227 | } else { | ||||||
3228 | Diag(New->getLocation(), diag::err_static_non_static) << New; | ||||||
3229 | Diag(OldLocation, PrevDiag); | ||||||
3230 | return true; | ||||||
3231 | } | ||||||
3232 | } | ||||||
3233 | |||||||
3234 | if (New->hasAttr<InternalLinkageAttr>() && | ||||||
3235 | !Old->hasAttr<InternalLinkageAttr>()) { | ||||||
3236 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | ||||||
3237 | << New->getDeclName(); | ||||||
3238 | notePreviousDefinition(Old, New->getLocation()); | ||||||
3239 | New->dropAttr<InternalLinkageAttr>(); | ||||||
3240 | } | ||||||
3241 | |||||||
3242 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||||
3243 | return true; | ||||||
3244 | |||||||
3245 | if (!getLangOpts().CPlusPlus) { | ||||||
3246 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); | ||||||
3247 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { | ||||||
3248 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) | ||||||
3249 | << New << OldOvl; | ||||||
3250 | |||||||
3251 | // Try our best to find a decl that actually has the overloadable | ||||||
3252 | // attribute for the note. In most cases (e.g. programs with only one | ||||||
3253 | // broken declaration/definition), this won't matter. | ||||||
3254 | // | ||||||
3255 | // FIXME: We could do this if we juggled some extra state in | ||||||
3256 | // OverloadableAttr, rather than just removing it. | ||||||
3257 | const Decl *DiagOld = Old; | ||||||
3258 | if (OldOvl) { | ||||||
3259 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { | ||||||
3260 | const auto *A = D->getAttr<OverloadableAttr>(); | ||||||
3261 | return A && !A->isImplicit(); | ||||||
3262 | }); | ||||||
3263 | // If we've implicitly added *all* of the overloadable attrs to this | ||||||
3264 | // chain, emitting a "previous redecl" note is pointless. | ||||||
3265 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; | ||||||
3266 | } | ||||||
3267 | |||||||
3268 | if (DiagOld) | ||||||
3269 | Diag(DiagOld->getLocation(), | ||||||
3270 | diag::note_attribute_overloadable_prev_overload) | ||||||
3271 | << OldOvl; | ||||||
3272 | |||||||
3273 | if (OldOvl) | ||||||
3274 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||||
3275 | else | ||||||
3276 | New->dropAttr<OverloadableAttr>(); | ||||||
3277 | } | ||||||
3278 | } | ||||||
3279 | |||||||
3280 | // If a function is first declared with a calling convention, but is later | ||||||
3281 | // declared or defined without one, all following decls assume the calling | ||||||
3282 | // convention of the first. | ||||||
3283 | // | ||||||
3284 | // It's OK if a function is first declared without a calling convention, | ||||||
3285 | // but is later declared or defined with the default calling convention. | ||||||
3286 | // | ||||||
3287 | // To test if either decl has an explicit calling convention, we look for | ||||||
3288 | // AttributedType sugar nodes on the type as written. If they are missing or | ||||||
3289 | // were canonicalized away, we assume the calling convention was implicit. | ||||||
3290 | // | ||||||
3291 | // Note also that we DO NOT return at this point, because we still have | ||||||
3292 | // other tests to run. | ||||||
3293 | QualType OldQType = Context.getCanonicalType(Old->getType()); | ||||||
3294 | QualType NewQType = Context.getCanonicalType(New->getType()); | ||||||
3295 | const FunctionType *OldType = cast<FunctionType>(OldQType); | ||||||
3296 | const FunctionType *NewType = cast<FunctionType>(NewQType); | ||||||
3297 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||||
3298 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||||
3299 | bool RequiresAdjustment = false; | ||||||
3300 | |||||||
3301 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { | ||||||
3302 | FunctionDecl *First = Old->getFirstDecl(); | ||||||
3303 | const FunctionType *FT = | ||||||
3304 | First->getType().getCanonicalType()->castAs<FunctionType>(); | ||||||
3305 | FunctionType::ExtInfo FI = FT->getExtInfo(); | ||||||
3306 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); | ||||||
3307 | if (!NewCCExplicit) { | ||||||
3308 | // Inherit the CC from the previous declaration if it was specified | ||||||
3309 | // there but not here. | ||||||
3310 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||||
3311 | RequiresAdjustment = true; | ||||||
3312 | } else if (New->getBuiltinID()) { | ||||||
3313 | // Calling Conventions on a Builtin aren't really useful and setting a | ||||||
3314 | // default calling convention and cdecl'ing some builtin redeclarations is | ||||||
3315 | // common, so warn and ignore the calling convention on the redeclaration. | ||||||
3316 | Diag(New->getLocation(), diag::warn_cconv_unsupported) | ||||||
3317 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||||
3318 | << (int)CallingConventionIgnoredReason::BuiltinFunction; | ||||||
3319 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||||
3320 | RequiresAdjustment = true; | ||||||
3321 | } else { | ||||||
3322 | // Calling conventions aren't compatible, so complain. | ||||||
3323 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); | ||||||
3324 | Diag(New->getLocation(), diag::err_cconv_change) | ||||||
3325 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||||
3326 | << !FirstCCExplicit | ||||||
3327 | << (!FirstCCExplicit ? "" : | ||||||
3328 | FunctionType::getNameForCallConv(FI.getCC())); | ||||||
3329 | |||||||
3330 | // Put the note on the first decl, since it is the one that matters. | ||||||
3331 | Diag(First->getLocation(), diag::note_previous_declaration); | ||||||
3332 | return true; | ||||||
3333 | } | ||||||
3334 | } | ||||||
3335 | |||||||
3336 | // FIXME: diagnose the other way around? | ||||||
3337 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { | ||||||
3338 | NewTypeInfo = NewTypeInfo.withNoReturn(true); | ||||||
3339 | RequiresAdjustment = true; | ||||||
3340 | } | ||||||
3341 | |||||||
3342 | // Merge regparm attribute. | ||||||
3343 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || | ||||||
3344 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { | ||||||
3345 | if (NewTypeInfo.getHasRegParm()) { | ||||||
3346 | Diag(New->getLocation(), diag::err_regparm_mismatch) | ||||||
3347 | << NewType->getRegParmType() | ||||||
3348 | << OldType->getRegParmType(); | ||||||
3349 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3350 | return true; | ||||||
3351 | } | ||||||
3352 | |||||||
3353 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); | ||||||
3354 | RequiresAdjustment = true; | ||||||
3355 | } | ||||||
3356 | |||||||
3357 | // Merge ns_returns_retained attribute. | ||||||
3358 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { | ||||||
3359 | if (NewTypeInfo.getProducesResult()) { | ||||||
3360 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) | ||||||
3361 | << "'ns_returns_retained'"; | ||||||
3362 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3363 | return true; | ||||||
3364 | } | ||||||
3365 | |||||||
3366 | NewTypeInfo = NewTypeInfo.withProducesResult(true); | ||||||
3367 | RequiresAdjustment = true; | ||||||
3368 | } | ||||||
3369 | |||||||
3370 | if (OldTypeInfo.getNoCallerSavedRegs() != | ||||||
3371 | NewTypeInfo.getNoCallerSavedRegs()) { | ||||||
3372 | if (NewTypeInfo.getNoCallerSavedRegs()) { | ||||||
3373 | AnyX86NoCallerSavedRegistersAttr *Attr = | ||||||
3374 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); | ||||||
3375 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; | ||||||
3376 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3377 | return true; | ||||||
3378 | } | ||||||
3379 | |||||||
3380 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); | ||||||
3381 | RequiresAdjustment = true; | ||||||
3382 | } | ||||||
3383 | |||||||
3384 | if (RequiresAdjustment) { | ||||||
3385 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); | ||||||
3386 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); | ||||||
3387 | New->setType(QualType(AdjustedType, 0)); | ||||||
3388 | NewQType = Context.getCanonicalType(New->getType()); | ||||||
3389 | } | ||||||
3390 | |||||||
3391 | // If this redeclaration makes the function inline, we may need to add it to | ||||||
3392 | // UndefinedButUsed. | ||||||
3393 | if (!Old->isInlined() && New->isInlined() && | ||||||
3394 | !New->hasAttr<GNUInlineAttr>() && | ||||||
3395 | !getLangOpts().GNUInline && | ||||||
3396 | Old->isUsed(false) && | ||||||
3397 | !Old->isDefined() && !New->isThisDeclarationADefinition()) | ||||||
3398 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||||
3399 | SourceLocation())); | ||||||
3400 | |||||||
3401 | // If this redeclaration makes it newly gnu_inline, we don't want to warn | ||||||
3402 | // about it. | ||||||
3403 | if (New->hasAttr<GNUInlineAttr>() && | ||||||
3404 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { | ||||||
3405 | UndefinedButUsed.erase(Old->getCanonicalDecl()); | ||||||
3406 | } | ||||||
3407 | |||||||
3408 | // If pass_object_size params don't match up perfectly, this isn't a valid | ||||||
3409 | // redeclaration. | ||||||
3410 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && | ||||||
3411 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { | ||||||
3412 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) | ||||||
3413 | << New->getDeclName(); | ||||||
3414 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3415 | return true; | ||||||
3416 | } | ||||||
3417 | |||||||
3418 | if (getLangOpts().CPlusPlus) { | ||||||
3419 | // C++1z [over.load]p2 | ||||||
3420 | // Certain function declarations cannot be overloaded: | ||||||
3421 | // -- Function declarations that differ only in the return type, | ||||||
3422 | // the exception specification, or both cannot be overloaded. | ||||||
3423 | |||||||
3424 | // Check the exception specifications match. This may recompute the type of | ||||||
3425 | // both Old and New if it resolved exception specifications, so grab the | ||||||
3426 | // types again after this. Because this updates the type, we do this before | ||||||
3427 | // any of the other checks below, which may update the "de facto" NewQType | ||||||
3428 | // but do not necessarily update the type of New. | ||||||
3429 | if (CheckEquivalentExceptionSpec(Old, New)) | ||||||
3430 | return true; | ||||||
3431 | OldQType = Context.getCanonicalType(Old->getType()); | ||||||
3432 | NewQType = Context.getCanonicalType(New->getType()); | ||||||
3433 | |||||||
3434 | // Go back to the type source info to compare the declared return types, | ||||||
3435 | // per C++1y [dcl.type.auto]p13: | ||||||
3436 | // Redeclarations or specializations of a function or function template | ||||||
3437 | // with a declared return type that uses a placeholder type shall also | ||||||
3438 | // use that placeholder, not a deduced type. | ||||||
3439 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); | ||||||
3440 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); | ||||||
3441 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && | ||||||
3442 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, | ||||||
3443 | OldDeclaredReturnType)) { | ||||||
3444 | QualType ResQT; | ||||||
3445 | if (NewDeclaredReturnType->isObjCObjectPointerType() && | ||||||
3446 | OldDeclaredReturnType->isObjCObjectPointerType()) | ||||||
3447 | // FIXME: This does the wrong thing for a deduced return type. | ||||||
3448 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); | ||||||
3449 | if (ResQT.isNull()) { | ||||||
3450 | if (New->isCXXClassMember() && New->isOutOfLine()) | ||||||
3451 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) | ||||||
3452 | << New << New->getReturnTypeSourceRange(); | ||||||
3453 | else | ||||||
3454 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) | ||||||
3455 | << New->getReturnTypeSourceRange(); | ||||||
3456 | Diag(OldLocation, PrevDiag) << Old << Old->getType() | ||||||
3457 | << Old->getReturnTypeSourceRange(); | ||||||
3458 | return true; | ||||||
3459 | } | ||||||
3460 | else | ||||||
3461 | NewQType = ResQT; | ||||||
3462 | } | ||||||
3463 | |||||||
3464 | QualType OldReturnType = OldType->getReturnType(); | ||||||
3465 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); | ||||||
3466 | if (OldReturnType != NewReturnType) { | ||||||
3467 | // If this function has a deduced return type and has already been | ||||||
3468 | // defined, copy the deduced value from the old declaration. | ||||||
3469 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); | ||||||
3470 | if (OldAT && OldAT->isDeduced()) { | ||||||
3471 | New->setType( | ||||||
3472 | SubstAutoType(New->getType(), | ||||||
3473 | OldAT->isDependentType() ? Context.DependentTy | ||||||
3474 | : OldAT->getDeducedType())); | ||||||
3475 | NewQType = Context.getCanonicalType( | ||||||
3476 | SubstAutoType(NewQType, | ||||||
3477 | OldAT->isDependentType() ? Context.DependentTy | ||||||
3478 | : OldAT->getDeducedType())); | ||||||
3479 | } | ||||||
3480 | } | ||||||
3481 | |||||||
3482 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | ||||||
3483 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | ||||||
3484 | if (OldMethod && NewMethod) { | ||||||
3485 | // Preserve triviality. | ||||||
3486 | NewMethod->setTrivial(OldMethod->isTrivial()); | ||||||
3487 | |||||||
3488 | // MSVC allows explicit template specialization at class scope: | ||||||
3489 | // 2 CXXMethodDecls referring to the same function will be injected. | ||||||
3490 | // We don't want a redeclaration error. | ||||||
3491 | bool IsClassScopeExplicitSpecialization = | ||||||
3492 | OldMethod->isFunctionTemplateSpecialization() && | ||||||
3493 | NewMethod->isFunctionTemplateSpecialization(); | ||||||
3494 | bool isFriend = NewMethod->getFriendObjectKind(); | ||||||
3495 | |||||||
3496 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && | ||||||
3497 | !IsClassScopeExplicitSpecialization) { | ||||||
3498 | // -- Member function declarations with the same name and the | ||||||
3499 | // same parameter types cannot be overloaded if any of them | ||||||
3500 | // is a static member function declaration. | ||||||
3501 | if (OldMethod->isStatic() != NewMethod->isStatic()) { | ||||||
3502 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); | ||||||
3503 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3504 | return true; | ||||||
3505 | } | ||||||
3506 | |||||||
3507 | // C++ [class.mem]p1: | ||||||
3508 | // [...] A member shall not be declared twice in the | ||||||
3509 | // member-specification, except that a nested class or member | ||||||
3510 | // class template can be declared and then later defined. | ||||||
3511 | if (!inTemplateInstantiation()) { | ||||||
3512 | unsigned NewDiag; | ||||||
3513 | if (isa<CXXConstructorDecl>(OldMethod)) | ||||||
3514 | NewDiag = diag::err_constructor_redeclared; | ||||||
3515 | else if (isa<CXXDestructorDecl>(NewMethod)) | ||||||
3516 | NewDiag = diag::err_destructor_redeclared; | ||||||
3517 | else if (isa<CXXConversionDecl>(NewMethod)) | ||||||
3518 | NewDiag = diag::err_conv_function_redeclared; | ||||||
3519 | else | ||||||
3520 | NewDiag = diag::err_member_redeclared; | ||||||
3521 | |||||||
3522 | Diag(New->getLocation(), NewDiag); | ||||||
3523 | } else { | ||||||
3524 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) | ||||||
3525 | << New << New->getType(); | ||||||
3526 | } | ||||||
3527 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3528 | return true; | ||||||
3529 | |||||||
3530 | // Complain if this is an explicit declaration of a special | ||||||
3531 | // member that was initially declared implicitly. | ||||||
3532 | // | ||||||
3533 | // As an exception, it's okay to befriend such methods in order | ||||||
3534 | // to permit the implicit constructor/destructor/operator calls. | ||||||
3535 | } else if (OldMethod->isImplicit()) { | ||||||
3536 | if (isFriend) { | ||||||
3537 | NewMethod->setImplicit(); | ||||||
3538 | } else { | ||||||
3539 | Diag(NewMethod->getLocation(), | ||||||
3540 | diag::err_definition_of_implicitly_declared_member) | ||||||
3541 | << New << getSpecialMember(OldMethod); | ||||||
3542 | return true; | ||||||
3543 | } | ||||||
3544 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { | ||||||
3545 | Diag(NewMethod->getLocation(), | ||||||
3546 | diag::err_definition_of_explicitly_defaulted_member) | ||||||
3547 | << getSpecialMember(OldMethod); | ||||||
3548 | return true; | ||||||
3549 | } | ||||||
3550 | } | ||||||
3551 | |||||||
3552 | // C++11 [dcl.attr.noreturn]p1: | ||||||
3553 | // The first declaration of a function shall specify the noreturn | ||||||
3554 | // attribute if any declaration of that function specifies the noreturn | ||||||
3555 | // attribute. | ||||||
3556 | const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); | ||||||
3557 | if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { | ||||||
3558 | Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); | ||||||
3559 | Diag(Old->getFirstDecl()->getLocation(), | ||||||
3560 | diag::note_noreturn_missing_first_decl); | ||||||
3561 | } | ||||||
3562 | |||||||
3563 | // C++11 [dcl.attr.depend]p2: | ||||||
3564 | // The first declaration of a function shall specify the | ||||||
3565 | // carries_dependency attribute for its declarator-id if any declaration | ||||||
3566 | // of the function specifies the carries_dependency attribute. | ||||||
3567 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); | ||||||
3568 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { | ||||||
3569 | Diag(CDA->getLocation(), | ||||||
3570 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; | ||||||
3571 | Diag(Old->getFirstDecl()->getLocation(), | ||||||
3572 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; | ||||||
3573 | } | ||||||
3574 | |||||||
3575 | // (C++98 8.3.5p3): | ||||||
3576 | // All declarations for a function shall agree exactly in both the | ||||||
3577 | // return type and the parameter-type-list. | ||||||
3578 | // We also want to respect all the extended bits except noreturn. | ||||||
3579 | |||||||
3580 | // noreturn should now match unless the old type info didn't have it. | ||||||
3581 | QualType OldQTypeForComparison = OldQType; | ||||||
3582 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { | ||||||
3583 | auto *OldType = OldQType->castAs<FunctionProtoType>(); | ||||||
3584 | const FunctionType *OldTypeForComparison | ||||||
3585 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); | ||||||
3586 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); | ||||||
3587 | assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void> (0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 3587, __PRETTY_FUNCTION__)); | ||||||
3588 | } | ||||||
3589 | |||||||
3590 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||||
3591 | // As a special case, retain the language linkage from previous | ||||||
3592 | // declarations of a friend function as an extension. | ||||||
3593 | // | ||||||
3594 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC | ||||||
3595 | // and is useful because there's otherwise no way to specify language | ||||||
3596 | // linkage within class scope. | ||||||
3597 | // | ||||||
3598 | // Check cautiously as the friend object kind isn't yet complete. | ||||||
3599 | if (New->getFriendObjectKind() != Decl::FOK_None) { | ||||||
3600 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; | ||||||
3601 | Diag(OldLocation, PrevDiag); | ||||||
3602 | } else { | ||||||
3603 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||||
3604 | Diag(OldLocation, PrevDiag); | ||||||
3605 | return true; | ||||||
3606 | } | ||||||
3607 | } | ||||||
3608 | |||||||
3609 | // If the function types are compatible, merge the declarations. Ignore the | ||||||
3610 | // exception specifier because it was already checked above in | ||||||
3611 | // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics | ||||||
3612 | // about incompatible types under -fms-compatibility. | ||||||
3613 | if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, | ||||||
3614 | NewQType)) | ||||||
3615 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3616 | |||||||
3617 | // If the types are imprecise (due to dependent constructs in friends or | ||||||
3618 | // local extern declarations), it's OK if they differ. We'll check again | ||||||
3619 | // during instantiation. | ||||||
3620 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) | ||||||
3621 | return false; | ||||||
3622 | |||||||
3623 | // Fall through for conflicting redeclarations and redefinitions. | ||||||
3624 | } | ||||||
3625 | |||||||
3626 | // C: Function types need to be compatible, not identical. This handles | ||||||
3627 | // duplicate function decls like "void f(int); void f(enum X);" properly. | ||||||
3628 | if (!getLangOpts().CPlusPlus && | ||||||
3629 | Context.typesAreCompatible(OldQType, NewQType)) { | ||||||
3630 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); | ||||||
3631 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); | ||||||
3632 | const FunctionProtoType *OldProto = nullptr; | ||||||
3633 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && | ||||||
3634 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { | ||||||
3635 | // The old declaration provided a function prototype, but the | ||||||
3636 | // new declaration does not. Merge in the prototype. | ||||||
3637 | assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((!OldProto->hasExceptionSpec() && "Exception spec in C" ) ? static_cast<void> (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 3637, __PRETTY_FUNCTION__)); | ||||||
3638 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); | ||||||
3639 | NewQType = | ||||||
3640 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, | ||||||
3641 | OldProto->getExtProtoInfo()); | ||||||
3642 | New->setType(NewQType); | ||||||
3643 | New->setHasInheritedPrototype(); | ||||||
3644 | |||||||
3645 | // Synthesize parameters with the same types. | ||||||
3646 | SmallVector<ParmVarDecl*, 16> Params; | ||||||
3647 | for (const auto &ParamType : OldProto->param_types()) { | ||||||
3648 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), | ||||||
3649 | SourceLocation(), nullptr, | ||||||
3650 | ParamType, /*TInfo=*/nullptr, | ||||||
3651 | SC_None, nullptr); | ||||||
3652 | Param->setScopeInfo(0, Params.size()); | ||||||
3653 | Param->setImplicit(); | ||||||
3654 | Params.push_back(Param); | ||||||
3655 | } | ||||||
3656 | |||||||
3657 | New->setParams(Params); | ||||||
3658 | } | ||||||
3659 | |||||||
3660 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3661 | } | ||||||
3662 | |||||||
3663 | // Check if the function types are compatible when pointer size address | ||||||
3664 | // spaces are ignored. | ||||||
3665 | if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) | ||||||
3666 | return false; | ||||||
3667 | |||||||
3668 | // GNU C permits a K&R definition to follow a prototype declaration | ||||||
3669 | // if the declared types of the parameters in the K&R definition | ||||||
3670 | // match the types in the prototype declaration, even when the | ||||||
3671 | // promoted types of the parameters from the K&R definition differ | ||||||
3672 | // from the types in the prototype. GCC then keeps the types from | ||||||
3673 | // the prototype. | ||||||
3674 | // | ||||||
3675 | // If a variadic prototype is followed by a non-variadic K&R definition, | ||||||
3676 | // the K&R definition becomes variadic. This is sort of an edge case, but | ||||||
3677 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and | ||||||
3678 | // C99 6.9.1p8. | ||||||
3679 | if (!getLangOpts().CPlusPlus && | ||||||
3680 | Old->hasPrototype() && !New->hasPrototype() && | ||||||
3681 | New->getType()->getAs<FunctionProtoType>() && | ||||||
3682 | Old->getNumParams() == New->getNumParams()) { | ||||||
3683 | SmallVector<QualType, 16> ArgTypes; | ||||||
3684 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; | ||||||
3685 | const FunctionProtoType *OldProto | ||||||
3686 | = Old->getType()->getAs<FunctionProtoType>(); | ||||||
3687 | const FunctionProtoType *NewProto | ||||||
3688 | = New->getType()->getAs<FunctionProtoType>(); | ||||||
3689 | |||||||
3690 | // Determine whether this is the GNU C extension. | ||||||
3691 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), | ||||||
3692 | NewProto->getReturnType()); | ||||||
3693 | bool LooseCompatible = !MergedReturn.isNull(); | ||||||
3694 | for (unsigned Idx = 0, End = Old->getNumParams(); | ||||||
3695 | LooseCompatible && Idx != End; ++Idx) { | ||||||
3696 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); | ||||||
3697 | ParmVarDecl *NewParm = New->getParamDecl(Idx); | ||||||
3698 | if (Context.typesAreCompatible(OldParm->getType(), | ||||||
3699 | NewProto->getParamType(Idx))) { | ||||||
3700 | ArgTypes.push_back(NewParm->getType()); | ||||||
3701 | } else if (Context.typesAreCompatible(OldParm->getType(), | ||||||
3702 | NewParm->getType(), | ||||||
3703 | /*CompareUnqualified=*/true)) { | ||||||
3704 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, | ||||||
3705 | NewProto->getParamType(Idx) }; | ||||||
3706 | Warnings.push_back(Warn); | ||||||
3707 | ArgTypes.push_back(NewParm->getType()); | ||||||
3708 | } else | ||||||
3709 | LooseCompatible = false; | ||||||
3710 | } | ||||||
3711 | |||||||
3712 | if (LooseCompatible) { | ||||||
3713 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { | ||||||
3714 | Diag(Warnings[Warn].NewParm->getLocation(), | ||||||
3715 | diag::ext_param_promoted_not_compatible_with_prototype) | ||||||
3716 | << Warnings[Warn].PromotedType | ||||||
3717 | << Warnings[Warn].OldParm->getType(); | ||||||
3718 | if (Warnings[Warn].OldParm->getLocation().isValid()) | ||||||
3719 | Diag(Warnings[Warn].OldParm->getLocation(), | ||||||
3720 | diag::note_previous_declaration); | ||||||
3721 | } | ||||||
3722 | |||||||
3723 | if (MergeTypeWithOld) | ||||||
3724 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, | ||||||
3725 | OldProto->getExtProtoInfo())); | ||||||
3726 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3727 | } | ||||||
3728 | |||||||
3729 | // Fall through to diagnose conflicting types. | ||||||
3730 | } | ||||||
3731 | |||||||
3732 | // A function that has already been declared has been redeclared or | ||||||
3733 | // defined with a different type; show an appropriate diagnostic. | ||||||
3734 | |||||||
3735 | // If the previous declaration was an implicitly-generated builtin | ||||||
3736 | // declaration, then at the very least we should use a specialized note. | ||||||
3737 | unsigned BuiltinID; | ||||||
3738 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { | ||||||
3739 | // If it's actually a library-defined builtin function like 'malloc' | ||||||
3740 | // or 'printf', just warn about the incompatible redeclaration. | ||||||
3741 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { | ||||||
3742 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; | ||||||
3743 | Diag(OldLocation, diag::note_previous_builtin_declaration) | ||||||
3744 | << Old << Old->getType(); | ||||||
3745 | |||||||
3746 | // If this is a global redeclaration, just forget hereafter | ||||||
3747 | // about the "builtin-ness" of the function. | ||||||
3748 | // | ||||||
3749 | // Doing this for local extern declarations is problematic. If | ||||||
3750 | // the builtin declaration remains visible, a second invalid | ||||||
3751 | // local declaration will produce a hard error; if it doesn't | ||||||
3752 | // remain visible, a single bogus local redeclaration (which is | ||||||
3753 | // actually only a warning) could break all the downstream code. | ||||||
3754 | if (!New->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||
3755 | New->getIdentifier()->revertBuiltin(); | ||||||
3756 | |||||||
3757 | return false; | ||||||
3758 | } | ||||||
3759 | |||||||
3760 | PrevDiag = diag::note_previous_builtin_declaration; | ||||||
3761 | } | ||||||
3762 | |||||||
3763 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); | ||||||
3764 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3765 | return true; | ||||||
3766 | } | ||||||
3767 | |||||||
3768 | /// Completes the merge of two function declarations that are | ||||||
3769 | /// known to be compatible. | ||||||
3770 | /// | ||||||
3771 | /// This routine handles the merging of attributes and other | ||||||
3772 | /// properties of function declarations from the old declaration to | ||||||
3773 | /// the new declaration, once we know that New is in fact a | ||||||
3774 | /// redeclaration of Old. | ||||||
3775 | /// | ||||||
3776 | /// \returns false | ||||||
3777 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | ||||||
3778 | Scope *S, bool MergeTypeWithOld) { | ||||||
3779 | // Merge the attributes | ||||||
3780 | mergeDeclAttributes(New, Old); | ||||||
3781 | |||||||
3782 | // Merge "pure" flag. | ||||||
3783 | if (Old->isPure()) | ||||||
3784 | New->setPure(); | ||||||
3785 | |||||||
3786 | // Merge "used" flag. | ||||||
3787 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||||
3788 | New->setIsUsed(); | ||||||
3789 | |||||||
3790 | // Merge attributes from the parameters. These can mismatch with K&R | ||||||
3791 | // declarations. | ||||||
3792 | if (New->getNumParams() == Old->getNumParams()) | ||||||
3793 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { | ||||||
3794 | ParmVarDecl *NewParam = New->getParamDecl(i); | ||||||
3795 | ParmVarDecl *OldParam = Old->getParamDecl(i); | ||||||
3796 | mergeParamDeclAttributes(NewParam, OldParam, *this); | ||||||
3797 | mergeParamDeclTypes(NewParam, OldParam, *this); | ||||||
3798 | } | ||||||
3799 | |||||||
3800 | if (getLangOpts().CPlusPlus) | ||||||
3801 | return MergeCXXFunctionDecl(New, Old, S); | ||||||
3802 | |||||||
3803 | // Merge the function types so the we get the composite types for the return | ||||||
3804 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl | ||||||
3805 | // was visible. | ||||||
3806 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); | ||||||
3807 | if (!Merged.isNull() && MergeTypeWithOld) | ||||||
3808 | New->setType(Merged); | ||||||
3809 | |||||||
3810 | return false; | ||||||
3811 | } | ||||||
3812 | |||||||
3813 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, | ||||||
3814 | ObjCMethodDecl *oldMethod) { | ||||||
3815 | // Merge the attributes, including deprecated/unavailable | ||||||
3816 | AvailabilityMergeKind MergeKind = | ||||||
3817 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) | ||||||
3818 | ? AMK_ProtocolImplementation | ||||||
3819 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration | ||||||
3820 | : AMK_Override; | ||||||
3821 | |||||||
3822 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); | ||||||
3823 | |||||||
3824 | // Merge attributes from the parameters. | ||||||
3825 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), | ||||||
3826 | oe = oldMethod->param_end(); | ||||||
3827 | for (ObjCMethodDecl::param_iterator | ||||||
3828 | ni = newMethod->param_begin(), ne = newMethod->param_end(); | ||||||
3829 | ni != ne && oi != oe; ++ni, ++oi) | ||||||
3830 | mergeParamDeclAttributes(*ni, *oi, *this); | ||||||
3831 | |||||||
3832 | CheckObjCMethodOverride(newMethod, oldMethod); | ||||||
3833 | } | ||||||
3834 | |||||||
3835 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { | ||||||
3836 | assert(!S.Context.hasSameType(New->getType(), Old->getType()))((!S.Context.hasSameType(New->getType(), Old->getType() )) ? static_cast<void> (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 3836, __PRETTY_FUNCTION__)); | ||||||
3837 | |||||||
3838 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() | ||||||
3839 | ? diag::err_redefinition_different_type | ||||||
3840 | : diag::err_redeclaration_different_type) | ||||||
3841 | << New->getDeclName() << New->getType() << Old->getType(); | ||||||
3842 | |||||||
3843 | diag::kind PrevDiag; | ||||||
3844 | SourceLocation OldLocation; | ||||||
3845 | std::tie(PrevDiag, OldLocation) | ||||||
3846 | = getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
3847 | S.Diag(OldLocation, PrevDiag); | ||||||
3848 | New->setInvalidDecl(); | ||||||
3849 | } | ||||||
3850 | |||||||
3851 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and | ||||||
3852 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, | ||||||
3853 | /// emitting diagnostics as appropriate. | ||||||
3854 | /// | ||||||
3855 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back | ||||||
3856 | /// to here in AddInitializerToDecl. We can't check them before the initializer | ||||||
3857 | /// is attached. | ||||||
3858 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, | ||||||
3859 | bool MergeTypeWithOld) { | ||||||
3860 | if (New->isInvalidDecl() || Old->isInvalidDecl()) | ||||||
3861 | return; | ||||||
3862 | |||||||
3863 | QualType MergedT; | ||||||
3864 | if (getLangOpts().CPlusPlus) { | ||||||
3865 | if (New->getType()->isUndeducedType()) { | ||||||
3866 | // We don't know what the new type is until the initializer is attached. | ||||||
3867 | return; | ||||||
3868 | } else if (Context.hasSameType(New->getType(), Old->getType())) { | ||||||
3869 | // These could still be something that needs exception specs checked. | ||||||
3870 | return MergeVarDeclExceptionSpecs(New, Old); | ||||||
3871 | } | ||||||
3872 | // C++ [basic.link]p10: | ||||||
3873 | // [...] the types specified by all declarations referring to a given | ||||||
3874 | // object or function shall be identical, except that declarations for an | ||||||
3875 | // array object can specify array types that differ by the presence or | ||||||
3876 | // absence of a major array bound (8.3.4). | ||||||
3877 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { | ||||||
3878 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); | ||||||
3879 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); | ||||||
3880 | |||||||
3881 | // We are merging a variable declaration New into Old. If it has an array | ||||||
3882 | // bound, and that bound differs from Old's bound, we should diagnose the | ||||||
3883 | // mismatch. | ||||||
3884 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { | ||||||
3885 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; | ||||||
3886 | PrevVD = PrevVD->getPreviousDecl()) { | ||||||
3887 | const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); | ||||||
3888 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) | ||||||
3889 | continue; | ||||||
3890 | |||||||
3891 | if (!Context.hasSameType(NewArray, PrevVDTy)) | ||||||
3892 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); | ||||||
3893 | } | ||||||
3894 | } | ||||||
3895 | |||||||
3896 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { | ||||||
3897 | if (Context.hasSameType(OldArray->getElementType(), | ||||||
3898 | NewArray->getElementType())) | ||||||
3899 | MergedT = New->getType(); | ||||||
3900 | } | ||||||
3901 | // FIXME: Check visibility. New is hidden but has a complete type. If New | ||||||
3902 | // has no array bound, it should not inherit one from Old, if Old is not | ||||||
3903 | // visible. | ||||||
3904 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { | ||||||
3905 | if (Context.hasSameType(OldArray->getElementType(), | ||||||
3906 | NewArray->getElementType())) | ||||||
3907 | MergedT = Old->getType(); | ||||||
3908 | } | ||||||
3909 | } | ||||||
3910 | else if (New->getType()->isObjCObjectPointerType() && | ||||||
3911 | Old->getType()->isObjCObjectPointerType()) { | ||||||
3912 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), | ||||||
3913 | Old->getType()); | ||||||
3914 | } | ||||||
3915 | } else { | ||||||
3916 | // C 6.2.7p2: | ||||||
3917 | // All declarations that refer to the same object or function shall have | ||||||
3918 | // compatible type. | ||||||
3919 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); | ||||||
3920 | } | ||||||
3921 | if (MergedT.isNull()) { | ||||||
3922 | // It's OK if we couldn't merge types if either type is dependent, for a | ||||||
3923 | // block-scope variable. In other cases (static data members of class | ||||||
3924 | // templates, variable templates, ...), we require the types to be | ||||||
3925 | // equivalent. | ||||||
3926 | // FIXME: The C++ standard doesn't say anything about this. | ||||||
3927 | if ((New->getType()->isDependentType() || | ||||||
3928 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { | ||||||
3929 | // If the old type was dependent, we can't merge with it, so the new type | ||||||
3930 | // becomes dependent for now. We'll reproduce the original type when we | ||||||
3931 | // instantiate the TypeSourceInfo for the variable. | ||||||
3932 | if (!New->getType()->isDependentType() && MergeTypeWithOld) | ||||||
3933 | New->setType(Context.DependentTy); | ||||||
3934 | return; | ||||||
3935 | } | ||||||
3936 | return diagnoseVarDeclTypeMismatch(*this, New, Old); | ||||||
3937 | } | ||||||
3938 | |||||||
3939 | // Don't actually update the type on the new declaration if the old | ||||||
3940 | // declaration was an extern declaration in a different scope. | ||||||
3941 | if (MergeTypeWithOld) | ||||||
3942 | New->setType(MergedT); | ||||||
3943 | } | ||||||
3944 | |||||||
3945 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, | ||||||
3946 | LookupResult &Previous) { | ||||||
3947 | // C11 6.2.7p4: | ||||||
3948 | // For an identifier with internal or external linkage declared | ||||||
3949 | // in a scope in which a prior declaration of that identifier is | ||||||
3950 | // visible, if the prior declaration specifies internal or | ||||||
3951 | // external linkage, the type of the identifier at the later | ||||||
3952 | // declaration becomes the composite type. | ||||||
3953 | // | ||||||
3954 | // If the variable isn't visible, we do not merge with its type. | ||||||
3955 | if (Previous.isShadowed()) | ||||||
3956 | return false; | ||||||
3957 | |||||||
3958 | if (S.getLangOpts().CPlusPlus) { | ||||||
3959 | // C++11 [dcl.array]p3: | ||||||
3960 | // If there is a preceding declaration of the entity in the same | ||||||
3961 | // scope in which the bound was specified, an omitted array bound | ||||||
3962 | // is taken to be the same as in that earlier declaration. | ||||||
3963 | return NewVD->isPreviousDeclInSameBlockScope() || | ||||||
3964 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && | ||||||
3965 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); | ||||||
3966 | } else { | ||||||
3967 | // If the old declaration was function-local, don't merge with its | ||||||
3968 | // type unless we're in the same function. | ||||||
3969 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || | ||||||
3970 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); | ||||||
3971 | } | ||||||
3972 | } | ||||||
3973 | |||||||
3974 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name | ||||||
3975 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this | ||||||
3976 | /// situation, merging decls or emitting diagnostics as appropriate. | ||||||
3977 | /// | ||||||
3978 | /// Tentative definition rules (C99 6.9.2p2) are checked by | ||||||
3979 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative | ||||||
3980 | /// definitions here, since the initializer hasn't been attached. | ||||||
3981 | /// | ||||||
3982 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { | ||||||
3983 | // If the new decl is already invalid, don't do any other checking. | ||||||
3984 | if (New->isInvalidDecl()) | ||||||
3985 | return; | ||||||
3986 | |||||||
3987 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) | ||||||
3988 | return; | ||||||
3989 | |||||||
3990 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); | ||||||
3991 | |||||||
3992 | // Verify the old decl was also a variable or variable template. | ||||||
3993 | VarDecl *Old = nullptr; | ||||||
3994 | VarTemplateDecl *OldTemplate = nullptr; | ||||||
3995 | if (Previous.isSingleResult()) { | ||||||
3996 | if (NewTemplate) { | ||||||
3997 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); | ||||||
3998 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; | ||||||
3999 | |||||||
4000 | if (auto *Shadow = | ||||||
4001 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||||
4002 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) | ||||||
4003 | return New->setInvalidDecl(); | ||||||
4004 | } else { | ||||||
4005 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); | ||||||
4006 | |||||||
4007 | if (auto *Shadow = | ||||||
4008 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||||
4009 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) | ||||||
4010 | return New->setInvalidDecl(); | ||||||
4011 | } | ||||||
4012 | } | ||||||
4013 | if (!Old) { | ||||||
4014 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
4015 | << New->getDeclName(); | ||||||
4016 | notePreviousDefinition(Previous.getRepresentativeDecl(), | ||||||
4017 | New->getLocation()); | ||||||
4018 | return New->setInvalidDecl(); | ||||||
4019 | } | ||||||
4020 | |||||||
4021 | // Ensure the template parameters are compatible. | ||||||
4022 | if (NewTemplate && | ||||||
4023 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | ||||||
4024 | OldTemplate->getTemplateParameters(), | ||||||
4025 | /*Complain=*/true, TPL_TemplateMatch)) | ||||||
4026 | return New->setInvalidDecl(); | ||||||
4027 | |||||||
4028 | // C++ [class.mem]p1: | ||||||
4029 | // A member shall not be declared twice in the member-specification [...] | ||||||
4030 | // | ||||||
4031 | // Here, we need only consider static data members. | ||||||
4032 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { | ||||||
4033 | Diag(New->getLocation(), diag::err_duplicate_member) | ||||||
4034 | << New->getIdentifier(); | ||||||
4035 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
4036 | New->setInvalidDecl(); | ||||||
4037 | } | ||||||
4038 | |||||||
4039 | mergeDeclAttributes(New, Old); | ||||||
4040 | // Warn if an already-declared variable is made a weak_import in a subsequent | ||||||
4041 | // declaration | ||||||
4042 | if (New->hasAttr<WeakImportAttr>() && | ||||||
4043 | Old->getStorageClass() == SC_None && | ||||||
4044 | !Old->hasAttr<WeakImportAttr>()) { | ||||||
4045 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); | ||||||
4046 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4047 | // Remove weak_import attribute on new declaration. | ||||||
4048 | New->dropAttr<WeakImportAttr>(); | ||||||
4049 | } | ||||||
4050 | |||||||
4051 | if (New->hasAttr<InternalLinkageAttr>() && | ||||||
4052 | !Old->hasAttr<InternalLinkageAttr>()) { | ||||||
4053 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | ||||||
4054 | << New->getDeclName(); | ||||||
4055 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4056 | New->dropAttr<InternalLinkageAttr>(); | ||||||
4057 | } | ||||||
4058 | |||||||
4059 | // Merge the types. | ||||||
4060 | VarDecl *MostRecent = Old->getMostRecentDecl(); | ||||||
4061 | if (MostRecent != Old) { | ||||||
4062 | MergeVarDeclTypes(New, MostRecent, | ||||||
4063 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); | ||||||
4064 | if (New->isInvalidDecl()) | ||||||
4065 | return; | ||||||
4066 | } | ||||||
4067 | |||||||
4068 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); | ||||||
4069 | if (New->isInvalidDecl()) | ||||||
4070 | return; | ||||||
4071 | |||||||
4072 | diag::kind PrevDiag; | ||||||
4073 | SourceLocation OldLocation; | ||||||
4074 | std::tie(PrevDiag, OldLocation) = | ||||||
4075 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
4076 | |||||||
4077 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. | ||||||
4078 | if (New->getStorageClass() == SC_Static && | ||||||
4079 | !New->isStaticDataMember() && | ||||||
4080 | Old->hasExternalFormalLinkage()) { | ||||||
4081 | if (getLangOpts().MicrosoftExt) { | ||||||
4082 | Diag(New->getLocation(), diag::ext_static_non_static) | ||||||
4083 | << New->getDeclName(); | ||||||
4084 | Diag(OldLocation, PrevDiag); | ||||||
4085 | } else { | ||||||
4086 | Diag(New->getLocation(), diag::err_static_non_static) | ||||||
4087 | << New->getDeclName(); | ||||||
4088 | Diag(OldLocation, PrevDiag); | ||||||
4089 | return New->setInvalidDecl(); | ||||||
4090 | } | ||||||
4091 | } | ||||||
4092 | // C99 6.2.2p4: | ||||||
4093 | // For an identifier declared with the storage-class specifier | ||||||
4094 | // extern in a scope in which a prior declaration of that | ||||||
4095 | // identifier is visible,23) if the prior declaration specifies | ||||||
4096 | // internal or external linkage, the linkage of the identifier at | ||||||
4097 | // the later declaration is the same as the linkage specified at | ||||||
4098 | // the prior declaration. If no prior declaration is visible, or | ||||||
4099 | // if the prior declaration specifies no linkage, then the | ||||||
4100 | // identifier has external linkage. | ||||||
4101 | if (New->hasExternalStorage() && Old->hasLinkage()) | ||||||
4102 | /* Okay */; | ||||||
4103 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && | ||||||
4104 | !New->isStaticDataMember() && | ||||||
4105 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { | ||||||
4106 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); | ||||||
4107 | Diag(OldLocation, PrevDiag); | ||||||
4108 | return New->setInvalidDecl(); | ||||||
4109 | } | ||||||
4110 | |||||||
4111 | // Check if extern is followed by non-extern and vice-versa. | ||||||
4112 | if (New->hasExternalStorage() && | ||||||
4113 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { | ||||||
4114 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); | ||||||
4115 | Diag(OldLocation, PrevDiag); | ||||||
4116 | return New->setInvalidDecl(); | ||||||
4117 | } | ||||||
4118 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && | ||||||
4119 | !New->hasExternalStorage()) { | ||||||
4120 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); | ||||||
4121 | Diag(OldLocation, PrevDiag); | ||||||
4122 | return New->setInvalidDecl(); | ||||||
4123 | } | ||||||
4124 | |||||||
4125 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||||
4126 | return; | ||||||
4127 | |||||||
4128 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. | ||||||
4129 | |||||||
4130 | // FIXME: The test for external storage here seems wrong? We still | ||||||
4131 | // need to check for mismatches. | ||||||
4132 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && | ||||||
4133 | // Don't complain about out-of-line definitions of static members. | ||||||
4134 | !(Old->getLexicalDeclContext()->isRecord() && | ||||||
4135 | !New->getLexicalDeclContext()->isRecord())) { | ||||||
4136 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); | ||||||
4137 | Diag(OldLocation, PrevDiag); | ||||||
4138 | return New->setInvalidDecl(); | ||||||
4139 | } | ||||||
4140 | |||||||
4141 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { | ||||||
4142 | if (VarDecl *Def = Old->getDefinition()) { | ||||||
4143 | // C++1z [dcl.fcn.spec]p4: | ||||||
4144 | // If the definition of a variable appears in a translation unit before | ||||||
4145 | // its first declaration as inline, the program is ill-formed. | ||||||
4146 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | ||||||
4147 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
4148 | } | ||||||
4149 | } | ||||||
4150 | |||||||
4151 | // If this redeclaration makes the variable inline, we may need to add it to | ||||||
4152 | // UndefinedButUsed. | ||||||
4153 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && | ||||||
4154 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) | ||||||
4155 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||||
4156 | SourceLocation())); | ||||||
4157 | |||||||
4158 | if (New->getTLSKind() != Old->getTLSKind()) { | ||||||
4159 | if (!Old->getTLSKind()) { | ||||||
4160 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); | ||||||
4161 | Diag(OldLocation, PrevDiag); | ||||||
4162 | } else if (!New->getTLSKind()) { | ||||||
4163 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); | ||||||
4164 | Diag(OldLocation, PrevDiag); | ||||||
4165 | } else { | ||||||
4166 | // Do not allow redeclaration to change the variable between requiring | ||||||
4167 | // static and dynamic initialization. | ||||||
4168 | // FIXME: GCC allows this, but uses the TLS keyword on the first | ||||||
4169 | // declaration to determine the kind. Do we need to be compatible here? | ||||||
4170 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) | ||||||
4171 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); | ||||||
4172 | Diag(OldLocation, PrevDiag); | ||||||
4173 | } | ||||||
4174 | } | ||||||
4175 | |||||||
4176 | // C++ doesn't have tentative definitions, so go right ahead and check here. | ||||||
4177 | if (getLangOpts().CPlusPlus && | ||||||
4178 | New->isThisDeclarationADefinition() == VarDecl::Definition) { | ||||||
4179 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && | ||||||
4180 | Old->getCanonicalDecl()->isConstexpr()) { | ||||||
4181 | // This definition won't be a definition any more once it's been merged. | ||||||
4182 | Diag(New->getLocation(), | ||||||
4183 | diag::warn_deprecated_redundant_constexpr_static_def); | ||||||
4184 | } else if (VarDecl *Def = Old->getDefinition()) { | ||||||
4185 | if (checkVarDeclRedefinition(Def, New)) | ||||||
4186 | return; | ||||||
4187 | } | ||||||
4188 | } | ||||||
4189 | |||||||
4190 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||||
4191 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||||
4192 | Diag(OldLocation, PrevDiag); | ||||||
4193 | New->setInvalidDecl(); | ||||||
4194 | return; | ||||||
4195 | } | ||||||
4196 | |||||||
4197 | // Merge "used" flag. | ||||||
4198 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||||
4199 | New->setIsUsed(); | ||||||
4200 | |||||||
4201 | // Keep a chain of previous declarations. | ||||||
4202 | New->setPreviousDecl(Old); | ||||||
4203 | if (NewTemplate) | ||||||
4204 | NewTemplate->setPreviousDecl(OldTemplate); | ||||||
4205 | adjustDeclContextForDeclaratorDecl(New, Old); | ||||||
4206 | |||||||
4207 | // Inherit access appropriately. | ||||||
4208 | New->setAccess(Old->getAccess()); | ||||||
4209 | if (NewTemplate) | ||||||
4210 | NewTemplate->setAccess(New->getAccess()); | ||||||
4211 | |||||||
4212 | if (Old->isInline()) | ||||||
4213 | New->setImplicitlyInline(); | ||||||
4214 | } | ||||||
4215 | |||||||
4216 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { | ||||||
4217 | SourceManager &SrcMgr = getSourceManager(); | ||||||
4218 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); | ||||||
4219 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); | ||||||
4220 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); | ||||||
4221 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); | ||||||
4222 | auto &HSI = PP.getHeaderSearchInfo(); | ||||||
4223 | StringRef HdrFilename = | ||||||
4224 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); | ||||||
4225 | |||||||
4226 | auto noteFromModuleOrInclude = [&](Module *Mod, | ||||||
4227 | SourceLocation IncLoc) -> bool { | ||||||
4228 | // Redefinition errors with modules are common with non modular mapped | ||||||
4229 | // headers, example: a non-modular header H in module A that also gets | ||||||
4230 | // included directly in a TU. Pointing twice to the same header/definition | ||||||
4231 | // is confusing, try to get better diagnostics when modules is on. | ||||||
4232 | if (IncLoc.isValid()) { | ||||||
4233 | if (Mod) { | ||||||
4234 | Diag(IncLoc, diag::note_redefinition_modules_same_file) | ||||||
4235 | << HdrFilename.str() << Mod->getFullModuleName(); | ||||||
4236 | if (!Mod->DefinitionLoc.isInvalid()) | ||||||
4237 | Diag(Mod->DefinitionLoc, diag::note_defined_here) | ||||||
4238 | << Mod->getFullModuleName(); | ||||||
4239 | } else { | ||||||
4240 | Diag(IncLoc, diag::note_redefinition_include_same_file) | ||||||
4241 | << HdrFilename.str(); | ||||||
4242 | } | ||||||
4243 | return true; | ||||||
4244 | } | ||||||
4245 | |||||||
4246 | return false; | ||||||
4247 | }; | ||||||
4248 | |||||||
4249 | // Is it the same file and same offset? Provide more information on why | ||||||
4250 | // this leads to a redefinition error. | ||||||
4251 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { | ||||||
4252 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); | ||||||
4253 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); | ||||||
4254 | bool EmittedDiag = | ||||||
4255 | noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); | ||||||
4256 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); | ||||||
4257 | |||||||
4258 | // If the header has no guards, emit a note suggesting one. | ||||||
4259 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) | ||||||
4260 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); | ||||||
4261 | |||||||
4262 | if (EmittedDiag) | ||||||
4263 | return; | ||||||
4264 | } | ||||||
4265 | |||||||
4266 | // Redefinition coming from different files or couldn't do better above. | ||||||
4267 | if (Old->getLocation().isValid()) | ||||||
4268 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||||
4269 | } | ||||||
4270 | |||||||
4271 | /// We've just determined that \p Old and \p New both appear to be definitions | ||||||
4272 | /// of the same variable. Either diagnose or fix the problem. | ||||||
4273 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { | ||||||
4274 | if (!hasVisibleDefinition(Old) && | ||||||
4275 | (New->getFormalLinkage() == InternalLinkage || | ||||||
4276 | New->isInline() || | ||||||
4277 | New->getDescribedVarTemplate() || | ||||||
4278 | New->getNumTemplateParameterLists() || | ||||||
4279 | New->getDeclContext()->isDependentContext())) { | ||||||
4280 | // The previous definition is hidden, and multiple definitions are | ||||||
4281 | // permitted (in separate TUs). Demote this to a declaration. | ||||||
4282 | New->demoteThisDefinitionToDeclaration(); | ||||||
4283 | |||||||
4284 | // Make the canonical definition visible. | ||||||
4285 | if (auto *OldTD = Old->getDescribedVarTemplate()) | ||||||
4286 | makeMergedDefinitionVisible(OldTD); | ||||||
4287 | makeMergedDefinitionVisible(Old); | ||||||
4288 | return false; | ||||||
4289 | } else { | ||||||
4290 | Diag(New->getLocation(), diag::err_redefinition) << New; | ||||||
4291 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4292 | New->setInvalidDecl(); | ||||||
4293 | return true; | ||||||
4294 | } | ||||||
4295 | } | ||||||
4296 | |||||||
4297 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||||
4298 | /// no declarator (e.g. "struct foo;") is parsed. | ||||||
4299 | Decl * | ||||||
4300 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||||
4301 | RecordDecl *&AnonRecord) { | ||||||
4302 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, | ||||||
4303 | AnonRecord); | ||||||
4304 | } | ||||||
4305 | |||||||
4306 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to | ||||||
4307 | // disambiguate entities defined in different scopes. | ||||||
4308 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks | ||||||
4309 | // compatibility. | ||||||
4310 | // We will pick our mangling number depending on which version of MSVC is being | ||||||
4311 | // targeted. | ||||||
4312 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { | ||||||
4313 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) | ||||||
4314 | ? S->getMSCurManglingNumber() | ||||||
4315 | : S->getMSLastManglingNumber(); | ||||||
4316 | } | ||||||
4317 | |||||||
4318 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { | ||||||
4319 | if (!Context.getLangOpts().CPlusPlus) | ||||||
4320 | return; | ||||||
4321 | |||||||
4322 | if (isa<CXXRecordDecl>(Tag->getParent())) { | ||||||
4323 | // If this tag is the direct child of a class, number it if | ||||||
4324 | // it is anonymous. | ||||||
4325 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) | ||||||
4326 | return; | ||||||
4327 | MangleNumberingContext &MCtx = | ||||||
4328 | Context.getManglingNumberContext(Tag->getParent()); | ||||||
4329 | Context.setManglingNumber( | ||||||
4330 | Tag, MCtx.getManglingNumber( | ||||||
4331 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||||
4332 | return; | ||||||
4333 | } | ||||||
4334 | |||||||
4335 | // If this tag isn't a direct child of a class, number it if it is local. | ||||||
4336 | MangleNumberingContext *MCtx; | ||||||
4337 | Decl *ManglingContextDecl; | ||||||
4338 | std::tie(MCtx, ManglingContextDecl) = | ||||||
4339 | getCurrentMangleNumberContext(Tag->getDeclContext()); | ||||||
4340 | if (MCtx) { | ||||||
4341 | Context.setManglingNumber( | ||||||
4342 | Tag, MCtx->getManglingNumber( | ||||||
4343 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||||
4344 | } | ||||||
4345 | } | ||||||
4346 | |||||||
4347 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | ||||||
4348 | TypedefNameDecl *NewTD) { | ||||||
4349 | if (TagFromDeclSpec->isInvalidDecl()) | ||||||
4350 | return; | ||||||
4351 | |||||||
4352 | // Do nothing if the tag already has a name for linkage purposes. | ||||||
4353 | if (TagFromDeclSpec->hasNameForLinkage()) | ||||||
4354 | return; | ||||||
4355 | |||||||
4356 | // A well-formed anonymous tag must always be a TUK_Definition. | ||||||
4357 | assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast <void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4357, __PRETTY_FUNCTION__)); | ||||||
4358 | |||||||
4359 | // The type must match the tag exactly; no qualifiers allowed. | ||||||
4360 | if (!Context.hasSameType(NewTD->getUnderlyingType(), | ||||||
4361 | Context.getTagDeclType(TagFromDeclSpec))) { | ||||||
4362 | if (getLangOpts().CPlusPlus) | ||||||
4363 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); | ||||||
4364 | return; | ||||||
4365 | } | ||||||
4366 | |||||||
4367 | // If we've already computed linkage for the anonymous tag, then | ||||||
4368 | // adding a typedef name for the anonymous decl can change that | ||||||
4369 | // linkage, which might be a serious problem. Diagnose this as | ||||||
4370 | // unsupported and ignore the typedef name. TODO: we should | ||||||
4371 | // pursue this as a language defect and establish a formal rule | ||||||
4372 | // for how to handle it. | ||||||
4373 | if (TagFromDeclSpec->hasLinkageBeenComputed()) { | ||||||
4374 | Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); | ||||||
4375 | |||||||
4376 | SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); | ||||||
4377 | tagLoc = getLocForEndOfToken(tagLoc); | ||||||
4378 | |||||||
4379 | llvm::SmallString<40> textToInsert; | ||||||
4380 | textToInsert += ' '; | ||||||
4381 | textToInsert += NewTD->getIdentifier()->getName(); | ||||||
4382 | Diag(tagLoc, diag::note_typedef_changes_linkage) | ||||||
4383 | << FixItHint::CreateInsertion(tagLoc, textToInsert); | ||||||
4384 | return; | ||||||
4385 | } | ||||||
4386 | |||||||
4387 | // Otherwise, set this is the anon-decl typedef for the tag. | ||||||
4388 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); | ||||||
4389 | } | ||||||
4390 | |||||||
4391 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { | ||||||
4392 | switch (T) { | ||||||
4393 | case DeclSpec::TST_class: | ||||||
4394 | return 0; | ||||||
4395 | case DeclSpec::TST_struct: | ||||||
4396 | return 1; | ||||||
4397 | case DeclSpec::TST_interface: | ||||||
4398 | return 2; | ||||||
4399 | case DeclSpec::TST_union: | ||||||
4400 | return 3; | ||||||
4401 | case DeclSpec::TST_enum: | ||||||
4402 | return 4; | ||||||
4403 | default: | ||||||
4404 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4404); | ||||||
4405 | } | ||||||
4406 | } | ||||||
4407 | |||||||
4408 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||||
4409 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template | ||||||
4410 | /// parameters to cope with template friend declarations. | ||||||
4411 | Decl * | ||||||
4412 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||||
4413 | MultiTemplateParamsArg TemplateParams, | ||||||
4414 | bool IsExplicitInstantiation, | ||||||
4415 | RecordDecl *&AnonRecord) { | ||||||
4416 | Decl *TagD = nullptr; | ||||||
4417 | TagDecl *Tag = nullptr; | ||||||
4418 | if (DS.getTypeSpecType() == DeclSpec::TST_class || | ||||||
4419 | DS.getTypeSpecType() == DeclSpec::TST_struct || | ||||||
4420 | DS.getTypeSpecType() == DeclSpec::TST_interface || | ||||||
4421 | DS.getTypeSpecType() == DeclSpec::TST_union || | ||||||
4422 | DS.getTypeSpecType() == DeclSpec::TST_enum) { | ||||||
4423 | TagD = DS.getRepAsDecl(); | ||||||
4424 | |||||||
4425 | if (!TagD) // We probably had an error | ||||||
4426 | return nullptr; | ||||||
4427 | |||||||
4428 | // Note that the above type specs guarantee that the | ||||||
4429 | // type rep is a Decl, whereas in many of the others | ||||||
4430 | // it's a Type. | ||||||
4431 | if (isa<TagDecl>(TagD)) | ||||||
4432 | Tag = cast<TagDecl>(TagD); | ||||||
4433 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) | ||||||
4434 | Tag = CTD->getTemplatedDecl(); | ||||||
4435 | } | ||||||
4436 | |||||||
4437 | if (Tag) { | ||||||
4438 | handleTagNumbering(Tag, S); | ||||||
4439 | Tag->setFreeStanding(); | ||||||
4440 | if (Tag->isInvalidDecl()) | ||||||
4441 | return Tag; | ||||||
4442 | } | ||||||
4443 | |||||||
4444 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | ||||||
4445 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object | ||||||
4446 | // or incomplete types shall not be restrict-qualified." | ||||||
4447 | if (TypeQuals & DeclSpec::TQ_restrict) | ||||||
4448 | Diag(DS.getRestrictSpecLoc(), | ||||||
4449 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) | ||||||
4450 | << DS.getSourceRange(); | ||||||
4451 | } | ||||||
4452 | |||||||
4453 | if (DS.isInlineSpecified()) | ||||||
4454 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
4455 | << getLangOpts().CPlusPlus17; | ||||||
4456 | |||||||
4457 | if (DS.hasConstexprSpecifier()) { | ||||||
4458 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations | ||||||
4459 | // and definitions of functions and variables. | ||||||
4460 | // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to | ||||||
4461 | // the declaration of a function or function template | ||||||
4462 | if (Tag) | ||||||
4463 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) | ||||||
4464 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) | ||||||
4465 | << DS.getConstexprSpecifier(); | ||||||
4466 | else | ||||||
4467 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) | ||||||
4468 | << DS.getConstexprSpecifier(); | ||||||
4469 | // Don't emit warnings after this error. | ||||||
4470 | return TagD; | ||||||
4471 | } | ||||||
4472 | |||||||
4473 | DiagnoseFunctionSpecifiers(DS); | ||||||
4474 | |||||||
4475 | if (DS.isFriendSpecified()) { | ||||||
4476 | // If we're dealing with a decl but not a TagDecl, assume that | ||||||
4477 | // whatever routines created it handled the friendship aspect. | ||||||
4478 | if (TagD && !Tag) | ||||||
4479 | return nullptr; | ||||||
4480 | return ActOnFriendTypeDecl(S, DS, TemplateParams); | ||||||
4481 | } | ||||||
4482 | |||||||
4483 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); | ||||||
4484 | bool IsExplicitSpecialization = | ||||||
4485 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; | ||||||
4486 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && | ||||||
4487 | !IsExplicitInstantiation && !IsExplicitSpecialization && | ||||||
4488 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { | ||||||
4489 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a | ||||||
4490 | // nested-name-specifier unless it is an explicit instantiation | ||||||
4491 | // or an explicit specialization. | ||||||
4492 | // | ||||||
4493 | // FIXME: We allow class template partial specializations here too, per the | ||||||
4494 | // obvious intent of DR1819. | ||||||
4495 | // | ||||||
4496 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. | ||||||
4497 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) | ||||||
4498 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); | ||||||
4499 | return nullptr; | ||||||
4500 | } | ||||||
4501 | |||||||
4502 | // Track whether this decl-specifier declares anything. | ||||||
4503 | bool DeclaresAnything = true; | ||||||
4504 | |||||||
4505 | // Handle anonymous struct definitions. | ||||||
4506 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { | ||||||
4507 | if (!Record->getDeclName() && Record->isCompleteDefinition() && | ||||||
4508 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { | ||||||
4509 | if (getLangOpts().CPlusPlus || | ||||||
4510 | Record->getDeclContext()->isRecord()) { | ||||||
4511 | // If CurContext is a DeclContext that can contain statements, | ||||||
4512 | // RecursiveASTVisitor won't visit the decls that | ||||||
4513 | // BuildAnonymousStructOrUnion() will put into CurContext. | ||||||
4514 | // Also store them here so that they can be part of the | ||||||
4515 | // DeclStmt that gets created in this case. | ||||||
4516 | // FIXME: Also return the IndirectFieldDecls created by | ||||||
4517 | // BuildAnonymousStructOr union, for the same reason? | ||||||
4518 | if (CurContext->isFunctionOrMethod()) | ||||||
4519 | AnonRecord = Record; | ||||||
4520 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, | ||||||
4521 | Context.getPrintingPolicy()); | ||||||
4522 | } | ||||||
4523 | |||||||
4524 | DeclaresAnything = false; | ||||||
4525 | } | ||||||
4526 | } | ||||||
4527 | |||||||
4528 | // C11 6.7.2.1p2: | ||||||
4529 | // A struct-declaration that does not declare an anonymous structure or | ||||||
4530 | // anonymous union shall contain a struct-declarator-list. | ||||||
4531 | // | ||||||
4532 | // This rule also existed in C89 and C99; the grammar for struct-declaration | ||||||
4533 | // did not permit a struct-declaration without a struct-declarator-list. | ||||||
4534 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && | ||||||
4535 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { | ||||||
4536 | // Check for Microsoft C extension: anonymous struct/union member. | ||||||
4537 | // Handle 2 kinds of anonymous struct/union: | ||||||
4538 | // struct STRUCT; | ||||||
4539 | // union UNION; | ||||||
4540 | // and | ||||||
4541 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. | ||||||
4542 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. | ||||||
4543 | if ((Tag && Tag->getDeclName()) || | ||||||
4544 | DS.getTypeSpecType() == DeclSpec::TST_typename) { | ||||||
4545 | RecordDecl *Record = nullptr; | ||||||
4546 | if (Tag) | ||||||
4547 | Record = dyn_cast<RecordDecl>(Tag); | ||||||
4548 | else if (const RecordType *RT = | ||||||
4549 | DS.getRepAsType().get()->getAsStructureType()) | ||||||
4550 | Record = RT->getDecl(); | ||||||
4551 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) | ||||||
4552 | Record = UT->getDecl(); | ||||||
4553 | |||||||
4554 | if (Record && getLangOpts().MicrosoftExt) { | ||||||
4555 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) | ||||||
4556 | << Record->isUnion() << DS.getSourceRange(); | ||||||
4557 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); | ||||||
4558 | } | ||||||
4559 | |||||||
4560 | DeclaresAnything = false; | ||||||
4561 | } | ||||||
4562 | } | ||||||
4563 | |||||||
4564 | // Skip all the checks below if we have a type error. | ||||||
4565 | if (DS.getTypeSpecType() == DeclSpec::TST_error || | ||||||
4566 | (TagD && TagD->isInvalidDecl())) | ||||||
4567 | return TagD; | ||||||
4568 | |||||||
4569 | if (getLangOpts().CPlusPlus && | ||||||
4570 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) | ||||||
4571 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) | ||||||
4572 | if (Enum->enumerator_begin() == Enum->enumerator_end() && | ||||||
4573 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) | ||||||
4574 | DeclaresAnything = false; | ||||||
4575 | |||||||
4576 | if (!DS.isMissingDeclaratorOk()) { | ||||||
4577 | // Customize diagnostic for a typedef missing a name. | ||||||
4578 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||||
4579 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) | ||||||
4580 | << DS.getSourceRange(); | ||||||
4581 | else | ||||||
4582 | DeclaresAnything = false; | ||||||
4583 | } | ||||||
4584 | |||||||
4585 | if (DS.isModulePrivateSpecified() && | ||||||
4586 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) | ||||||
4587 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) | ||||||
4588 | << Tag->getTagKind() | ||||||
4589 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); | ||||||
4590 | |||||||
4591 | ActOnDocumentableDecl(TagD); | ||||||
4592 | |||||||
4593 | // C 6.7/2: | ||||||
4594 | // A declaration [...] shall declare at least a declarator [...], a tag, | ||||||
4595 | // or the members of an enumeration. | ||||||
4596 | // C++ [dcl.dcl]p3: | ||||||
4597 | // [If there are no declarators], and except for the declaration of an | ||||||
4598 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||||
4599 | // names into the program, or shall redeclare a name introduced by a | ||||||
4600 | // previous declaration. | ||||||
4601 | if (!DeclaresAnything) { | ||||||
4602 | // In C, we allow this as a (popular) extension / bug. Don't bother | ||||||
4603 | // producing further diagnostics for redundant qualifiers after this. | ||||||
4604 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | ||||||
4605 | return TagD; | ||||||
4606 | } | ||||||
4607 | |||||||
4608 | // C++ [dcl.stc]p1: | ||||||
4609 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the | ||||||
4610 | // init-declarator-list of the declaration shall not be empty. | ||||||
4611 | // C++ [dcl.fct.spec]p1: | ||||||
4612 | // If a cv-qualifier appears in a decl-specifier-seq, the | ||||||
4613 | // init-declarator-list of the declaration shall not be empty. | ||||||
4614 | // | ||||||
4615 | // Spurious qualifiers here appear to be valid in C. | ||||||
4616 | unsigned DiagID = diag::warn_standalone_specifier; | ||||||
4617 | if (getLangOpts().CPlusPlus) | ||||||
4618 | DiagID = diag::ext_standalone_specifier; | ||||||
4619 | |||||||
4620 | // Note that a linkage-specification sets a storage class, but | ||||||
4621 | // 'extern "C" struct foo;' is actually valid and not theoretically | ||||||
4622 | // useless. | ||||||
4623 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { | ||||||
4624 | if (SCS == DeclSpec::SCS_mutable) | ||||||
4625 | // Since mutable is not a viable storage class specifier in C, there is | ||||||
4626 | // no reason to treat it as an extension. Instead, diagnose as an error. | ||||||
4627 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); | ||||||
4628 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) | ||||||
4629 | Diag(DS.getStorageClassSpecLoc(), DiagID) | ||||||
4630 | << DeclSpec::getSpecifierName(SCS); | ||||||
4631 | } | ||||||
4632 | |||||||
4633 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||||
4634 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) | ||||||
4635 | << DeclSpec::getSpecifierName(TSCS); | ||||||
4636 | if (DS.getTypeQualifiers()) { | ||||||
4637 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||||
4638 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; | ||||||
4639 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||||
4640 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; | ||||||
4641 | // Restrict is covered above. | ||||||
4642 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||||
4643 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; | ||||||
4644 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||||
4645 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; | ||||||
4646 | } | ||||||
4647 | |||||||
4648 | // Warn about ignored type attributes, for example: | ||||||
4649 | // __attribute__((aligned)) struct A; | ||||||
4650 | // Attributes should be placed after tag to apply to type declaration. | ||||||
4651 | if (!DS.getAttributes().empty()) { | ||||||
4652 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); | ||||||
4653 | if (TypeSpecType == DeclSpec::TST_class || | ||||||
4654 | TypeSpecType == DeclSpec::TST_struct || | ||||||
4655 | TypeSpecType == DeclSpec::TST_interface || | ||||||
4656 | TypeSpecType == DeclSpec::TST_union || | ||||||
4657 | TypeSpecType == DeclSpec::TST_enum) { | ||||||
4658 | for (const ParsedAttr &AL : DS.getAttributes()) | ||||||
4659 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) | ||||||
4660 | << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); | ||||||
4661 | } | ||||||
4662 | } | ||||||
4663 | |||||||
4664 | return TagD; | ||||||
4665 | } | ||||||
4666 | |||||||
4667 | /// We are trying to inject an anonymous member into the given scope; | ||||||
4668 | /// check if there's an existing declaration that can't be overloaded. | ||||||
4669 | /// | ||||||
4670 | /// \return true if this is a forbidden redeclaration | ||||||
4671 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, | ||||||
4672 | Scope *S, | ||||||
4673 | DeclContext *Owner, | ||||||
4674 | DeclarationName Name, | ||||||
4675 | SourceLocation NameLoc, | ||||||
4676 | bool IsUnion) { | ||||||
4677 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, | ||||||
4678 | Sema::ForVisibleRedeclaration); | ||||||
4679 | if (!SemaRef.LookupName(R, S)) return false; | ||||||
4680 | |||||||
4681 | // Pick a representative declaration. | ||||||
4682 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); | ||||||
4683 | assert(PrevDecl && "Expected a non-null Decl")((PrevDecl && "Expected a non-null Decl") ? static_cast <void> (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4683, __PRETTY_FUNCTION__)); | ||||||
4684 | |||||||
4685 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) | ||||||
4686 | return false; | ||||||
4687 | |||||||
4688 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) | ||||||
4689 | << IsUnion << Name; | ||||||
4690 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
4691 | |||||||
4692 | return true; | ||||||
4693 | } | ||||||
4694 | |||||||
4695 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the | ||||||
4696 | /// anonymous struct or union AnonRecord into the owning context Owner | ||||||
4697 | /// and scope S. This routine will be invoked just after we realize | ||||||
4698 | /// that an unnamed union or struct is actually an anonymous union or | ||||||
4699 | /// struct, e.g., | ||||||
4700 | /// | ||||||
4701 | /// @code | ||||||
4702 | /// union { | ||||||
4703 | /// int i; | ||||||
4704 | /// float f; | ||||||
4705 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and | ||||||
4706 | /// // f into the surrounding scope.x | ||||||
4707 | /// @endcode | ||||||
4708 | /// | ||||||
4709 | /// This routine is recursive, injecting the names of nested anonymous | ||||||
4710 | /// structs/unions into the owning context and scope as well. | ||||||
4711 | static bool | ||||||
4712 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, | ||||||
4713 | RecordDecl *AnonRecord, AccessSpecifier AS, | ||||||
4714 | SmallVectorImpl<NamedDecl *> &Chaining) { | ||||||
4715 | bool Invalid = false; | ||||||
4716 | |||||||
4717 | // Look every FieldDecl and IndirectFieldDecl with a name. | ||||||
4718 | for (auto *D : AnonRecord->decls()) { | ||||||
4719 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && | ||||||
4720 | cast<NamedDecl>(D)->getDeclName()) { | ||||||
4721 | ValueDecl *VD = cast<ValueDecl>(D); | ||||||
4722 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), | ||||||
4723 | VD->getLocation(), | ||||||
4724 | AnonRecord->isUnion())) { | ||||||
4725 | // C++ [class.union]p2: | ||||||
4726 | // The names of the members of an anonymous union shall be | ||||||
4727 | // distinct from the names of any other entity in the | ||||||
4728 | // scope in which the anonymous union is declared. | ||||||
4729 | Invalid = true; | ||||||
4730 | } else { | ||||||
4731 | // C++ [class.union]p2: | ||||||
4732 | // For the purpose of name lookup, after the anonymous union | ||||||
4733 | // definition, the members of the anonymous union are | ||||||
4734 | // considered to have been defined in the scope in which the | ||||||
4735 | // anonymous union is declared. | ||||||
4736 | unsigned OldChainingSize = Chaining.size(); | ||||||
4737 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) | ||||||
4738 | Chaining.append(IF->chain_begin(), IF->chain_end()); | ||||||
4739 | else | ||||||
4740 | Chaining.push_back(VD); | ||||||
4741 | |||||||
4742 | assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4742, __PRETTY_FUNCTION__)); | ||||||
4743 | NamedDecl **NamedChain = | ||||||
4744 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; | ||||||
4745 | for (unsigned i = 0; i < Chaining.size(); i++) | ||||||
4746 | NamedChain[i] = Chaining[i]; | ||||||
4747 | |||||||
4748 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( | ||||||
4749 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), | ||||||
4750 | VD->getType(), {NamedChain, Chaining.size()}); | ||||||
4751 | |||||||
4752 | for (const auto *Attr : VD->attrs()) | ||||||
4753 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); | ||||||
4754 | |||||||
4755 | IndirectField->setAccess(AS); | ||||||
4756 | IndirectField->setImplicit(); | ||||||
4757 | SemaRef.PushOnScopeChains(IndirectField, S); | ||||||
4758 | |||||||
4759 | // That includes picking up the appropriate access specifier. | ||||||
4760 | if (AS != AS_none) IndirectField->setAccess(AS); | ||||||
4761 | |||||||
4762 | Chaining.resize(OldChainingSize); | ||||||
4763 | } | ||||||
4764 | } | ||||||
4765 | } | ||||||
4766 | |||||||
4767 | return Invalid; | ||||||
4768 | } | ||||||
4769 | |||||||
4770 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to | ||||||
4771 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: | ||||||
4772 | /// illegal input values are mapped to SC_None. | ||||||
4773 | static StorageClass | ||||||
4774 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { | ||||||
4775 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); | ||||||
4776 | assert(StorageClassSpec != DeclSpec::SCS_typedef &&((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4777, __PRETTY_FUNCTION__)) | ||||||
4777 | "Parser allowed 'typedef' as storage class VarDecl.")((StorageClassSpec != DeclSpec::SCS_typedef && "Parser allowed 'typedef' as storage class VarDecl." ) ? static_cast<void> (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4777, __PRETTY_FUNCTION__)); | ||||||
4778 | switch (StorageClassSpec) { | ||||||
4779 | case DeclSpec::SCS_unspecified: return SC_None; | ||||||
4780 | case DeclSpec::SCS_extern: | ||||||
4781 | if (DS.isExternInLinkageSpec()) | ||||||
4782 | return SC_None; | ||||||
4783 | return SC_Extern; | ||||||
4784 | case DeclSpec::SCS_static: return SC_Static; | ||||||
4785 | case DeclSpec::SCS_auto: return SC_Auto; | ||||||
4786 | case DeclSpec::SCS_register: return SC_Register; | ||||||
4787 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||||
4788 | // Illegal SCSs map to None: error reporting is up to the caller. | ||||||
4789 | case DeclSpec::SCS_mutable: // Fall through. | ||||||
4790 | case DeclSpec::SCS_typedef: return SC_None; | ||||||
4791 | } | ||||||
4792 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4792); | ||||||
4793 | } | ||||||
4794 | |||||||
4795 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { | ||||||
4796 | assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void> (0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4796, __PRETTY_FUNCTION__)); | ||||||
4797 | |||||||
4798 | for (const auto *I : Record->decls()) { | ||||||
4799 | const auto *FD = dyn_cast<FieldDecl>(I); | ||||||
4800 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||||
4801 | FD = IFD->getAnonField(); | ||||||
4802 | if (FD && FD->hasInClassInitializer()) | ||||||
4803 | return FD->getLocation(); | ||||||
4804 | } | ||||||
4805 | |||||||
4806 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4806); | ||||||
4807 | } | ||||||
4808 | |||||||
4809 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||||
4810 | SourceLocation DefaultInitLoc) { | ||||||
4811 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||||
4812 | return; | ||||||
4813 | |||||||
4814 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); | ||||||
4815 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; | ||||||
4816 | } | ||||||
4817 | |||||||
4818 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||||
4819 | CXXRecordDecl *AnonUnion) { | ||||||
4820 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||||
4821 | return; | ||||||
4822 | |||||||
4823 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); | ||||||
4824 | } | ||||||
4825 | |||||||
4826 | /// BuildAnonymousStructOrUnion - Handle the declaration of an | ||||||
4827 | /// anonymous structure or union. Anonymous unions are a C++ feature | ||||||
4828 | /// (C++ [class.union]) and a C11 feature; anonymous structures | ||||||
4829 | /// are a C11 feature and GNU C++ extension. | ||||||
4830 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | ||||||
4831 | AccessSpecifier AS, | ||||||
4832 | RecordDecl *Record, | ||||||
4833 | const PrintingPolicy &Policy) { | ||||||
4834 | DeclContext *Owner = Record->getDeclContext(); | ||||||
4835 | |||||||
4836 | // Diagnose whether this anonymous struct/union is an extension. | ||||||
4837 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) | ||||||
4838 | Diag(Record->getLocation(), diag::ext_anonymous_union); | ||||||
4839 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) | ||||||
4840 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); | ||||||
4841 | else if (!Record->isUnion() && !getLangOpts().C11) | ||||||
4842 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); | ||||||
4843 | |||||||
4844 | // C and C++ require different kinds of checks for anonymous | ||||||
4845 | // structs/unions. | ||||||
4846 | bool Invalid = false; | ||||||
4847 | if (getLangOpts().CPlusPlus) { | ||||||
4848 | const char *PrevSpec = nullptr; | ||||||
4849 | if (Record->isUnion()) { | ||||||
4850 | // C++ [class.union]p6: | ||||||
4851 | // C++17 [class.union.anon]p2: | ||||||
4852 | // Anonymous unions declared in a named namespace or in the | ||||||
4853 | // global namespace shall be declared static. | ||||||
4854 | unsigned DiagID; | ||||||
4855 | DeclContext *OwnerScope = Owner->getRedeclContext(); | ||||||
4856 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && | ||||||
4857 | (OwnerScope->isTranslationUnit() || | ||||||
4858 | (OwnerScope->isNamespace() && | ||||||
4859 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { | ||||||
4860 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) | ||||||
4861 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); | ||||||
4862 | |||||||
4863 | // Recover by adding 'static'. | ||||||
4864 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), | ||||||
4865 | PrevSpec, DiagID, Policy); | ||||||
4866 | } | ||||||
4867 | // C++ [class.union]p6: | ||||||
4868 | // A storage class is not allowed in a declaration of an | ||||||
4869 | // anonymous union in a class scope. | ||||||
4870 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && | ||||||
4871 | isa<RecordDecl>(Owner)) { | ||||||
4872 | Diag(DS.getStorageClassSpecLoc(), | ||||||
4873 | diag::err_anonymous_union_with_storage_spec) | ||||||
4874 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
4875 | |||||||
4876 | // Recover by removing the storage specifier. | ||||||
4877 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, | ||||||
4878 | SourceLocation(), | ||||||
4879 | PrevSpec, DiagID, Context.getPrintingPolicy()); | ||||||
4880 | } | ||||||
4881 | } | ||||||
4882 | |||||||
4883 | // Ignore const/volatile/restrict qualifiers. | ||||||
4884 | if (DS.getTypeQualifiers()) { | ||||||
4885 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||||
4886 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) | ||||||
4887 | << Record->isUnion() << "const" | ||||||
4888 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); | ||||||
4889 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||||
4890 | Diag(DS.getVolatileSpecLoc(), | ||||||
4891 | diag::ext_anonymous_struct_union_qualified) | ||||||
4892 | << Record->isUnion() << "volatile" | ||||||
4893 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); | ||||||
4894 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | ||||||
4895 | Diag(DS.getRestrictSpecLoc(), | ||||||
4896 | diag::ext_anonymous_struct_union_qualified) | ||||||
4897 | << Record->isUnion() << "restrict" | ||||||
4898 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); | ||||||
4899 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||||
4900 | Diag(DS.getAtomicSpecLoc(), | ||||||
4901 | diag::ext_anonymous_struct_union_qualified) | ||||||
4902 | << Record->isUnion() << "_Atomic" | ||||||
4903 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); | ||||||
4904 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||||
4905 | Diag(DS.getUnalignedSpecLoc(), | ||||||
4906 | diag::ext_anonymous_struct_union_qualified) | ||||||
4907 | << Record->isUnion() << "__unaligned" | ||||||
4908 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); | ||||||
4909 | |||||||
4910 | DS.ClearTypeQualifiers(); | ||||||
4911 | } | ||||||
4912 | |||||||
4913 | // C++ [class.union]p2: | ||||||
4914 | // The member-specification of an anonymous union shall only | ||||||
4915 | // define non-static data members. [Note: nested types and | ||||||
4916 | // functions cannot be declared within an anonymous union. ] | ||||||
4917 | for (auto *Mem : Record->decls()) { | ||||||
4918 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { | ||||||
4919 | // C++ [class.union]p3: | ||||||
4920 | // An anonymous union shall not have private or protected | ||||||
4921 | // members (clause 11). | ||||||
4922 | assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0 ) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 4922, __PRETTY_FUNCTION__)); | ||||||
4923 | if (FD->getAccess() != AS_public) { | ||||||
4924 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) | ||||||
4925 | << Record->isUnion() << (FD->getAccess() == AS_protected); | ||||||
4926 | Invalid = true; | ||||||
4927 | } | ||||||
4928 | |||||||
4929 | // C++ [class.union]p1 | ||||||
4930 | // An object of a class with a non-trivial constructor, a non-trivial | ||||||
4931 | // copy constructor, a non-trivial destructor, or a non-trivial copy | ||||||
4932 | // assignment operator cannot be a member of a union, nor can an | ||||||
4933 | // array of such objects. | ||||||
4934 | if (CheckNontrivialField(FD)) | ||||||
4935 | Invalid = true; | ||||||
4936 | } else if (Mem->isImplicit()) { | ||||||
4937 | // Any implicit members are fine. | ||||||
4938 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { | ||||||
4939 | // This is a type that showed up in an | ||||||
4940 | // elaborated-type-specifier inside the anonymous struct or | ||||||
4941 | // union, but which actually declares a type outside of the | ||||||
4942 | // anonymous struct or union. It's okay. | ||||||
4943 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { | ||||||
4944 | if (!MemRecord->isAnonymousStructOrUnion() && | ||||||
4945 | MemRecord->getDeclName()) { | ||||||
4946 | // Visual C++ allows type definition in anonymous struct or union. | ||||||
4947 | if (getLangOpts().MicrosoftExt) | ||||||
4948 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) | ||||||
4949 | << Record->isUnion(); | ||||||
4950 | else { | ||||||
4951 | // This is a nested type declaration. | ||||||
4952 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) | ||||||
4953 | << Record->isUnion(); | ||||||
4954 | Invalid = true; | ||||||
4955 | } | ||||||
4956 | } else { | ||||||
4957 | // This is an anonymous type definition within another anonymous type. | ||||||
4958 | // This is a popular extension, provided by Plan9, MSVC and GCC, but | ||||||
4959 | // not part of standard C++. | ||||||
4960 | Diag(MemRecord->getLocation(), | ||||||
4961 | diag::ext_anonymous_record_with_anonymous_type) | ||||||
4962 | << Record->isUnion(); | ||||||
4963 | } | ||||||
4964 | } else if (isa<AccessSpecDecl>(Mem)) { | ||||||
4965 | // Any access specifier is fine. | ||||||
4966 | } else if (isa<StaticAssertDecl>(Mem)) { | ||||||
4967 | // In C++1z, static_assert declarations are also fine. | ||||||
4968 | } else { | ||||||
4969 | // We have something that isn't a non-static data | ||||||
4970 | // member. Complain about it. | ||||||
4971 | unsigned DK = diag::err_anonymous_record_bad_member; | ||||||
4972 | if (isa<TypeDecl>(Mem)) | ||||||
4973 | DK = diag::err_anonymous_record_with_type; | ||||||
4974 | else if (isa<FunctionDecl>(Mem)) | ||||||
4975 | DK = diag::err_anonymous_record_with_function; | ||||||
4976 | else if (isa<VarDecl>(Mem)) | ||||||
4977 | DK = diag::err_anonymous_record_with_static; | ||||||
4978 | |||||||
4979 | // Visual C++ allows type definition in anonymous struct or union. | ||||||
4980 | if (getLangOpts().MicrosoftExt && | ||||||
4981 | DK == diag::err_anonymous_record_with_type) | ||||||
4982 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) | ||||||
4983 | << Record->isUnion(); | ||||||
4984 | else { | ||||||
4985 | Diag(Mem->getLocation(), DK) << Record->isUnion(); | ||||||
4986 | Invalid = true; | ||||||
4987 | } | ||||||
4988 | } | ||||||
4989 | } | ||||||
4990 | |||||||
4991 | // C++11 [class.union]p8 (DR1460): | ||||||
4992 | // At most one variant member of a union may have a | ||||||
4993 | // brace-or-equal-initializer. | ||||||
4994 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && | ||||||
4995 | Owner->isRecord()) | ||||||
4996 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), | ||||||
4997 | cast<CXXRecordDecl>(Record)); | ||||||
4998 | } | ||||||
4999 | |||||||
5000 | if (!Record->isUnion() && !Owner->isRecord()) { | ||||||
5001 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) | ||||||
5002 | << getLangOpts().CPlusPlus; | ||||||
5003 | Invalid = true; | ||||||
5004 | } | ||||||
5005 | |||||||
5006 | // C++ [dcl.dcl]p3: | ||||||
5007 | // [If there are no declarators], and except for the declaration of an | ||||||
5008 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||||
5009 | // names into the program | ||||||
5010 | // C++ [class.mem]p2: | ||||||
5011 | // each such member-declaration shall either declare at least one member | ||||||
5012 | // name of the class or declare at least one unnamed bit-field | ||||||
5013 | // | ||||||
5014 | // For C this is an error even for a named struct, and is diagnosed elsewhere. | ||||||
5015 | if (getLangOpts().CPlusPlus && Record->field_empty()) | ||||||
5016 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | ||||||
5017 | |||||||
5018 | // Mock up a declarator. | ||||||
5019 | Declarator Dc(DS, DeclaratorContext::MemberContext); | ||||||
5020 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||||
5021 | assert(TInfo && "couldn't build declarator info for anonymous struct/union")((TInfo && "couldn't build declarator info for anonymous struct/union" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 5021, __PRETTY_FUNCTION__)); | ||||||
5022 | |||||||
5023 | // Create a declaration for this anonymous struct/union. | ||||||
5024 | NamedDecl *Anon = nullptr; | ||||||
5025 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { | ||||||
5026 | Anon = FieldDecl::Create( | ||||||
5027 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), | ||||||
5028 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, | ||||||
5029 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||||
5030 | /*InitStyle=*/ICIS_NoInit); | ||||||
5031 | Anon->setAccess(AS); | ||||||
5032 | ProcessDeclAttributes(S, Anon, Dc); | ||||||
5033 | |||||||
5034 | if (getLangOpts().CPlusPlus) | ||||||
5035 | FieldCollector->Add(cast<FieldDecl>(Anon)); | ||||||
5036 | } else { | ||||||
5037 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); | ||||||
5038 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); | ||||||
5039 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||||
5040 | // mutable can only appear on non-static class members, so it's always | ||||||
5041 | // an error here | ||||||
5042 | Diag(Record->getLocation(), diag::err_mutable_nonmember); | ||||||
5043 | Invalid = true; | ||||||
5044 | SC = SC_None; | ||||||
5045 | } | ||||||
5046 | |||||||
5047 | assert(DS.getAttributes().empty() && "No attribute expected")((DS.getAttributes().empty() && "No attribute expected" ) ? static_cast<void> (0) : __assert_fail ("DS.getAttributes().empty() && \"No attribute expected\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 5047, __PRETTY_FUNCTION__)); | ||||||
5048 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), | ||||||
5049 | Record->getLocation(), /*IdentifierInfo=*/nullptr, | ||||||
5050 | Context.getTypeDeclType(Record), TInfo, SC); | ||||||
5051 | |||||||
5052 | // Default-initialize the implicit variable. This initialization will be | ||||||
5053 | // trivial in almost all cases, except if a union member has an in-class | ||||||
5054 | // initializer: | ||||||
5055 | // union { int n = 0; }; | ||||||
5056 | ActOnUninitializedDecl(Anon); | ||||||
5057 | } | ||||||
5058 | Anon->setImplicit(); | ||||||
5059 | |||||||
5060 | // Mark this as an anonymous struct/union type. | ||||||
5061 | Record->setAnonymousStructOrUnion(true); | ||||||
5062 | |||||||
5063 | // Add the anonymous struct/union object to the current | ||||||
5064 | // context. We'll be referencing this object when we refer to one of | ||||||
5065 | // its members. | ||||||
5066 | Owner->addDecl(Anon); | ||||||
5067 | |||||||
5068 | // Inject the members of the anonymous struct/union into the owning | ||||||
5069 | // context and into the identifier resolver chain for name lookup | ||||||
5070 | // purposes. | ||||||
5071 | SmallVector<NamedDecl*, 2> Chain; | ||||||
5072 | Chain.push_back(Anon); | ||||||
5073 | |||||||
5074 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) | ||||||
5075 | Invalid = true; | ||||||
5076 | |||||||
5077 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { | ||||||
5078 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||||
5079 | MangleNumberingContext *MCtx; | ||||||
5080 | Decl *ManglingContextDecl; | ||||||
5081 | std::tie(MCtx, ManglingContextDecl) = | ||||||
5082 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | ||||||
5083 | if (MCtx) { | ||||||
5084 | Context.setManglingNumber( | ||||||
5085 | NewVD, MCtx->getManglingNumber( | ||||||
5086 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||||
5087 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||||
5088 | } | ||||||
5089 | } | ||||||
5090 | } | ||||||
5091 | |||||||
5092 | if (Invalid) | ||||||
5093 | Anon->setInvalidDecl(); | ||||||
5094 | |||||||
5095 | return Anon; | ||||||
5096 | } | ||||||
5097 | |||||||
5098 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an | ||||||
5099 | /// Microsoft C anonymous structure. | ||||||
5100 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx | ||||||
5101 | /// Example: | ||||||
5102 | /// | ||||||
5103 | /// struct A { int a; }; | ||||||
5104 | /// struct B { struct A; int b; }; | ||||||
5105 | /// | ||||||
5106 | /// void foo() { | ||||||
5107 | /// B var; | ||||||
5108 | /// var.a = 3; | ||||||
5109 | /// } | ||||||
5110 | /// | ||||||
5111 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | ||||||
5112 | RecordDecl *Record) { | ||||||
5113 | assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void > (0) : __assert_fail ("Record && \"expected a record!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 5113, __PRETTY_FUNCTION__)); | ||||||
5114 | |||||||
5115 | // Mock up a declarator. | ||||||
5116 | Declarator Dc(DS, DeclaratorContext::TypeNameContext); | ||||||
5117 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||||
5118 | assert(TInfo && "couldn't build declarator info for anonymous struct")((TInfo && "couldn't build declarator info for anonymous struct" ) ? static_cast<void> (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 5118, __PRETTY_FUNCTION__)); | ||||||
5119 | |||||||
5120 | auto *ParentDecl = cast<RecordDecl>(CurContext); | ||||||
5121 | QualType RecTy = Context.getTypeDeclType(Record); | ||||||
5122 | |||||||
5123 | // Create a declaration for this anonymous struct. | ||||||
5124 | NamedDecl *Anon = | ||||||
5125 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), | ||||||
5126 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, | ||||||
5127 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||||
5128 | /*InitStyle=*/ICIS_NoInit); | ||||||
5129 | Anon->setImplicit(); | ||||||
5130 | |||||||
5131 | // Add the anonymous struct object to the current context. | ||||||
5132 | CurContext->addDecl(Anon); | ||||||
5133 | |||||||
5134 | // Inject the members of the anonymous struct into the current | ||||||
5135 | // context and into the identifier resolver chain for name lookup | ||||||
5136 | // purposes. | ||||||
5137 | SmallVector<NamedDecl*, 2> Chain; | ||||||
5138 | Chain.push_back(Anon); | ||||||
5139 | |||||||
5140 | RecordDecl *RecordDef = Record->getDefinition(); | ||||||
5141 | if (RequireCompleteType(Anon->getLocation(), RecTy, | ||||||
5142 | diag::err_field_incomplete) || | ||||||
5143 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, | ||||||
5144 | AS_none, Chain)) { | ||||||
5145 | Anon->setInvalidDecl(); | ||||||
5146 | ParentDecl->setInvalidDecl(); | ||||||
5147 | } | ||||||
5148 | |||||||
5149 | return Anon; | ||||||
5150 | } | ||||||
5151 | |||||||
5152 | /// GetNameForDeclarator - Determine the full declaration name for the | ||||||
5153 | /// given Declarator. | ||||||
5154 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { | ||||||
5155 | return GetNameFromUnqualifiedId(D.getName()); | ||||||
5156 | } | ||||||
5157 | |||||||
5158 | /// Retrieves the declaration name from a parsed unqualified-id. | ||||||
5159 | DeclarationNameInfo | ||||||
5160 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { | ||||||
5161 | DeclarationNameInfo NameInfo; | ||||||
5162 | NameInfo.setLoc(Name.StartLocation); | ||||||
5163 | |||||||
5164 | switch (Name.getKind()) { | ||||||
5165 | |||||||
5166 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||||
5167 | case UnqualifiedIdKind::IK_Identifier: | ||||||
5168 | NameInfo.setName(Name.Identifier); | ||||||
5169 | return NameInfo; | ||||||
5170 | |||||||
5171 | case UnqualifiedIdKind::IK_DeductionGuideName: { | ||||||
5172 | // C++ [temp.deduct.guide]p3: | ||||||
5173 | // The simple-template-id shall name a class template specialization. | ||||||
5174 | // The template-name shall be the same identifier as the template-name | ||||||
5175 | // of the simple-template-id. | ||||||
5176 | // These together intend to imply that the template-name shall name a | ||||||
5177 | // class template. | ||||||
5178 | // FIXME: template<typename T> struct X {}; | ||||||
5179 | // template<typename T> using Y = X<T>; | ||||||
5180 | // Y(int) -> Y<int>; | ||||||
5181 | // satisfies these rules but does not name a class template. | ||||||
5182 | TemplateName TN = Name.TemplateName.get().get(); | ||||||
5183 | auto *Template = TN.getAsTemplateDecl(); | ||||||
5184 | if (!Template || !isa<ClassTemplateDecl>(Template)) { | ||||||
5185 | Diag(Name.StartLocation, | ||||||
5186 | diag::err_deduction_guide_name_not_class_template) | ||||||
5187 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; | ||||||
5188 | if (Template) | ||||||
5189 | Diag(Template->getLocation(), diag::note_template_decl_here); | ||||||
5190 | return DeclarationNameInfo(); | ||||||
5191 | } | ||||||
5192 | |||||||
5193 | NameInfo.setName( | ||||||
5194 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); | ||||||
5195 | return NameInfo; | ||||||
5196 | } | ||||||
5197 | |||||||
5198 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||||
5199 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( | ||||||
5200 | Name.OperatorFunctionId.Operator)); | ||||||
5201 | NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc | ||||||
5202 | = Name.OperatorFunctionId.SymbolLocations[0]; | ||||||
5203 | NameInfo.getInfo().CXXOperatorName.EndOpNameLoc | ||||||
5204 | = Name.EndLocation.getRawEncoding(); | ||||||
5205 | return NameInfo; | ||||||
5206 | |||||||
5207 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||||
5208 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( | ||||||
5209 | Name.Identifier)); | ||||||
5210 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); | ||||||
5211 | return NameInfo; | ||||||
5212 | |||||||
5213 | case UnqualifiedIdKind::IK_ConversionFunctionId: { | ||||||
5214 | TypeSourceInfo *TInfo; | ||||||
5215 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); | ||||||
5216 | if (Ty.isNull()) | ||||||
5217 | return DeclarationNameInfo(); | ||||||
5218 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( | ||||||
5219 | Context.getCanonicalType(Ty))); | ||||||
5220 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5221 | return NameInfo; | ||||||
5222 | } | ||||||
5223 | |||||||
5224 | case UnqualifiedIdKind::IK_ConstructorName: { | ||||||
5225 | TypeSourceInfo *TInfo; | ||||||
5226 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); | ||||||
5227 | if (Ty.isNull()) | ||||||
5228 | return DeclarationNameInfo(); | ||||||
5229 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||||
5230 | Context.getCanonicalType(Ty))); | ||||||
5231 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5232 | return NameInfo; | ||||||
5233 | } | ||||||
5234 | |||||||
5235 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { | ||||||
5236 | // In well-formed code, we can only have a constructor | ||||||
5237 | // template-id that refers to the current context, so go there | ||||||
5238 | // to find the actual type being constructed. | ||||||
5239 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); | ||||||
5240 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) | ||||||
5241 | return DeclarationNameInfo(); | ||||||
5242 | |||||||
5243 | // Determine the type of the class being constructed. | ||||||
5244 | QualType CurClassType = Context.getTypeDeclType(CurClass); | ||||||
5245 | |||||||
5246 | // FIXME: Check two things: that the template-id names the same type as | ||||||
5247 | // CurClassType, and that the template-id does not occur when the name | ||||||
5248 | // was qualified. | ||||||
5249 | |||||||
5250 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||||
5251 | Context.getCanonicalType(CurClassType))); | ||||||
5252 | // FIXME: should we retrieve TypeSourceInfo? | ||||||
5253 | NameInfo.setNamedTypeInfo(nullptr); | ||||||
5254 | return NameInfo; | ||||||
5255 | } | ||||||
5256 | |||||||
5257 | case UnqualifiedIdKind::IK_DestructorName: { | ||||||
5258 | TypeSourceInfo *TInfo; | ||||||
5259 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); | ||||||
5260 | if (Ty.isNull()) | ||||||
5261 | return DeclarationNameInfo(); | ||||||
5262 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( | ||||||
5263 | Context.getCanonicalType(Ty))); | ||||||
5264 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5265 | return NameInfo; | ||||||
5266 | } | ||||||
5267 | |||||||
5268 | case UnqualifiedIdKind::IK_TemplateId: { | ||||||
5269 | TemplateName TName = Name.TemplateId->Template.get(); | ||||||
5270 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; | ||||||
5271 | return Context.getNameForTemplate(TName, TNameLoc); | ||||||
5272 | } | ||||||
5273 | |||||||
5274 | } // switch (Name.getKind()) | ||||||
5275 | |||||||
5276 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 5276); | ||||||
5277 | } | ||||||
5278 | |||||||
5279 | static QualType getCoreType(QualType Ty) { | ||||||
5280 | do { | ||||||
5281 | if (Ty->isPointerType() || Ty->isReferenceType()) | ||||||
5282 | Ty = Ty->getPointeeType(); | ||||||
5283 | else if (Ty->isArrayType()) | ||||||
5284 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); | ||||||
5285 | else | ||||||
5286 | return Ty.withoutLocalFastQualifiers(); | ||||||
5287 | } while (true); | ||||||
5288 | } | ||||||
5289 | |||||||
5290 | /// hasSimilarParameters - Determine whether the C++ functions Declaration | ||||||
5291 | /// and Definition have "nearly" matching parameters. This heuristic is | ||||||
5292 | /// used to improve diagnostics in the case where an out-of-line function | ||||||
5293 | /// definition doesn't match any declaration within the class or namespace. | ||||||
5294 | /// Also sets Params to the list of indices to the parameters that differ | ||||||
5295 | /// between the declaration and the definition. If hasSimilarParameters | ||||||
5296 | /// returns true and Params is empty, then all of the parameters match. | ||||||
5297 | static bool hasSimilarParameters(ASTContext &Context, | ||||||
5298 | FunctionDecl *Declaration, | ||||||
5299 | FunctionDecl *Definition, | ||||||
5300 | SmallVectorImpl<unsigned> &Params) { | ||||||
5301 | Params.clear(); | ||||||
5302 | if (Declaration->param_size() != Definition->param_size()) | ||||||
5303 | return false; | ||||||
5304 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { | ||||||
5305 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); | ||||||
5306 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); | ||||||
5307 | |||||||
5308 | // The parameter types are identical | ||||||
5309 | if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) | ||||||
5310 | continue; | ||||||
5311 | |||||||
5312 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); | ||||||
5313 | QualType DefParamBaseTy = getCoreType(DefParamTy); | ||||||
5314 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); | ||||||
5315 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); | ||||||
5316 | |||||||
5317 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || | ||||||
5318 | (DeclTyName && DeclTyName == DefTyName)) | ||||||
5319 | Params.push_back(Idx); | ||||||
5320 | else // The two parameters aren't even close | ||||||
5321 | return false; | ||||||
5322 | } | ||||||
5323 | |||||||
5324 | return true; | ||||||
5325 | } | ||||||
5326 | |||||||
5327 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given | ||||||
5328 | /// declarator needs to be rebuilt in the current instantiation. | ||||||
5329 | /// Any bits of declarator which appear before the name are valid for | ||||||
5330 | /// consideration here. That's specifically the type in the decl spec | ||||||
5331 | /// and the base type in any member-pointer chunks. | ||||||
5332 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, | ||||||
5333 | DeclarationName Name) { | ||||||
5334 | // The types we specifically need to rebuild are: | ||||||
5335 | // - typenames, typeofs, and decltypes | ||||||
5336 | // - types which will become injected class names | ||||||
5337 | // Of course, we also need to rebuild any type referencing such a | ||||||
5338 | // type. It's safest to just say "dependent", but we call out a | ||||||
5339 | // few cases here. | ||||||
5340 | |||||||
5341 | DeclSpec &DS = D.getMutableDeclSpec(); | ||||||
5342 | switch (DS.getTypeSpecType()) { | ||||||
5343 | case DeclSpec::TST_typename: | ||||||
5344 | case DeclSpec::TST_typeofType: | ||||||
5345 | case DeclSpec::TST_underlyingType: | ||||||
5346 | case DeclSpec::TST_atomic: { | ||||||
5347 | // Grab the type from the parser. | ||||||
5348 | TypeSourceInfo *TSI = nullptr; | ||||||
5349 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); | ||||||
5350 | if (T.isNull() || !T->isDependentType()) break; | ||||||
5351 | |||||||
5352 | // Make sure there's a type source info. This isn't really much | ||||||
5353 | // of a waste; most dependent types should have type source info | ||||||
5354 | // attached already. | ||||||
5355 | if (!TSI) | ||||||
5356 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); | ||||||
5357 | |||||||
5358 | // Rebuild the type in the current instantiation. | ||||||
5359 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); | ||||||
5360 | if (!TSI) return true; | ||||||
5361 | |||||||
5362 | // Store the new type back in the decl spec. | ||||||
5363 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); | ||||||
5364 | DS.UpdateTypeRep(LocType); | ||||||
5365 | break; | ||||||
5366 | } | ||||||
5367 | |||||||
5368 | case DeclSpec::TST_decltype: | ||||||
5369 | case DeclSpec::TST_typeofExpr: { | ||||||
5370 | Expr *E = DS.getRepAsExpr(); | ||||||
5371 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); | ||||||
5372 | if (Result.isInvalid()) return true; | ||||||
5373 | DS.UpdateExprRep(Result.get()); | ||||||
5374 | break; | ||||||
5375 | } | ||||||
5376 | |||||||
5377 | default: | ||||||
5378 | // Nothing to do for these decl specs. | ||||||
5379 | break; | ||||||
5380 | } | ||||||
5381 | |||||||
5382 | // It doesn't matter what order we do this in. | ||||||
5383 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | ||||||
5384 | DeclaratorChunk &Chunk = D.getTypeObject(I); | ||||||
5385 | |||||||
5386 | // The only type information in the declarator which can come | ||||||
5387 | // before the declaration name is the base type of a member | ||||||
5388 | // pointer. | ||||||
5389 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) | ||||||
5390 | continue; | ||||||
5391 | |||||||
5392 | // Rebuild the scope specifier in-place. | ||||||
5393 | CXXScopeSpec &SS = Chunk.Mem.Scope(); | ||||||
5394 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) | ||||||
5395 | return true; | ||||||
5396 | } | ||||||
5397 | |||||||
5398 | return false; | ||||||
5399 | } | ||||||
5400 | |||||||
5401 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { | ||||||
5402 | D.setFunctionDefinitionKind(FDK_Declaration); | ||||||
5403 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); | ||||||
5404 | |||||||
5405 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && | ||||||
5406 | Dcl && Dcl->getDeclContext()->isFileContext()) | ||||||
5407 | Dcl->setTopLevelDeclInObjCContainer(); | ||||||
5408 | |||||||
5409 | if (getLangOpts().OpenCL) | ||||||
5410 | setCurrentOpenCLExtensionForDecl(Dcl); | ||||||
5411 | |||||||
5412 | return Dcl; | ||||||
5413 | } | ||||||
5414 | |||||||
5415 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: | ||||||
5416 | /// If T is the name of a class, then each of the following shall have a | ||||||
5417 | /// name different from T: | ||||||
5418 | /// - every static data member of class T; | ||||||
5419 | /// - every member function of class T | ||||||
5420 | /// - every member of class T that is itself a type; | ||||||
5421 | /// \returns true if the declaration name violates these rules. | ||||||
5422 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, | ||||||
5423 | DeclarationNameInfo NameInfo) { | ||||||
5424 | DeclarationName Name = NameInfo.getName(); | ||||||
5425 | |||||||
5426 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); | ||||||
5427 | while (Record && Record->isAnonymousStructOrUnion()) | ||||||
5428 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); | ||||||
5429 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { | ||||||
5430 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; | ||||||
5431 | return true; | ||||||
5432 | } | ||||||
5433 | |||||||
5434 | return false; | ||||||
5435 | } | ||||||
5436 | |||||||
5437 | /// Diagnose a declaration whose declarator-id has the given | ||||||
5438 | /// nested-name-specifier. | ||||||
5439 | /// | ||||||
5440 | /// \param SS The nested-name-specifier of the declarator-id. | ||||||
5441 | /// | ||||||
5442 | /// \param DC The declaration context to which the nested-name-specifier | ||||||
5443 | /// resolves. | ||||||
5444 | /// | ||||||
5445 | /// \param Name The name of the entity being declared. | ||||||
5446 | /// | ||||||
5447 | /// \param Loc The location of the name of the entity being declared. | ||||||
5448 | /// | ||||||
5449 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus | ||||||
5450 | /// we're declaring an explicit / partial specialization / instantiation. | ||||||
5451 | /// | ||||||
5452 | /// \returns true if we cannot safely recover from this error, false otherwise. | ||||||
5453 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | ||||||
5454 | DeclarationName Name, | ||||||
5455 | SourceLocation Loc, bool IsTemplateId) { | ||||||
5456 | DeclContext *Cur = CurContext; | ||||||
5457 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) | ||||||
5458 | Cur = Cur->getParent(); | ||||||
5459 | |||||||
5460 | // If the user provided a superfluous scope specifier that refers back to the | ||||||
5461 | // class in which the entity is already declared, diagnose and ignore it. | ||||||
5462 | // | ||||||
5463 | // class X { | ||||||
5464 | // void X::f(); | ||||||
5465 | // }; | ||||||
5466 | // | ||||||
5467 | // Note, it was once ill-formed to give redundant qualification in all | ||||||
5468 | // contexts, but that rule was removed by DR482. | ||||||
5469 | if (Cur->Equals(DC)) { | ||||||
5470 | if (Cur->isRecord()) { | ||||||
5471 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification | ||||||
5472 | : diag::err_member_extra_qualification) | ||||||
5473 | << Name << FixItHint::CreateRemoval(SS.getRange()); | ||||||
5474 | SS.clear(); | ||||||
5475 | } else { | ||||||
5476 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; | ||||||
5477 | } | ||||||
5478 | return false; | ||||||
5479 | } | ||||||
5480 | |||||||
5481 | // Check whether the qualifying scope encloses the scope of the original | ||||||
5482 | // declaration. For a template-id, we perform the checks in | ||||||
5483 | // CheckTemplateSpecializationScope. | ||||||
5484 | if (!Cur->Encloses(DC) && !IsTemplateId) { | ||||||
5485 | if (Cur->isRecord()) | ||||||
5486 | Diag(Loc, diag::err_member_qualification) | ||||||
5487 | << Name << SS.getRange(); | ||||||
5488 | else if (isa<TranslationUnitDecl>(DC)) | ||||||
5489 | Diag(Loc, diag::err_invalid_declarator_global_scope) | ||||||
5490 | << Name << SS.getRange(); | ||||||
5491 | else if (isa<FunctionDecl>(Cur)) | ||||||
5492 | Diag(Loc, diag::err_invalid_declarator_in_function) | ||||||
5493 | << Name << SS.getRange(); | ||||||
5494 | else if (isa<BlockDecl>(Cur)) | ||||||
5495 | Diag(Loc, diag::err_invalid_declarator_in_block) | ||||||
5496 | << Name << SS.getRange(); | ||||||
5497 | else | ||||||
5498 | Diag(Loc, diag::err_invalid_declarator_scope) | ||||||
5499 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); | ||||||
5500 | |||||||
5501 | return true; | ||||||
5502 | } | ||||||
5503 | |||||||
5504 | if (Cur->isRecord()) { | ||||||
5505 | // Cannot qualify members within a class. | ||||||
5506 | Diag(Loc, diag::err_member_qualification) | ||||||
5507 | << Name << SS.getRange(); | ||||||
5508 | SS.clear(); | ||||||
5509 | |||||||
5510 | // C++ constructors and destructors with incorrect scopes can break | ||||||
5511 | // our AST invariants by having the wrong underlying types. If | ||||||
5512 | // that's the case, then drop this declaration entirely. | ||||||
5513 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || | ||||||
5514 | Name.getNameKind() == DeclarationName::CXXDestructorName) && | ||||||
5515 | !Context.hasSameType(Name.getCXXNameType(), | ||||||
5516 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) | ||||||
5517 | return true; | ||||||
5518 | |||||||
5519 | return false; | ||||||
5520 | } | ||||||
5521 | |||||||
5522 | // C++11 [dcl.meaning]p1: | ||||||
5523 | // [...] "The nested-name-specifier of the qualified declarator-id shall | ||||||
5524 | // not begin with a decltype-specifer" | ||||||
5525 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); | ||||||
5526 | while (SpecLoc.getPrefix()) | ||||||
5527 | SpecLoc = SpecLoc.getPrefix(); | ||||||
5528 | if (dyn_cast_or_null<DecltypeType>( | ||||||
5529 | SpecLoc.getNestedNameSpecifier()->getAsType())) | ||||||
5530 | Diag(Loc, diag::err_decltype_in_declarator) | ||||||
5531 | << SpecLoc.getTypeLoc().getSourceRange(); | ||||||
5532 | |||||||
5533 | return false; | ||||||
5534 | } | ||||||
5535 | |||||||
5536 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, | ||||||
5537 | MultiTemplateParamsArg TemplateParamLists) { | ||||||
5538 | // TODO: consider using NameInfo for diagnostic. | ||||||
5539 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||||
5540 | DeclarationName Name = NameInfo.getName(); | ||||||
5541 | |||||||
5542 | // All of these full declarators require an identifier. If it doesn't have | ||||||
5543 | // one, the ParsedFreeStandingDeclSpec action should be used. | ||||||
5544 | if (D.isDecompositionDeclarator()) { | ||||||
5545 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); | ||||||
5546 | } else if (!Name) { | ||||||
5547 | if (!D.isInvalidType()) // Reject this if we think it is valid. | ||||||
5548 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) | ||||||
5549 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); | ||||||
5550 | return nullptr; | ||||||
5551 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) | ||||||
5552 | return nullptr; | ||||||
5553 | |||||||
5554 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||||
5555 | // we find one that is. | ||||||
5556 | while ((S->getFlags() & Scope::DeclScope) == 0 || | ||||||
5557 | (S->getFlags() & Scope::TemplateParamScope) != 0) | ||||||
5558 | S = S->getParent(); | ||||||
5559 | |||||||
5560 | DeclContext *DC = CurContext; | ||||||
5561 | if (D.getCXXScopeSpec().isInvalid()) | ||||||
5562 | D.setInvalidType(); | ||||||
5563 | else if (D.getCXXScopeSpec().isSet()) { | ||||||
5564 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), | ||||||
5565 | UPPC_DeclarationQualifier)) | ||||||
5566 | return nullptr; | ||||||
5567 | |||||||
5568 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); | ||||||
5569 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); | ||||||
5570 | if (!DC || isa<EnumDecl>(DC)) { | ||||||
5571 | // If we could not compute the declaration context, it's because the | ||||||
5572 | // declaration context is dependent but does not refer to a class, | ||||||
5573 | // class template, or class template partial specialization. Complain | ||||||
5574 | // and return early, to avoid the coming semantic disaster. | ||||||
5575 | Diag(D.getIdentifierLoc(), | ||||||
5576 | diag::err_template_qualified_declarator_no_match) | ||||||
5577 | << D.getCXXScopeSpec().getScopeRep() | ||||||
5578 | << D.getCXXScopeSpec().getRange(); | ||||||
5579 | return nullptr; | ||||||
5580 | } | ||||||
5581 | bool IsDependentContext = DC->isDependentContext(); | ||||||
5582 | |||||||
5583 | if (!IsDependentContext && | ||||||
5584 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) | ||||||
5585 | return nullptr; | ||||||
5586 | |||||||
5587 | // If a class is incomplete, do not parse entities inside it. | ||||||
5588 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { | ||||||
5589 | Diag(D.getIdentifierLoc(), | ||||||
5590 | diag::err_member_def_undefined_record) | ||||||
5591 | << Name << DC << D.getCXXScopeSpec().getRange(); | ||||||
5592 | return nullptr; | ||||||
5593 | } | ||||||
5594 | if (!D.getDeclSpec().isFriendSpecified()) { | ||||||
5595 | if (diagnoseQualifiedDeclaration( | ||||||
5596 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), | ||||||
5597 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { | ||||||
5598 | if (DC->isRecord()) | ||||||
5599 | return nullptr; | ||||||
5600 | |||||||
5601 | D.setInvalidType(); | ||||||
5602 | } | ||||||
5603 | } | ||||||
5604 | |||||||
5605 | // Check whether we need to rebuild the type of the given | ||||||
5606 | // declaration in the current instantiation. | ||||||
5607 | if (EnteringContext && IsDependentContext && | ||||||
5608 | TemplateParamLists.size() != 0) { | ||||||
5609 | ContextRAII SavedContext(*this, DC); | ||||||
5610 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) | ||||||
5611 | D.setInvalidType(); | ||||||
5612 | } | ||||||
5613 | } | ||||||
5614 | |||||||
5615 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
5616 | QualType R = TInfo->getType(); | ||||||
5617 | |||||||
5618 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||||
5619 | UPPC_DeclarationType)) | ||||||
5620 | D.setInvalidType(); | ||||||
5621 | |||||||
5622 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||||
5623 | forRedeclarationInCurContext()); | ||||||
5624 | |||||||
5625 | // See if this is a redefinition of a variable in the same scope. | ||||||
5626 | if (!D.getCXXScopeSpec().isSet()) { | ||||||
5627 | bool IsLinkageLookup = false; | ||||||
5628 | bool CreateBuiltins = false; | ||||||
5629 | |||||||
5630 | // If the declaration we're planning to build will be a function | ||||||
5631 | // or object with linkage, then look for another declaration with | ||||||
5632 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). | ||||||
5633 | // | ||||||
5634 | // If the declaration we're planning to build will be declared with | ||||||
5635 | // external linkage in the translation unit, create any builtin with | ||||||
5636 | // the same name. | ||||||
5637 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||||
5638 | /* Do nothing*/; | ||||||
5639 | else if (CurContext->isFunctionOrMethod() && | ||||||
5640 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || | ||||||
5641 | R->isFunctionType())) { | ||||||
5642 | IsLinkageLookup = true; | ||||||
5643 | CreateBuiltins = | ||||||
5644 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); | ||||||
5645 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && | ||||||
5646 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) | ||||||
5647 | CreateBuiltins = true; | ||||||
5648 | |||||||
5649 | if (IsLinkageLookup) { | ||||||
5650 | Previous.clear(LookupRedeclarationWithLinkage); | ||||||
5651 | Previous.setRedeclarationKind(ForExternalRedeclaration); | ||||||
5652 | } | ||||||
5653 | |||||||
5654 | LookupName(Previous, S, CreateBuiltins); | ||||||
5655 | } else { // Something like "int foo::x;" | ||||||
5656 | LookupQualifiedName(Previous, DC); | ||||||
5657 | |||||||
5658 | // C++ [dcl.meaning]p1: | ||||||
5659 | // When the declarator-id is qualified, the declaration shall refer to a | ||||||
5660 | // previously declared member of the class or namespace to which the | ||||||
5661 | // qualifier refers (or, in the case of a namespace, of an element of the | ||||||
5662 | // inline namespace set of that namespace (7.3.1)) or to a specialization | ||||||
5663 | // thereof; [...] | ||||||
5664 | // | ||||||
5665 | // Note that we already checked the context above, and that we do not have | ||||||
5666 | // enough information to make sure that Previous contains the declaration | ||||||
5667 | // we want to match. For example, given: | ||||||
5668 | // | ||||||
5669 | // class X { | ||||||
5670 | // void f(); | ||||||
5671 | // void f(float); | ||||||
5672 | // }; | ||||||
5673 | // | ||||||
5674 | // void X::f(int) { } // ill-formed | ||||||
5675 | // | ||||||
5676 | // In this case, Previous will point to the overload set | ||||||
5677 | // containing the two f's declared in X, but neither of them | ||||||
5678 | // matches. | ||||||
5679 | |||||||
5680 | // C++ [dcl.meaning]p1: | ||||||
5681 | // [...] the member shall not merely have been introduced by a | ||||||
5682 | // using-declaration in the scope of the class or namespace nominated by | ||||||
5683 | // the nested-name-specifier of the declarator-id. | ||||||
5684 | RemoveUsingDecls(Previous); | ||||||
5685 | } | ||||||
5686 | |||||||
5687 | if (Previous.isSingleResult() && | ||||||
5688 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||||
5689 | // Maybe we will complain about the shadowed template parameter. | ||||||
5690 | if (!D.isInvalidType()) | ||||||
5691 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | ||||||
5692 | Previous.getFoundDecl()); | ||||||
5693 | |||||||
5694 | // Just pretend that we didn't see the previous declaration. | ||||||
5695 | Previous.clear(); | ||||||
5696 | } | ||||||
5697 | |||||||
5698 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) | ||||||
5699 | // Forget that the previous declaration is the injected-class-name. | ||||||
5700 | Previous.clear(); | ||||||
5701 | |||||||
5702 | // In C++, the previous declaration we find might be a tag type | ||||||
5703 | // (class or enum). In this case, the new declaration will hide the | ||||||
5704 | // tag type. Note that this applies to functions, function templates, and | ||||||
5705 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. | ||||||
5706 | if (Previous.isSingleTagDecl() && | ||||||
5707 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | ||||||
5708 | (TemplateParamLists.size() == 0 || R->isFunctionType())) | ||||||
5709 | Previous.clear(); | ||||||
5710 | |||||||
5711 | // Check that there are no default arguments other than in the parameters | ||||||
5712 | // of a function declaration (C++ only). | ||||||
5713 | if (getLangOpts().CPlusPlus) | ||||||
5714 | CheckExtraCXXDefaultArguments(D); | ||||||
5715 | |||||||
5716 | NamedDecl *New; | ||||||
5717 | |||||||
5718 | bool AddToScope = true; | ||||||
5719 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { | ||||||
5720 | if (TemplateParamLists.size()) { | ||||||
5721 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); | ||||||
5722 | return nullptr; | ||||||
5723 | } | ||||||
5724 | |||||||
5725 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); | ||||||
5726 | } else if (R->isFunctionType()) { | ||||||
5727 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, | ||||||
5728 | TemplateParamLists, | ||||||
5729 | AddToScope); | ||||||
5730 | } else { | ||||||
5731 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, | ||||||
5732 | AddToScope); | ||||||
5733 | } | ||||||
5734 | |||||||
5735 | if (!New) | ||||||
5736 | return nullptr; | ||||||
5737 | |||||||
5738 | // If this has an identifier and is not a function template specialization, | ||||||
5739 | // add it to the scope stack. | ||||||
5740 | if (New->getDeclName() && AddToScope) | ||||||
5741 | PushOnScopeChains(New, S); | ||||||
5742 | |||||||
5743 | if (isInOpenMPDeclareTargetContext()) | ||||||
5744 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | ||||||
5745 | |||||||
5746 | return New; | ||||||
5747 | } | ||||||
5748 | |||||||
5749 | /// Helper method to turn variable array types into constant array | ||||||
5750 | /// types in certain situations which would otherwise be errors (for | ||||||
5751 | /// GCC compatibility). | ||||||
5752 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, | ||||||
5753 | ASTContext &Context, | ||||||
5754 | bool &SizeIsNegative, | ||||||
5755 | llvm::APSInt &Oversized) { | ||||||
5756 | // This method tries to turn a variable array into a constant | ||||||
5757 | // array even when the size isn't an ICE. This is necessary | ||||||
5758 | // for compatibility with code that depends on gcc's buggy | ||||||
5759 | // constant expression folding, like struct {char x[(int)(char*)2];} | ||||||
5760 | SizeIsNegative = false; | ||||||
5761 | Oversized = 0; | ||||||
5762 | |||||||
5763 | if (T->isDependentType()) | ||||||
5764 | return QualType(); | ||||||
5765 | |||||||
5766 | QualifierCollector Qs; | ||||||
5767 | const Type *Ty = Qs.strip(T); | ||||||
5768 | |||||||
5769 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { | ||||||
5770 | QualType Pointee = PTy->getPointeeType(); | ||||||
5771 | QualType FixedType = | ||||||
5772 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, | ||||||
5773 | Oversized); | ||||||
5774 | if (FixedType.isNull()) return FixedType; | ||||||
5775 | FixedType = Context.getPointerType(FixedType); | ||||||
5776 | return Qs.apply(Context, FixedType); | ||||||
5777 | } | ||||||
5778 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { | ||||||
5779 | QualType Inner = PTy->getInnerType(); | ||||||
5780 | QualType FixedType = | ||||||
5781 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, | ||||||
5782 | Oversized); | ||||||
5783 | if (FixedType.isNull()) return FixedType; | ||||||
5784 | FixedType = Context.getParenType(FixedType); | ||||||
5785 | return Qs.apply(Context, FixedType); | ||||||
5786 | } | ||||||
5787 | |||||||
5788 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); | ||||||
5789 | if (!VLATy) | ||||||
5790 | return QualType(); | ||||||
5791 | // FIXME: We should probably handle this case | ||||||
5792 | if (VLATy->getElementType()->isVariablyModifiedType()) | ||||||
5793 | return QualType(); | ||||||
5794 | |||||||
5795 | Expr::EvalResult Result; | ||||||
5796 | if (!VLATy->getSizeExpr() || | ||||||
5797 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) | ||||||
5798 | return QualType(); | ||||||
5799 | |||||||
5800 | llvm::APSInt Res = Result.Val.getInt(); | ||||||
5801 | |||||||
5802 | // Check whether the array size is negative. | ||||||
5803 | if (Res.isSigned() && Res.isNegative()) { | ||||||
5804 | SizeIsNegative = true; | ||||||
5805 | return QualType(); | ||||||
5806 | } | ||||||
5807 | |||||||
5808 | // Check whether the array is too large to be addressed. | ||||||
5809 | unsigned ActiveSizeBits | ||||||
5810 | = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), | ||||||
5811 | Res); | ||||||
5812 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | ||||||
5813 | Oversized = Res; | ||||||
5814 | return QualType(); | ||||||
5815 | } | ||||||
5816 | |||||||
5817 | return Context.getConstantArrayType( | ||||||
5818 | VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); | ||||||
5819 | } | ||||||
5820 | |||||||
5821 | static void | ||||||
5822 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { | ||||||
5823 | SrcTL = SrcTL.getUnqualifiedLoc(); | ||||||
5824 | DstTL = DstTL.getUnqualifiedLoc(); | ||||||
5825 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { | ||||||
5826 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); | ||||||
5827 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), | ||||||
5828 | DstPTL.getPointeeLoc()); | ||||||
5829 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); | ||||||
5830 | return; | ||||||
5831 | } | ||||||
5832 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { | ||||||
5833 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); | ||||||
5834 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), | ||||||
5835 | DstPTL.getInnerLoc()); | ||||||
5836 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); | ||||||
5837 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); | ||||||
5838 | return; | ||||||
5839 | } | ||||||
5840 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); | ||||||
5841 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); | ||||||
5842 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); | ||||||
5843 | TypeLoc DstElemTL = DstATL.getElementLoc(); | ||||||
5844 | DstElemTL.initializeFullCopy(SrcElemTL); | ||||||
5845 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); | ||||||
5846 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); | ||||||
5847 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); | ||||||
5848 | } | ||||||
5849 | |||||||
5850 | /// Helper method to turn variable array types into constant array | ||||||
5851 | /// types in certain situations which would otherwise be errors (for | ||||||
5852 | /// GCC compatibility). | ||||||
5853 | static TypeSourceInfo* | ||||||
5854 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, | ||||||
5855 | ASTContext &Context, | ||||||
5856 | bool &SizeIsNegative, | ||||||
5857 | llvm::APSInt &Oversized) { | ||||||
5858 | QualType FixedTy | ||||||
5859 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, | ||||||
5860 | SizeIsNegative, Oversized); | ||||||
5861 | if (FixedTy.isNull()) | ||||||
5862 | return nullptr; | ||||||
5863 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); | ||||||
5864 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), | ||||||
5865 | FixedTInfo->getTypeLoc()); | ||||||
5866 | return FixedTInfo; | ||||||
5867 | } | ||||||
5868 | |||||||
5869 | /// Register the given locally-scoped extern "C" declaration so | ||||||
5870 | /// that it can be found later for redeclarations. We include any extern "C" | ||||||
5871 | /// declaration that is not visible in the translation unit here, not just | ||||||
5872 | /// function-scope declarations. | ||||||
5873 | void | ||||||
5874 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { | ||||||
5875 | if (!getLangOpts().CPlusPlus && | ||||||
5876 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||||
5877 | // Don't need to track declarations in the TU in C. | ||||||
5878 | return; | ||||||
5879 | |||||||
5880 | // Note that we have a locally-scoped external with this name. | ||||||
5881 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); | ||||||
5882 | } | ||||||
5883 | |||||||
5884 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { | ||||||
5885 | // FIXME: We can have multiple results via __attribute__((overloadable)). | ||||||
5886 | auto Result = Context.getExternCContextDecl()->lookup(Name); | ||||||
5887 | return Result.empty() ? nullptr : *Result.begin(); | ||||||
5888 | } | ||||||
5889 | |||||||
5890 | /// Diagnose function specifiers on a declaration of an identifier that | ||||||
5891 | /// does not identify a function. | ||||||
5892 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { | ||||||
5893 | // FIXME: We should probably indicate the identifier in question to avoid | ||||||
5894 | // confusion for constructs like "virtual int a(), b;" | ||||||
5895 | if (DS.isVirtualSpecified()) | ||||||
5896 | Diag(DS.getVirtualSpecLoc(), | ||||||
5897 | diag::err_virtual_non_function); | ||||||
5898 | |||||||
5899 | if (DS.hasExplicitSpecifier()) | ||||||
5900 | Diag(DS.getExplicitSpecLoc(), | ||||||
5901 | diag::err_explicit_non_function); | ||||||
5902 | |||||||
5903 | if (DS.isNoreturnSpecified()) | ||||||
5904 | Diag(DS.getNoreturnSpecLoc(), | ||||||
5905 | diag::err_noreturn_non_function); | ||||||
5906 | } | ||||||
5907 | |||||||
5908 | NamedDecl* | ||||||
5909 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | ||||||
5910 | TypeSourceInfo *TInfo, LookupResult &Previous) { | ||||||
5911 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||||
5912 | if (D.getCXXScopeSpec().isSet()) { | ||||||
5913 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) | ||||||
5914 | << D.getCXXScopeSpec().getRange(); | ||||||
5915 | D.setInvalidType(); | ||||||
5916 | // Pretend we didn't see the scope specifier. | ||||||
5917 | DC = CurContext; | ||||||
5918 | Previous.clear(); | ||||||
5919 | } | ||||||
5920 | |||||||
5921 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
5922 | |||||||
5923 | if (D.getDeclSpec().isInlineSpecified()) | ||||||
5924 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
5925 | << getLangOpts().CPlusPlus17; | ||||||
5926 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||||
5927 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||||
5928 | << 1 << D.getDeclSpec().getConstexprSpecifier(); | ||||||
5929 | |||||||
5930 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { | ||||||
5931 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) | ||||||
5932 | Diag(D.getName().StartLocation, | ||||||
5933 | diag::err_deduction_guide_invalid_specifier) | ||||||
5934 | << "typedef"; | ||||||
5935 | else | ||||||
5936 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) | ||||||
5937 | << D.getName().getSourceRange(); | ||||||
5938 | return nullptr; | ||||||
5939 | } | ||||||
5940 | |||||||
5941 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); | ||||||
5942 | if (!NewTD) return nullptr; | ||||||
5943 | |||||||
5944 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||||
5945 | ProcessDeclAttributes(S, NewTD, D); | ||||||
5946 | |||||||
5947 | CheckTypedefForVariablyModifiedType(S, NewTD); | ||||||
5948 | |||||||
5949 | bool Redeclaration = D.isRedeclaration(); | ||||||
5950 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); | ||||||
5951 | D.setRedeclaration(Redeclaration); | ||||||
5952 | return ND; | ||||||
5953 | } | ||||||
5954 | |||||||
5955 | void | ||||||
5956 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { | ||||||
5957 | // C99 6.7.7p2: If a typedef name specifies a variably modified type | ||||||
5958 | // then it shall have block scope. | ||||||
5959 | // Note that variably modified types must be fixed before merging the decl so | ||||||
5960 | // that redeclarations will match. | ||||||
5961 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); | ||||||
5962 | QualType T = TInfo->getType(); | ||||||
5963 | if (T->isVariablyModifiedType()) { | ||||||
5964 | setFunctionHasBranchProtectedScope(); | ||||||
5965 | |||||||
5966 | if (S->getFnParent() == nullptr) { | ||||||
5967 | bool SizeIsNegative; | ||||||
5968 | llvm::APSInt Oversized; | ||||||
5969 | TypeSourceInfo *FixedTInfo = | ||||||
5970 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||||
5971 | SizeIsNegative, | ||||||
5972 | Oversized); | ||||||
5973 | if (FixedTInfo) { | ||||||
5974 | Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); | ||||||
5975 | NewTD->setTypeSourceInfo(FixedTInfo); | ||||||
5976 | } else { | ||||||
5977 | if (SizeIsNegative) | ||||||
5978 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); | ||||||
5979 | else if (T->isVariableArrayType()) | ||||||
5980 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); | ||||||
5981 | else if (Oversized.getBoolValue()) | ||||||
5982 | Diag(NewTD->getLocation(), diag::err_array_too_large) | ||||||
5983 | << Oversized.toString(10); | ||||||
5984 | else | ||||||
5985 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||||
5986 | NewTD->setInvalidDecl(); | ||||||
5987 | } | ||||||
5988 | } | ||||||
5989 | } | ||||||
5990 | } | ||||||
5991 | |||||||
5992 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which | ||||||
5993 | /// declares a typedef-name, either using the 'typedef' type specifier or via | ||||||
5994 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. | ||||||
5995 | NamedDecl* | ||||||
5996 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, | ||||||
5997 | LookupResult &Previous, bool &Redeclaration) { | ||||||
5998 | |||||||
5999 | // Find the shadowed declaration before filtering for scope. | ||||||
6000 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); | ||||||
6001 | |||||||
6002 | // Merge the decl with the existing one if appropriate. If the decl is | ||||||
6003 | // in an outer scope, it isn't the same thing. | ||||||
6004 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, | ||||||
6005 | /*AllowInlineNamespace*/false); | ||||||
6006 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); | ||||||
6007 | if (!Previous.empty()) { | ||||||
6008 | Redeclaration = true; | ||||||
6009 | MergeTypedefNameDecl(S, NewTD, Previous); | ||||||
6010 | } else { | ||||||
6011 | inferGslPointerAttribute(NewTD); | ||||||
6012 | } | ||||||
6013 | |||||||
6014 | if (ShadowedDecl && !Redeclaration) | ||||||
6015 | CheckShadow(NewTD, ShadowedDecl, Previous); | ||||||
6016 | |||||||
6017 | // If this is the C FILE type, notify the AST context. | ||||||
6018 | if (IdentifierInfo *II = NewTD->getIdentifier()) | ||||||
6019 | if (!NewTD->isInvalidDecl() && | ||||||
6020 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
6021 | if (II->isStr("FILE")) | ||||||
6022 | Context.setFILEDecl(NewTD); | ||||||
6023 | else if (II->isStr("jmp_buf")) | ||||||
6024 | Context.setjmp_bufDecl(NewTD); | ||||||
6025 | else if (II->isStr("sigjmp_buf")) | ||||||
6026 | Context.setsigjmp_bufDecl(NewTD); | ||||||
6027 | else if (II->isStr("ucontext_t")) | ||||||
6028 | Context.setucontext_tDecl(NewTD); | ||||||
6029 | } | ||||||
6030 | |||||||
6031 | return NewTD; | ||||||
6032 | } | ||||||
6033 | |||||||
6034 | /// Determines whether the given declaration is an out-of-scope | ||||||
6035 | /// previous declaration. | ||||||
6036 | /// | ||||||
6037 | /// This routine should be invoked when name lookup has found a | ||||||
6038 | /// previous declaration (PrevDecl) that is not in the scope where a | ||||||
6039 | /// new declaration by the same name is being introduced. If the new | ||||||
6040 | /// declaration occurs in a local scope, previous declarations with | ||||||
6041 | /// linkage may still be considered previous declarations (C99 | ||||||
6042 | /// 6.2.2p4-5, C++ [basic.link]p6). | ||||||
6043 | /// | ||||||
6044 | /// \param PrevDecl the previous declaration found by name | ||||||
6045 | /// lookup | ||||||
6046 | /// | ||||||
6047 | /// \param DC the context in which the new declaration is being | ||||||
6048 | /// declared. | ||||||
6049 | /// | ||||||
6050 | /// \returns true if PrevDecl is an out-of-scope previous declaration | ||||||
6051 | /// for a new delcaration with the same name. | ||||||
6052 | static bool | ||||||
6053 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, | ||||||
6054 | ASTContext &Context) { | ||||||
6055 | if (!PrevDecl) | ||||||
6056 | return false; | ||||||
6057 | |||||||
6058 | if (!PrevDecl->hasLinkage()) | ||||||
6059 | return false; | ||||||
6060 | |||||||
6061 | if (Context.getLangOpts().CPlusPlus) { | ||||||
6062 | // C++ [basic.link]p6: | ||||||
6063 | // If there is a visible declaration of an entity with linkage | ||||||
6064 | // having the same name and type, ignoring entities declared | ||||||
6065 | // outside the innermost enclosing namespace scope, the block | ||||||
6066 | // scope declaration declares that same entity and receives the | ||||||
6067 | // linkage of the previous declaration. | ||||||
6068 | DeclContext *OuterContext = DC->getRedeclContext(); | ||||||
6069 | if (!OuterContext->isFunctionOrMethod()) | ||||||
6070 | // This rule only applies to block-scope declarations. | ||||||
6071 | return false; | ||||||
6072 | |||||||
6073 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); | ||||||
6074 | if (PrevOuterContext->isRecord()) | ||||||
6075 | // We found a member function: ignore it. | ||||||
6076 | return false; | ||||||
6077 | |||||||
6078 | // Find the innermost enclosing namespace for the new and | ||||||
6079 | // previous declarations. | ||||||
6080 | OuterContext = OuterContext->getEnclosingNamespaceContext(); | ||||||
6081 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); | ||||||
6082 | |||||||
6083 | // The previous declaration is in a different namespace, so it | ||||||
6084 | // isn't the same function. | ||||||
6085 | if (!OuterContext->Equals(PrevOuterContext)) | ||||||
6086 | return false; | ||||||
6087 | } | ||||||
6088 | |||||||
6089 | return true; | ||||||
6090 | } | ||||||
6091 | |||||||
6092 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { | ||||||
6093 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | ||||||
6094 | if (!SS.isSet()) return; | ||||||
6095 | DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); | ||||||
6096 | } | ||||||
6097 | |||||||
6098 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { | ||||||
6099 | QualType type = decl->getType(); | ||||||
6100 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); | ||||||
6101 | if (lifetime == Qualifiers::OCL_Autoreleasing) { | ||||||
6102 | // Various kinds of declaration aren't allowed to be __autoreleasing. | ||||||
6103 | unsigned kind = -1U; | ||||||
6104 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||||
6105 | if (var->hasAttr<BlocksAttr>()) | ||||||
6106 | kind = 0; // __block | ||||||
6107 | else if (!var->hasLocalStorage()) | ||||||
6108 | kind = 1; // global | ||||||
6109 | } else if (isa<ObjCIvarDecl>(decl)) { | ||||||
6110 | kind = 3; // ivar | ||||||
6111 | } else if (isa<FieldDecl>(decl)) { | ||||||
6112 | kind = 2; // field | ||||||
6113 | } | ||||||
6114 | |||||||
6115 | if (kind != -1U) { | ||||||
6116 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) | ||||||
6117 | << kind; | ||||||
6118 | } | ||||||
6119 | } else if (lifetime == Qualifiers::OCL_None) { | ||||||
6120 | // Try to infer lifetime. | ||||||
6121 | if (!type->isObjCLifetimeType()) | ||||||
6122 | return false; | ||||||
6123 | |||||||
6124 | lifetime = type->getObjCARCImplicitLifetime(); | ||||||
6125 | type = Context.getLifetimeQualifiedType(type, lifetime); | ||||||
6126 | decl->setType(type); | ||||||
6127 | } | ||||||
6128 | |||||||
6129 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||||
6130 | // Thread-local variables cannot have lifetime. | ||||||
6131 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && | ||||||
6132 | var->getTLSKind()) { | ||||||
6133 | Diag(var->getLocation(), diag::err_arc_thread_ownership) | ||||||
6134 | << var->getType(); | ||||||
6135 | return true; | ||||||
6136 | } | ||||||
6137 | } | ||||||
6138 | |||||||
6139 | return false; | ||||||
6140 | } | ||||||
6141 | |||||||
6142 | void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { | ||||||
6143 | if (Decl->getType().hasAddressSpace()) | ||||||
6144 | return; | ||||||
6145 | if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { | ||||||
6146 | QualType Type = Var->getType(); | ||||||
6147 | if (Type->isSamplerT() || Type->isVoidType()) | ||||||
6148 | return; | ||||||
6149 | LangAS ImplAS = LangAS::opencl_private; | ||||||
6150 | if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && | ||||||
6151 | Var->hasGlobalStorage()) | ||||||
6152 | ImplAS = LangAS::opencl_global; | ||||||
6153 | // If the original type from a decayed type is an array type and that array | ||||||
6154 | // type has no address space yet, deduce it now. | ||||||
6155 | if (auto DT = dyn_cast<DecayedType>(Type)) { | ||||||
6156 | auto OrigTy = DT->getOriginalType(); | ||||||
6157 | if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { | ||||||
6158 | // Add the address space to the original array type and then propagate | ||||||
6159 | // that to the element type through `getAsArrayType`. | ||||||
6160 | OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); | ||||||
6161 | OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); | ||||||
6162 | // Re-generate the decayed type. | ||||||
6163 | Type = Context.getDecayedType(OrigTy); | ||||||
6164 | } | ||||||
6165 | } | ||||||
6166 | Type = Context.getAddrSpaceQualType(Type, ImplAS); | ||||||
6167 | // Apply any qualifiers (including address space) from the array type to | ||||||
6168 | // the element type. This implements C99 6.7.3p8: "If the specification of | ||||||
6169 | // an array type includes any type qualifiers, the element type is so | ||||||
6170 | // qualified, not the array type." | ||||||
6171 | if (Type->isArrayType()) | ||||||
6172 | Type = QualType(Context.getAsArrayType(Type), 0); | ||||||
6173 | Decl->setType(Type); | ||||||
6174 | } | ||||||
6175 | } | ||||||
6176 | |||||||
6177 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { | ||||||
6178 | // Ensure that an auto decl is deduced otherwise the checks below might cache | ||||||
6179 | // the wrong linkage. | ||||||
6180 | assert(S.ParsingInitForAutoVars.count(&ND) == 0)((S.ParsingInitForAutoVars.count(&ND) == 0) ? static_cast <void> (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6180, __PRETTY_FUNCTION__)); | ||||||
6181 | |||||||
6182 | // 'weak' only applies to declarations with external linkage. | ||||||
6183 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { | ||||||
6184 | if (!ND.isExternallyVisible()) { | ||||||
6185 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); | ||||||
6186 | ND.dropAttr<WeakAttr>(); | ||||||
6187 | } | ||||||
6188 | } | ||||||
6189 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { | ||||||
6190 | if (ND.isExternallyVisible()) { | ||||||
6191 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); | ||||||
6192 | ND.dropAttr<WeakRefAttr>(); | ||||||
6193 | ND.dropAttr<AliasAttr>(); | ||||||
6194 | } | ||||||
6195 | } | ||||||
6196 | |||||||
6197 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { | ||||||
6198 | if (VD->hasInit()) { | ||||||
6199 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { | ||||||
6200 | assert(VD->isThisDeclarationADefinition() &&((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6201, __PRETTY_FUNCTION__)) | ||||||
6201 | !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((VD->isThisDeclarationADefinition() && !VD->isExternallyVisible () && "Broken AliasAttr handled late!") ? static_cast <void> (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6201, __PRETTY_FUNCTION__)); | ||||||
6202 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; | ||||||
6203 | VD->dropAttr<AliasAttr>(); | ||||||
6204 | } | ||||||
6205 | } | ||||||
6206 | } | ||||||
6207 | |||||||
6208 | // 'selectany' only applies to externally visible variable declarations. | ||||||
6209 | // It does not apply to functions. | ||||||
6210 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { | ||||||
6211 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { | ||||||
6212 | S.Diag(Attr->getLocation(), | ||||||
6213 | diag::err_attribute_selectany_non_extern_data); | ||||||
6214 | ND.dropAttr<SelectAnyAttr>(); | ||||||
6215 | } | ||||||
6216 | } | ||||||
6217 | |||||||
6218 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { | ||||||
6219 | auto *VD = dyn_cast<VarDecl>(&ND); | ||||||
6220 | bool IsAnonymousNS = false; | ||||||
6221 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||||
6222 | if (VD) { | ||||||
6223 | const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); | ||||||
6224 | while (NS && !IsAnonymousNS) { | ||||||
6225 | IsAnonymousNS = NS->isAnonymousNamespace(); | ||||||
6226 | NS = dyn_cast<NamespaceDecl>(NS->getParent()); | ||||||
6227 | } | ||||||
6228 | } | ||||||
6229 | // dll attributes require external linkage. Static locals may have external | ||||||
6230 | // linkage but still cannot be explicitly imported or exported. | ||||||
6231 | // In Microsoft mode, a variable defined in anonymous namespace must have | ||||||
6232 | // external linkage in order to be exported. | ||||||
6233 | bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; | ||||||
6234 | if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || | ||||||
6235 | (!AnonNSInMicrosoftMode && | ||||||
6236 | (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { | ||||||
6237 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) | ||||||
6238 | << &ND << Attr; | ||||||
6239 | ND.setInvalidDecl(); | ||||||
6240 | } | ||||||
6241 | } | ||||||
6242 | |||||||
6243 | // Virtual functions cannot be marked as 'notail'. | ||||||
6244 | if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) | ||||||
6245 | if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) | ||||||
6246 | if (MD->isVirtual()) { | ||||||
6247 | S.Diag(ND.getLocation(), | ||||||
6248 | diag::err_invalid_attribute_on_virtual_function) | ||||||
6249 | << Attr; | ||||||
6250 | ND.dropAttr<NotTailCalledAttr>(); | ||||||
6251 | } | ||||||
6252 | |||||||
6253 | // Check the attributes on the function type, if any. | ||||||
6254 | if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { | ||||||
6255 | // Don't declare this variable in the second operand of the for-statement; | ||||||
6256 | // GCC miscompiles that by ending its lifetime before evaluating the | ||||||
6257 | // third operand. See gcc.gnu.org/PR86769. | ||||||
6258 | AttributedTypeLoc ATL; | ||||||
6259 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); | ||||||
6260 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | ||||||
6261 | TL = ATL.getModifiedLoc()) { | ||||||
6262 | // The [[lifetimebound]] attribute can be applied to the implicit object | ||||||
6263 | // parameter of a non-static member function (other than a ctor or dtor) | ||||||
6264 | // by applying it to the function type. | ||||||
6265 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { | ||||||
6266 | const auto *MD = dyn_cast<CXXMethodDecl>(FD); | ||||||
6267 | if (!MD || MD->isStatic()) { | ||||||
6268 | S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) | ||||||
6269 | << !MD << A->getRange(); | ||||||
6270 | } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { | ||||||
6271 | S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) | ||||||
6272 | << isa<CXXDestructorDecl>(MD) << A->getRange(); | ||||||
6273 | } | ||||||
6274 | } | ||||||
6275 | } | ||||||
6276 | } | ||||||
6277 | } | ||||||
6278 | |||||||
6279 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, | ||||||
6280 | NamedDecl *NewDecl, | ||||||
6281 | bool IsSpecialization, | ||||||
6282 | bool IsDefinition) { | ||||||
6283 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) | ||||||
6284 | return; | ||||||
6285 | |||||||
6286 | bool IsTemplate = false; | ||||||
6287 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { | ||||||
6288 | OldDecl = OldTD->getTemplatedDecl(); | ||||||
6289 | IsTemplate = true; | ||||||
6290 | if (!IsSpecialization) | ||||||
6291 | IsDefinition = false; | ||||||
6292 | } | ||||||
6293 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { | ||||||
6294 | NewDecl = NewTD->getTemplatedDecl(); | ||||||
6295 | IsTemplate = true; | ||||||
6296 | } | ||||||
6297 | |||||||
6298 | if (!OldDecl || !NewDecl) | ||||||
6299 | return; | ||||||
6300 | |||||||
6301 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); | ||||||
6302 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); | ||||||
6303 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); | ||||||
6304 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); | ||||||
6305 | |||||||
6306 | // dllimport and dllexport are inheritable attributes so we have to exclude | ||||||
6307 | // inherited attribute instances. | ||||||
6308 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || | ||||||
6309 | (NewExportAttr && !NewExportAttr->isInherited()); | ||||||
6310 | |||||||
6311 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, | ||||||
6312 | // the only exception being explicit specializations. | ||||||
6313 | // Implicitly generated declarations are also excluded for now because there | ||||||
6314 | // is no other way to switch these to use dllimport or dllexport. | ||||||
6315 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; | ||||||
6316 | |||||||
6317 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { | ||||||
6318 | // Allow with a warning for free functions and global variables. | ||||||
6319 | bool JustWarn = false; | ||||||
6320 | if (!OldDecl->isCXXClassMember()) { | ||||||
6321 | auto *VD = dyn_cast<VarDecl>(OldDecl); | ||||||
6322 | if (VD && !VD->getDescribedVarTemplate()) | ||||||
6323 | JustWarn = true; | ||||||
6324 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); | ||||||
6325 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) | ||||||
6326 | JustWarn = true; | ||||||
6327 | } | ||||||
6328 | |||||||
6329 | // We cannot change a declaration that's been used because IR has already | ||||||
6330 | // been emitted. Dllimported functions will still work though (modulo | ||||||
6331 | // address equality) as they can use the thunk. | ||||||
6332 | if (OldDecl->isUsed()) | ||||||
6333 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) | ||||||
6334 | JustWarn = false; | ||||||
6335 | |||||||
6336 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration | ||||||
6337 | : diag::err_attribute_dll_redeclaration; | ||||||
6338 | S.Diag(NewDecl->getLocation(), DiagID) | ||||||
6339 | << NewDecl | ||||||
6340 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); | ||||||
6341 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6342 | if (!JustWarn) { | ||||||
6343 | NewDecl->setInvalidDecl(); | ||||||
6344 | return; | ||||||
6345 | } | ||||||
6346 | } | ||||||
6347 | |||||||
6348 | // A redeclaration is not allowed to drop a dllimport attribute, the only | ||||||
6349 | // exceptions being inline function definitions (except for function | ||||||
6350 | // templates), local extern declarations, qualified friend declarations or | ||||||
6351 | // special MSVC extension: in the last case, the declaration is treated as if | ||||||
6352 | // it were marked dllexport. | ||||||
6353 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; | ||||||
6354 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||||
6355 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { | ||||||
6356 | // Ignore static data because out-of-line definitions are diagnosed | ||||||
6357 | // separately. | ||||||
6358 | IsStaticDataMember = VD->isStaticDataMember(); | ||||||
6359 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != | ||||||
6360 | VarDecl::DeclarationOnly; | ||||||
6361 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { | ||||||
6362 | IsInline = FD->isInlined(); | ||||||
6363 | IsQualifiedFriend = FD->getQualifier() && | ||||||
6364 | FD->getFriendObjectKind() == Decl::FOK_Declared; | ||||||
6365 | } | ||||||
6366 | |||||||
6367 | if (OldImportAttr && !HasNewAttr && | ||||||
6368 | (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && | ||||||
6369 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { | ||||||
6370 | if (IsMicrosoft && IsDefinition) { | ||||||
6371 | S.Diag(NewDecl->getLocation(), | ||||||
6372 | diag::warn_redeclaration_without_import_attribute) | ||||||
6373 | << NewDecl; | ||||||
6374 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6375 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6376 | NewDecl->addAttr( | ||||||
6377 | DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); | ||||||
6378 | } else { | ||||||
6379 | S.Diag(NewDecl->getLocation(), | ||||||
6380 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) | ||||||
6381 | << NewDecl << OldImportAttr; | ||||||
6382 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6383 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); | ||||||
6384 | OldDecl->dropAttr<DLLImportAttr>(); | ||||||
6385 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6386 | } | ||||||
6387 | } else if (IsInline && OldImportAttr && !IsMicrosoft) { | ||||||
6388 | // In MinGW, seeing a function declared inline drops the dllimport | ||||||
6389 | // attribute. | ||||||
6390 | OldDecl->dropAttr<DLLImportAttr>(); | ||||||
6391 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6392 | S.Diag(NewDecl->getLocation(), | ||||||
6393 | diag::warn_dllimport_dropped_from_inline_function) | ||||||
6394 | << NewDecl << OldImportAttr; | ||||||
6395 | } | ||||||
6396 | |||||||
6397 | // A specialization of a class template member function is processed here | ||||||
6398 | // since it's a redeclaration. If the parent class is dllexport, the | ||||||
6399 | // specialization inherits that attribute. This doesn't happen automatically | ||||||
6400 | // since the parent class isn't instantiated until later. | ||||||
6401 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { | ||||||
6402 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && | ||||||
6403 | !NewImportAttr && !NewExportAttr) { | ||||||
6404 | if (const DLLExportAttr *ParentExportAttr = | ||||||
6405 | MD->getParent()->getAttr<DLLExportAttr>()) { | ||||||
6406 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); | ||||||
6407 | NewAttr->setInherited(true); | ||||||
6408 | NewDecl->addAttr(NewAttr); | ||||||
6409 | } | ||||||
6410 | } | ||||||
6411 | } | ||||||
6412 | } | ||||||
6413 | |||||||
6414 | /// Given that we are within the definition of the given function, | ||||||
6415 | /// will that definition behave like C99's 'inline', where the | ||||||
6416 | /// definition is discarded except for optimization purposes? | ||||||
6417 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { | ||||||
6418 | // Try to avoid calling GetGVALinkageForFunction. | ||||||
6419 | |||||||
6420 | // All cases of this require the 'inline' keyword. | ||||||
6421 | if (!FD->isInlined()) return false; | ||||||
6422 | |||||||
6423 | // This is only possible in C++ with the gnu_inline attribute. | ||||||
6424 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) | ||||||
6425 | return false; | ||||||
6426 | |||||||
6427 | // Okay, go ahead and call the relatively-more-expensive function. | ||||||
6428 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; | ||||||
6429 | } | ||||||
6430 | |||||||
6431 | /// Determine whether a variable is extern "C" prior to attaching | ||||||
6432 | /// an initializer. We can't just call isExternC() here, because that | ||||||
6433 | /// will also compute and cache whether the declaration is externally | ||||||
6434 | /// visible, which might change when we attach the initializer. | ||||||
6435 | /// | ||||||
6436 | /// This can only be used if the declaration is known to not be a | ||||||
6437 | /// redeclaration of an internal linkage declaration. | ||||||
6438 | /// | ||||||
6439 | /// For instance: | ||||||
6440 | /// | ||||||
6441 | /// auto x = []{}; | ||||||
6442 | /// | ||||||
6443 | /// Attaching the initializer here makes this declaration not externally | ||||||
6444 | /// visible, because its type has internal linkage. | ||||||
6445 | /// | ||||||
6446 | /// FIXME: This is a hack. | ||||||
6447 | template<typename T> | ||||||
6448 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { | ||||||
6449 | if (S.getLangOpts().CPlusPlus) { | ||||||
6450 | // In C++, the overloadable attribute negates the effects of extern "C". | ||||||
6451 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) | ||||||
6452 | return false; | ||||||
6453 | |||||||
6454 | // So do CUDA's host/device attributes. | ||||||
6455 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || | ||||||
6456 | D->template hasAttr<CUDAHostAttr>())) | ||||||
6457 | return false; | ||||||
6458 | } | ||||||
6459 | return D->isExternC(); | ||||||
6460 | } | ||||||
6461 | |||||||
6462 | static bool shouldConsiderLinkage(const VarDecl *VD) { | ||||||
6463 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); | ||||||
6464 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || | ||||||
6465 | isa<OMPDeclareMapperDecl>(DC)) | ||||||
6466 | return VD->hasExternalStorage(); | ||||||
6467 | if (DC->isFileContext()) | ||||||
6468 | return true; | ||||||
6469 | if (DC->isRecord()) | ||||||
6470 | return false; | ||||||
6471 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6471); | ||||||
6472 | } | ||||||
6473 | |||||||
6474 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { | ||||||
6475 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); | ||||||
6476 | if (DC->isFileContext() || DC->isFunctionOrMethod() || | ||||||
6477 | isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) | ||||||
6478 | return true; | ||||||
6479 | if (DC->isRecord()) | ||||||
6480 | return false; | ||||||
6481 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6481); | ||||||
6482 | } | ||||||
6483 | |||||||
6484 | static bool hasParsedAttr(Scope *S, const Declarator &PD, | ||||||
6485 | ParsedAttr::Kind Kind) { | ||||||
6486 | // Check decl attributes on the DeclSpec. | ||||||
6487 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) | ||||||
6488 | return true; | ||||||
6489 | |||||||
6490 | // Walk the declarator structure, checking decl attributes that were in a type | ||||||
6491 | // position to the decl itself. | ||||||
6492 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { | ||||||
6493 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) | ||||||
6494 | return true; | ||||||
6495 | } | ||||||
6496 | |||||||
6497 | // Finally, check attributes on the decl itself. | ||||||
6498 | return PD.getAttributes().hasAttribute(Kind); | ||||||
6499 | } | ||||||
6500 | |||||||
6501 | /// Adjust the \c DeclContext for a function or variable that might be a | ||||||
6502 | /// function-local external declaration. | ||||||
6503 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { | ||||||
6504 | if (!DC->isFunctionOrMethod()) | ||||||
6505 | return false; | ||||||
6506 | |||||||
6507 | // If this is a local extern function or variable declared within a function | ||||||
6508 | // template, don't add it into the enclosing namespace scope until it is | ||||||
6509 | // instantiated; it might have a dependent type right now. | ||||||
6510 | if (DC->isDependentContext()) | ||||||
6511 | return true; | ||||||
6512 | |||||||
6513 | // C++11 [basic.link]p7: | ||||||
6514 | // When a block scope declaration of an entity with linkage is not found to | ||||||
6515 | // refer to some other declaration, then that entity is a member of the | ||||||
6516 | // innermost enclosing namespace. | ||||||
6517 | // | ||||||
6518 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a | ||||||
6519 | // semantically-enclosing namespace, not a lexically-enclosing one. | ||||||
6520 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) | ||||||
6521 | DC = DC->getParent(); | ||||||
6522 | return true; | ||||||
6523 | } | ||||||
6524 | |||||||
6525 | /// Returns true if given declaration has external C language linkage. | ||||||
6526 | static bool isDeclExternC(const Decl *D) { | ||||||
6527 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) | ||||||
6528 | return FD->isExternC(); | ||||||
6529 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||||
6530 | return VD->isExternC(); | ||||||
6531 | |||||||
6532 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6532); | ||||||
6533 | } | ||||||
6534 | /// Returns true if there hasn't been any invalid type diagnosed. | ||||||
6535 | static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, | ||||||
6536 | DeclContext *DC, QualType R) { | ||||||
6537 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. | ||||||
6538 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function | ||||||
6539 | // argument. | ||||||
6540 | if (R->isImageType() || R->isPipeType()) { | ||||||
6541 | Se.Diag(D.getIdentifierLoc(), | ||||||
6542 | diag::err_opencl_type_can_only_be_used_as_function_parameter) | ||||||
6543 | << R; | ||||||
6544 | D.setInvalidType(); | ||||||
6545 | return false; | ||||||
6546 | } | ||||||
6547 | |||||||
6548 | // OpenCL v1.2 s6.9.r: | ||||||
6549 | // The event type cannot be used to declare a program scope variable. | ||||||
6550 | // OpenCL v2.0 s6.9.q: | ||||||
6551 | // The clk_event_t and reserve_id_t types cannot be declared in program | ||||||
6552 | // scope. | ||||||
6553 | if (NULL__null == S->getParent()) { | ||||||
6554 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { | ||||||
6555 | Se.Diag(D.getIdentifierLoc(), | ||||||
6556 | diag::err_invalid_type_for_program_scope_var) | ||||||
6557 | << R; | ||||||
6558 | D.setInvalidType(); | ||||||
6559 | return false; | ||||||
6560 | } | ||||||
6561 | } | ||||||
6562 | |||||||
6563 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. | ||||||
6564 | QualType NR = R; | ||||||
6565 | while (NR->isPointerType()) { | ||||||
6566 | if (NR->isFunctionPointerType()) { | ||||||
6567 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); | ||||||
6568 | D.setInvalidType(); | ||||||
6569 | return false; | ||||||
6570 | } | ||||||
6571 | NR = NR->getPointeeType(); | ||||||
6572 | } | ||||||
6573 | |||||||
6574 | if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | ||||||
6575 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and | ||||||
6576 | // half array type (unless the cl_khr_fp16 extension is enabled). | ||||||
6577 | if (Se.Context.getBaseElementType(R)->isHalfType()) { | ||||||
6578 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; | ||||||
6579 | D.setInvalidType(); | ||||||
6580 | return false; | ||||||
6581 | } | ||||||
6582 | } | ||||||
6583 | |||||||
6584 | // OpenCL v1.2 s6.9.r: | ||||||
6585 | // The event type cannot be used with the __local, __constant and __global | ||||||
6586 | // address space qualifiers. | ||||||
6587 | if (R->isEventT()) { | ||||||
6588 | if (R.getAddressSpace() != LangAS::opencl_private) { | ||||||
6589 | Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); | ||||||
6590 | D.setInvalidType(); | ||||||
6591 | return false; | ||||||
6592 | } | ||||||
6593 | } | ||||||
6594 | |||||||
6595 | // C++ for OpenCL does not allow the thread_local storage qualifier. | ||||||
6596 | // OpenCL C does not support thread_local either, and | ||||||
6597 | // also reject all other thread storage class specifiers. | ||||||
6598 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); | ||||||
6599 | if (TSC != TSCS_unspecified) { | ||||||
6600 | bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; | ||||||
6601 | Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
6602 | diag::err_opencl_unknown_type_specifier) | ||||||
6603 | << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() | ||||||
6604 | << DeclSpec::getSpecifierName(TSC) << 1; | ||||||
6605 | D.setInvalidType(); | ||||||
6606 | return false; | ||||||
6607 | } | ||||||
6608 | |||||||
6609 | if (R->isSamplerT()) { | ||||||
6610 | // OpenCL v1.2 s6.9.b p4: | ||||||
6611 | // The sampler type cannot be used with the __local and __global address | ||||||
6612 | // space qualifiers. | ||||||
6613 | if (R.getAddressSpace() == LangAS::opencl_local || | ||||||
6614 | R.getAddressSpace() == LangAS::opencl_global) { | ||||||
6615 | Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); | ||||||
6616 | D.setInvalidType(); | ||||||
6617 | } | ||||||
6618 | |||||||
6619 | // OpenCL v1.2 s6.12.14.1: | ||||||
6620 | // A global sampler must be declared with either the constant address | ||||||
6621 | // space qualifier or with the const qualifier. | ||||||
6622 | if (DC->isTranslationUnit() && | ||||||
6623 | !(R.getAddressSpace() == LangAS::opencl_constant || | ||||||
6624 | R.isConstQualified())) { | ||||||
6625 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); | ||||||
6626 | D.setInvalidType(); | ||||||
6627 | } | ||||||
6628 | if (D.isInvalidType()) | ||||||
6629 | return false; | ||||||
6630 | } | ||||||
6631 | return true; | ||||||
6632 | } | ||||||
6633 | |||||||
6634 | NamedDecl *Sema::ActOnVariableDeclarator( | ||||||
6635 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, | ||||||
6636 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, | ||||||
6637 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { | ||||||
6638 | QualType R = TInfo->getType(); | ||||||
6639 | DeclarationName Name = GetNameForDeclarator(D).getName(); | ||||||
6640 | |||||||
6641 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||
6642 | |||||||
6643 | if (D.isDecompositionDeclarator()) { | ||||||
6644 | // Take the name of the first declarator as our name for diagnostic | ||||||
6645 | // purposes. | ||||||
6646 | auto &Decomp = D.getDecompositionDeclarator(); | ||||||
6647 | if (!Decomp.bindings().empty()) { | ||||||
6648 | II = Decomp.bindings()[0].Name; | ||||||
6649 | Name = II; | ||||||
6650 | } | ||||||
6651 | } else if (!II) { | ||||||
6652 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; | ||||||
6653 | return nullptr; | ||||||
6654 | } | ||||||
6655 | |||||||
6656 | |||||||
6657 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); | ||||||
6658 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); | ||||||
6659 | |||||||
6660 | // dllimport globals without explicit storage class are treated as extern. We | ||||||
6661 | // have to change the storage class this early to get the right DeclContext. | ||||||
6662 | if (SC == SC_None && !DC->isRecord() && | ||||||
6663 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && | ||||||
6664 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) | ||||||
6665 | SC = SC_Extern; | ||||||
6666 | |||||||
6667 | DeclContext *OriginalDC = DC; | ||||||
6668 | bool IsLocalExternDecl = SC == SC_Extern && | ||||||
6669 | adjustContextForLocalExternDecl(DC); | ||||||
6670 | |||||||
6671 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||||
6672 | // mutable can only appear on non-static class members, so it's always | ||||||
6673 | // an error here | ||||||
6674 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); | ||||||
6675 | D.setInvalidType(); | ||||||
6676 | SC = SC_None; | ||||||
6677 | } | ||||||
6678 | |||||||
6679 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && | ||||||
6680 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( | ||||||
6681 | D.getDeclSpec().getStorageClassSpecLoc())) { | ||||||
6682 | // In C++11, the 'register' storage class specifier is deprecated. | ||||||
6683 | // Suppress the warning in system macros, it's used in macros in some | ||||||
6684 | // popular C system headers, such as in glibc's htonl() macro. | ||||||
6685 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6686 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||||
6687 | : diag::warn_deprecated_register) | ||||||
6688 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6689 | } | ||||||
6690 | |||||||
6691 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
6692 | |||||||
6693 | if (!DC->isRecord() && S->getFnParent() == nullptr) { | ||||||
6694 | // C99 6.9p2: The storage-class specifiers auto and register shall not | ||||||
6695 | // appear in the declaration specifiers in an external declaration. | ||||||
6696 | // Global Register+Asm is a GNU extension we support. | ||||||
6697 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { | ||||||
6698 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); | ||||||
6699 | D.setInvalidType(); | ||||||
6700 | } | ||||||
6701 | } | ||||||
6702 | |||||||
6703 | bool IsMemberSpecialization = false; | ||||||
6704 | bool IsVariableTemplateSpecialization = false; | ||||||
6705 | bool IsPartialSpecialization = false; | ||||||
6706 | bool IsVariableTemplate = false; | ||||||
6707 | VarDecl *NewVD = nullptr; | ||||||
6708 | VarTemplateDecl *NewTemplate = nullptr; | ||||||
6709 | TemplateParameterList *TemplateParams = nullptr; | ||||||
6710 | if (!getLangOpts().CPlusPlus) { | ||||||
6711 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), | ||||||
6712 | II, R, TInfo, SC); | ||||||
6713 | |||||||
6714 | if (R->getContainedDeducedType()) | ||||||
6715 | ParsingInitForAutoVars.insert(NewVD); | ||||||
6716 | |||||||
6717 | if (D.isInvalidType()) | ||||||
6718 | NewVD->setInvalidDecl(); | ||||||
6719 | |||||||
6720 | if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && | ||||||
6721 | NewVD->hasLocalStorage()) | ||||||
6722 | checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), | ||||||
6723 | NTCUC_AutoVar, NTCUK_Destruct); | ||||||
6724 | } else { | ||||||
6725 | bool Invalid = false; | ||||||
6726 | |||||||
6727 | if (DC->isRecord() && !CurContext->isRecord()) { | ||||||
6728 | // This is an out-of-line definition of a static data member. | ||||||
6729 | switch (SC) { | ||||||
6730 | case SC_None: | ||||||
6731 | break; | ||||||
6732 | case SC_Static: | ||||||
6733 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6734 | diag::err_static_out_of_line) | ||||||
6735 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6736 | break; | ||||||
6737 | case SC_Auto: | ||||||
6738 | case SC_Register: | ||||||
6739 | case SC_Extern: | ||||||
6740 | // [dcl.stc] p2: The auto or register specifiers shall be applied only | ||||||
6741 | // to names of variables declared in a block or to function parameters. | ||||||
6742 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration | ||||||
6743 | // of class members | ||||||
6744 | |||||||
6745 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6746 | diag::err_storage_class_for_static_member) | ||||||
6747 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6748 | break; | ||||||
6749 | case SC_PrivateExtern: | ||||||
6750 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6750); | ||||||
6751 | } | ||||||
6752 | } | ||||||
6753 | |||||||
6754 | if (SC == SC_Static && CurContext->isRecord()) { | ||||||
6755 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { | ||||||
6756 | if (RD->isLocalClass()) | ||||||
6757 | Diag(D.getIdentifierLoc(), | ||||||
6758 | diag::err_static_data_member_not_allowed_in_local_class) | ||||||
6759 | << Name << RD->getDeclName(); | ||||||
6760 | |||||||
6761 | // C++98 [class.union]p1: If a union contains a static data member, | ||||||
6762 | // the program is ill-formed. C++11 drops this restriction. | ||||||
6763 | if (RD->isUnion()) | ||||||
6764 | Diag(D.getIdentifierLoc(), | ||||||
6765 | getLangOpts().CPlusPlus11 | ||||||
6766 | ? diag::warn_cxx98_compat_static_data_member_in_union | ||||||
6767 | : diag::ext_static_data_member_in_union) << Name; | ||||||
6768 | // We conservatively disallow static data members in anonymous structs. | ||||||
6769 | else if (!RD->getDeclName()) | ||||||
6770 | Diag(D.getIdentifierLoc(), | ||||||
6771 | diag::err_static_data_member_not_allowed_in_anon_struct) | ||||||
6772 | << Name << RD->isUnion(); | ||||||
6773 | } | ||||||
6774 | } | ||||||
6775 | |||||||
6776 | // Match up the template parameter lists with the scope specifier, then | ||||||
6777 | // determine whether we have a template or a template specialization. | ||||||
6778 | TemplateParams = MatchTemplateParametersToScopeSpecifier( | ||||||
6779 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||||
6780 | D.getCXXScopeSpec(), | ||||||
6781 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||||
6782 | ? D.getName().TemplateId | ||||||
6783 | : nullptr, | ||||||
6784 | TemplateParamLists, | ||||||
6785 | /*never a friend*/ false, IsMemberSpecialization, Invalid); | ||||||
6786 | |||||||
6787 | if (TemplateParams) { | ||||||
6788 | if (!TemplateParams->size() && | ||||||
6789 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||||
6790 | // There is an extraneous 'template<>' for this variable. Complain | ||||||
6791 | // about it, but allow the declaration of the variable. | ||||||
6792 | Diag(TemplateParams->getTemplateLoc(), | ||||||
6793 | diag::err_template_variable_noparams) | ||||||
6794 | << II | ||||||
6795 | << SourceRange(TemplateParams->getTemplateLoc(), | ||||||
6796 | TemplateParams->getRAngleLoc()); | ||||||
6797 | TemplateParams = nullptr; | ||||||
6798 | } else { | ||||||
6799 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||
6800 | // This is an explicit specialization or a partial specialization. | ||||||
6801 | // FIXME: Check that we can declare a specialization here. | ||||||
6802 | IsVariableTemplateSpecialization = true; | ||||||
6803 | IsPartialSpecialization = TemplateParams->size() > 0; | ||||||
6804 | } else { // if (TemplateParams->size() > 0) | ||||||
6805 | // This is a template declaration. | ||||||
6806 | IsVariableTemplate = true; | ||||||
6807 | |||||||
6808 | // Check that we can declare a template here. | ||||||
6809 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||||
6810 | return nullptr; | ||||||
6811 | |||||||
6812 | // Only C++1y supports variable templates (N3651). | ||||||
6813 | Diag(D.getIdentifierLoc(), | ||||||
6814 | getLangOpts().CPlusPlus14 | ||||||
6815 | ? diag::warn_cxx11_compat_variable_template | ||||||
6816 | : diag::ext_variable_template); | ||||||
6817 | } | ||||||
6818 | } | ||||||
6819 | } else { | ||||||
6820 | assert((Invalid ||(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6822, __PRETTY_FUNCTION__)) | ||||||
6821 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6822, __PRETTY_FUNCTION__)) | ||||||
6822 | "should have a 'template<>' for this decl")(((Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId ) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 6822, __PRETTY_FUNCTION__)); | ||||||
6823 | } | ||||||
6824 | |||||||
6825 | if (IsVariableTemplateSpecialization) { | ||||||
6826 | SourceLocation TemplateKWLoc = | ||||||
6827 | TemplateParamLists.size() > 0 | ||||||
6828 | ? TemplateParamLists[0]->getTemplateLoc() | ||||||
6829 | : SourceLocation(); | ||||||
6830 | DeclResult Res = ActOnVarTemplateSpecialization( | ||||||
6831 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, | ||||||
6832 | IsPartialSpecialization); | ||||||
6833 | if (Res.isInvalid()) | ||||||
6834 | return nullptr; | ||||||
6835 | NewVD = cast<VarDecl>(Res.get()); | ||||||
6836 | AddToScope = false; | ||||||
6837 | } else if (D.isDecompositionDeclarator()) { | ||||||
6838 | NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), | ||||||
6839 | D.getIdentifierLoc(), R, TInfo, SC, | ||||||
6840 | Bindings); | ||||||
6841 | } else | ||||||
6842 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), | ||||||
6843 | D.getIdentifierLoc(), II, R, TInfo, SC); | ||||||
6844 | |||||||
6845 | // If this is supposed to be a variable template, create it as such. | ||||||
6846 | if (IsVariableTemplate) { | ||||||
6847 | NewTemplate = | ||||||
6848 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, | ||||||
6849 | TemplateParams, NewVD); | ||||||
6850 | NewVD->setDescribedVarTemplate(NewTemplate); | ||||||
6851 | } | ||||||
6852 | |||||||
6853 | // If this decl has an auto type in need of deduction, make a note of the | ||||||
6854 | // Decl so we can diagnose uses of it in its own initializer. | ||||||
6855 | if (R->getContainedDeducedType()) | ||||||
6856 | ParsingInitForAutoVars.insert(NewVD); | ||||||
6857 | |||||||
6858 | if (D.isInvalidType() || Invalid) { | ||||||
6859 | NewVD->setInvalidDecl(); | ||||||
6860 | if (NewTemplate) | ||||||
6861 | NewTemplate->setInvalidDecl(); | ||||||
6862 | } | ||||||
6863 | |||||||
6864 | SetNestedNameSpecifier(*this, NewVD, D); | ||||||
6865 | |||||||
6866 | // If we have any template parameter lists that don't directly belong to | ||||||
6867 | // the variable (matching the scope specifier), store them. | ||||||
6868 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; | ||||||
6869 | if (TemplateParamLists.size() > VDTemplateParamLists) | ||||||
6870 | NewVD->setTemplateParameterListsInfo( | ||||||
6871 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); | ||||||
6872 | } | ||||||
6873 | |||||||
6874 | if (D.getDeclSpec().isInlineSpecified()) { | ||||||
6875 | if (!getLangOpts().CPlusPlus) { | ||||||
6876 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
6877 | << 0; | ||||||
6878 | } else if (CurContext->isFunctionOrMethod()) { | ||||||
6879 | // 'inline' is not allowed on block scope variable declaration. | ||||||
6880 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
6881 | diag::err_inline_declaration_block_scope) << Name | ||||||
6882 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||||
6883 | } else { | ||||||
6884 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
6885 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable | ||||||
6886 | : diag::ext_inline_variable); | ||||||
6887 | NewVD->setInlineSpecified(); | ||||||
6888 | } | ||||||
6889 | } | ||||||
6890 | |||||||
6891 | // Set the lexical context. If the declarator has a C++ scope specifier, the | ||||||
6892 | // lexical context will be different from the semantic context. | ||||||
6893 | NewVD->setLexicalDeclContext(CurContext); | ||||||
6894 | if (NewTemplate) | ||||||
6895 | NewTemplate->setLexicalDeclContext(CurContext); | ||||||
6896 | |||||||
6897 | if (IsLocalExternDecl) { | ||||||
6898 | if (D.isDecompositionDeclarator()) | ||||||
6899 | for (auto *B : Bindings) | ||||||
6900 | B->setLocalExternDecl(); | ||||||
6901 | else | ||||||
6902 | NewVD->setLocalExternDecl(); | ||||||
6903 | } | ||||||
6904 | |||||||
6905 | bool EmitTLSUnsupportedError = false; | ||||||
6906 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { | ||||||
6907 | // C++11 [dcl.stc]p4: | ||||||
6908 | // When thread_local is applied to a variable of block scope the | ||||||
6909 | // storage-class-specifier static is implied if it does not appear | ||||||
6910 | // explicitly. | ||||||
6911 | // Core issue: 'static' is not implied if the variable is declared | ||||||
6912 | // 'extern'. | ||||||
6913 | if (NewVD->hasLocalStorage() && | ||||||
6914 | (SCSpec != DeclSpec::SCS_unspecified || | ||||||
6915 | TSCS != DeclSpec::TSCS_thread_local || | ||||||
6916 | !DC->isFunctionOrMethod())) | ||||||
6917 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
6918 | diag::err_thread_non_global) | ||||||
6919 | << DeclSpec::getSpecifierName(TSCS); | ||||||
6920 | else if (!Context.getTargetInfo().isTLSSupported()) { | ||||||
6921 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | ||||||
6922 | // Postpone error emission until we've collected attributes required to | ||||||
6923 | // figure out whether it's a host or device variable and whether the | ||||||
6924 | // error should be ignored. | ||||||
6925 | EmitTLSUnsupportedError = true; | ||||||
6926 | // We still need to mark the variable as TLS so it shows up in AST with | ||||||
6927 | // proper storage class for other tools to use even if we're not going | ||||||
6928 | // to emit any code for it. | ||||||
6929 | NewVD->setTSCSpec(TSCS); | ||||||
6930 | } else | ||||||
6931 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
6932 | diag::err_thread_unsupported); | ||||||
6933 | } else | ||||||
6934 | NewVD->setTSCSpec(TSCS); | ||||||
6935 | } | ||||||
6936 | |||||||
6937 | switch (D.getDeclSpec().getConstexprSpecifier()) { | ||||||
6938 | case CSK_unspecified: | ||||||
6939 | break; | ||||||
6940 | |||||||
6941 | case CSK_consteval: | ||||||
6942 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
6943 | diag::err_constexpr_wrong_decl_kind) | ||||||
6944 | << D.getDeclSpec().getConstexprSpecifier(); | ||||||
6945 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
6946 | |||||||
6947 | case CSK_constexpr: | ||||||
6948 | NewVD->setConstexpr(true); | ||||||
6949 | // C++1z [dcl.spec.constexpr]p1: | ||||||
6950 | // A static data member declared with the constexpr specifier is | ||||||
6951 | // implicitly an inline variable. | ||||||
6952 | if (NewVD->isStaticDataMember() && | ||||||
6953 | (getLangOpts().CPlusPlus17 || | ||||||
6954 | Context.getTargetInfo().getCXXABI().isMicrosoft())) | ||||||
6955 | NewVD->setImplicitlyInline(); | ||||||
6956 | break; | ||||||
6957 | |||||||
6958 | case CSK_constinit: | ||||||
6959 | if (!NewVD->hasGlobalStorage()) | ||||||
6960 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
6961 | diag::err_constinit_local_variable); | ||||||
6962 | else | ||||||
6963 | NewVD->addAttr(ConstInitAttr::Create( | ||||||
6964 | Context, D.getDeclSpec().getConstexprSpecLoc(), | ||||||
6965 | AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); | ||||||
6966 | break; | ||||||
6967 | } | ||||||
6968 | |||||||
6969 | // C99 6.7.4p3 | ||||||
6970 | // An inline definition of a function with external linkage shall | ||||||
6971 | // not contain a definition of a modifiable object with static or | ||||||
6972 | // thread storage duration... | ||||||
6973 | // We only apply this when the function is required to be defined | ||||||
6974 | // elsewhere, i.e. when the function is not 'extern inline'. Note | ||||||
6975 | // that a local variable with thread storage duration still has to | ||||||
6976 | // be marked 'static'. Also note that it's possible to get these | ||||||
6977 | // semantics in C++ using __attribute__((gnu_inline)). | ||||||
6978 | if (SC == SC_Static && S->getFnParent() != nullptr && | ||||||
6979 | !NewVD->getType().isConstQualified()) { | ||||||
6980 | FunctionDecl *CurFD = getCurFunctionDecl(); | ||||||
6981 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { | ||||||
6982 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6983 | diag::warn_static_local_in_extern_inline); | ||||||
6984 | MaybeSuggestAddingStaticToDecl(CurFD); | ||||||
6985 | } | ||||||
6986 | } | ||||||
6987 | |||||||
6988 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
6989 | if (IsVariableTemplateSpecialization) | ||||||
6990 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||||
6991 | << (IsPartialSpecialization ? 1 : 0) | ||||||
6992 | << FixItHint::CreateRemoval( | ||||||
6993 | D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
6994 | else if (IsMemberSpecialization) | ||||||
6995 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||||
6996 | << 2 | ||||||
6997 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
6998 | else if (NewVD->hasLocalStorage()) | ||||||
6999 | Diag(NewVD->getLocation(), diag::err_module_private_local) | ||||||
7000 | << 0 << NewVD->getDeclName() | ||||||
7001 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
7002 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
7003 | else { | ||||||
7004 | NewVD->setModulePrivate(); | ||||||
7005 | if (NewTemplate) | ||||||
7006 | NewTemplate->setModulePrivate(); | ||||||
7007 | for (auto *B : Bindings) | ||||||
7008 | B->setModulePrivate(); | ||||||
7009 | } | ||||||
7010 | } | ||||||
7011 | |||||||
7012 | if (getLangOpts().OpenCL) { | ||||||
7013 | |||||||
7014 | deduceOpenCLAddressSpace(NewVD); | ||||||
7015 | |||||||
7016 | diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); | ||||||
7017 | } | ||||||
7018 | |||||||
7019 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||||
7020 | ProcessDeclAttributes(S, NewVD, D); | ||||||
7021 | |||||||
7022 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { | ||||||
7023 | if (EmitTLSUnsupportedError && | ||||||
7024 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || | ||||||
7025 | (getLangOpts().OpenMPIsDevice && | ||||||
7026 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) | ||||||
7027 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
7028 | diag::err_thread_unsupported); | ||||||
7029 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static | ||||||
7030 | // storage [duration]." | ||||||
7031 | if (SC == SC_None && S->getFnParent() != nullptr && | ||||||
7032 | (NewVD->hasAttr<CUDASharedAttr>() || | ||||||
7033 | NewVD->hasAttr<CUDAConstantAttr>())) { | ||||||
7034 | NewVD->setStorageClass(SC_Static); | ||||||
7035 | } | ||||||
7036 | } | ||||||
7037 | |||||||
7038 | // Ensure that dllimport globals without explicit storage class are treated as | ||||||
7039 | // extern. The storage class is set above using parsed attributes. Now we can | ||||||
7040 | // check the VarDecl itself. | ||||||
7041 | assert(!NewVD->hasAttr<DLLImportAttr>() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 7043, __PRETTY_FUNCTION__)) | ||||||
7042 | NewVD->getAttr<DLLImportAttr>()->isInherited() ||((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 7043, __PRETTY_FUNCTION__)) | ||||||
7043 | NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr <DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember () || NewVD->getStorageClass() != SC_None) ? static_cast< void> (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 7043, __PRETTY_FUNCTION__)); | ||||||
7044 | |||||||
7045 | // In auto-retain/release, infer strong retension for variables of | ||||||
7046 | // retainable type. | ||||||
7047 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) | ||||||
7048 | NewVD->setInvalidDecl(); | ||||||
7049 | |||||||
7050 | // Handle GNU asm-label extension (encoded as an attribute). | ||||||
7051 | if (Expr *E = (Expr*)D.getAsmLabel()) { | ||||||
7052 | // The parser guarantees this is a string. | ||||||
7053 | StringLiteral *SE = cast<StringLiteral>(E); | ||||||
7054 | StringRef Label = SE->getString(); | ||||||
7055 | if (S->getFnParent() != nullptr) { | ||||||
7056 | switch (SC) { | ||||||
7057 | case SC_None: | ||||||
7058 | case SC_Auto: | ||||||
7059 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; | ||||||
7060 | break; | ||||||
7061 | case SC_Register: | ||||||
7062 | // Local Named register | ||||||
7063 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && | ||||||
7064 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) | ||||||
7065 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||||
7066 | break; | ||||||
7067 | case SC_Static: | ||||||
7068 | case SC_Extern: | ||||||
7069 | case SC_PrivateExtern: | ||||||
7070 | break; | ||||||
7071 | } | ||||||
7072 | } else if (SC == SC_Register) { | ||||||
7073 | // Global Named register | ||||||
7074 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { | ||||||
7075 | const auto &TI = Context.getTargetInfo(); | ||||||
7076 | bool HasSizeMismatch; | ||||||
7077 | |||||||
7078 | if (!TI.isValidGCCRegisterName(Label)) | ||||||
7079 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||||
7080 | else if (!TI.validateGlobalRegisterVariable(Label, | ||||||
7081 | Context.getTypeSize(R), | ||||||
7082 | HasSizeMismatch)) | ||||||
7083 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; | ||||||
7084 | else if (HasSizeMismatch) | ||||||
7085 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; | ||||||
7086 | } | ||||||
7087 | |||||||
7088 | if (!R->isIntegralType(Context) && !R->isPointerType()) { | ||||||
7089 | Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); | ||||||
7090 | NewVD->setInvalidDecl(true); | ||||||
7091 | } | ||||||
7092 | } | ||||||
7093 | |||||||
7094 | NewVD->addAttr(AsmLabelAttr::Create(Context, Label, | ||||||
7095 | /*IsLiteralLabel=*/true, | ||||||
7096 | SE->getStrTokenLoc(0))); | ||||||
7097 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||||
7098 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||||
7099 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); | ||||||
7100 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||||
7101 | if (isDeclExternC(NewVD)) { | ||||||
7102 | NewVD->addAttr(I->second); | ||||||
7103 | ExtnameUndeclaredIdentifiers.erase(I); | ||||||
7104 | } else | ||||||
7105 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
7106 | << /*Variable*/1 << NewVD; | ||||||
7107 | } | ||||||
7108 | } | ||||||
7109 | |||||||
7110 | // Find the shadowed declaration before filtering for scope. | ||||||
7111 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() | ||||||
7112 | ? getShadowedDeclaration(NewVD, Previous) | ||||||
7113 | : nullptr; | ||||||
7114 | |||||||
7115 | // Don't consider existing declarations that are in a different | ||||||
7116 | // scope and are out-of-semantic-context declarations (if the new | ||||||
7117 | // declaration has linkage). | ||||||
7118 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), | ||||||
7119 | D.getCXXScopeSpec().isNotEmpty() || | ||||||
7120 | IsMemberSpecialization || | ||||||
7121 | IsVariableTemplateSpecialization); | ||||||
7122 | |||||||
7123 | // Check whether the previous declaration is in the same block scope. This | ||||||
7124 | // affects whether we merge types with it, per C++11 [dcl.array]p3. | ||||||
7125 | if (getLangOpts().CPlusPlus && | ||||||
7126 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) | ||||||
7127 | NewVD->setPreviousDeclInSameBlockScope( | ||||||
7128 | Previous.isSingleResult() && !Previous.isShadowed() && | ||||||
7129 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); | ||||||
7130 | |||||||
7131 | if (!getLangOpts().CPlusPlus) { | ||||||
7132 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||||
7133 | } else { | ||||||
7134 | // If this is an explicit specialization of a static data member, check it. | ||||||
7135 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && | ||||||
7136 | CheckMemberSpecialization(NewVD, Previous)) | ||||||
7137 | NewVD->setInvalidDecl(); | ||||||
7138 | |||||||
7139 | // Merge the decl with the existing one if appropriate. | ||||||
7140 | if (!Previous.empty()) { | ||||||
7141 | if (Previous.isSingleResult() && | ||||||
7142 | isa<FieldDecl>(Previous.getFoundDecl()) && | ||||||
7143 | D.getCXXScopeSpec().isSet()) { | ||||||
7144 | // The user tried to define a non-static data member | ||||||
7145 | // out-of-line (C++ [dcl.meaning]p1). | ||||||
7146 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) | ||||||
7147 | << D.getCXXScopeSpec().getRange(); | ||||||
7148 | Previous.clear(); | ||||||
7149 | NewVD->setInvalidDecl(); | ||||||
7150 | } | ||||||
7151 | } else if (D.getCXXScopeSpec().isSet()) { | ||||||
7152 | // No previous declaration in the qualifying scope. | ||||||
7153 | Diag(D.getIdentifierLoc(), diag::err_no_member) | ||||||
7154 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) | ||||||
7155 | << D.getCXXScopeSpec().getRange(); | ||||||
7156 | NewVD->setInvalidDecl(); | ||||||
7157 | } | ||||||
7158 | |||||||
7159 | if (!IsVariableTemplateSpecialization) | ||||||
7160 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||||
7161 | |||||||
7162 | if (NewTemplate) { | ||||||
7163 | VarTemplateDecl *PrevVarTemplate = | ||||||
7164 | NewVD->getPreviousDecl() | ||||||
7165 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() | ||||||
7166 | : nullptr; | ||||||
7167 | |||||||
7168 | // Check the template parameter list of this declaration, possibly | ||||||
7169 | // merging in the template parameter list from the previous variable | ||||||
7170 | // template declaration. | ||||||
7171 | if (CheckTemplateParameterList( | ||||||
7172 | TemplateParams, | ||||||
7173 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() | ||||||
7174 | : nullptr, | ||||||
7175 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && | ||||||
7176 | DC->isDependentContext()) | ||||||
7177 | ? TPC_ClassTemplateMember | ||||||
7178 | : TPC_VarTemplate)) | ||||||
7179 | NewVD->setInvalidDecl(); | ||||||
7180 | |||||||
7181 | // If we are providing an explicit specialization of a static variable | ||||||
7182 | // template, make a note of that. | ||||||
7183 | if (PrevVarTemplate && | ||||||
7184 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) | ||||||
7185 | PrevVarTemplate->setMemberSpecialization(); | ||||||
7186 | } | ||||||
7187 | } | ||||||
7188 | |||||||
7189 | // Diagnose shadowed variables iff this isn't a redeclaration. | ||||||
7190 | if (ShadowedDecl && !D.isRedeclaration()) | ||||||
7191 | CheckShadow(NewVD, ShadowedDecl, Previous); | ||||||
7192 | |||||||
7193 | ProcessPragmaWeak(S, NewVD); | ||||||
7194 | |||||||
7195 | // If this is the first declaration of an extern C variable, update | ||||||
7196 | // the map of such variables. | ||||||
7197 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && | ||||||
7198 | isIncompleteDeclExternC(*this, NewVD)) | ||||||
7199 | RegisterLocallyScopedExternCDecl(NewVD, S); | ||||||
7200 | |||||||
7201 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||||
7202 | MangleNumberingContext *MCtx; | ||||||
7203 | Decl *ManglingContextDecl; | ||||||
7204 | std::tie(MCtx, ManglingContextDecl) = | ||||||
7205 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | ||||||
7206 | if (MCtx) { | ||||||
7207 | Context.setManglingNumber( | ||||||
7208 | NewVD, MCtx->getManglingNumber( | ||||||
7209 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||||
7210 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||||
7211 | } | ||||||
7212 | } | ||||||
7213 | |||||||
7214 | // Special handling of variable named 'main'. | ||||||
7215 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && | ||||||
7216 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||||
7217 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { | ||||||
7218 | |||||||
7219 | // C++ [basic.start.main]p3 | ||||||
7220 | // A program that declares a variable main at global scope is ill-formed. | ||||||
7221 | if (getLangOpts().CPlusPlus) | ||||||
7222 | Diag(D.getBeginLoc(), diag::err_main_global_variable); | ||||||
7223 | |||||||
7224 | // In C, and external-linkage variable named main results in undefined | ||||||
7225 | // behavior. | ||||||
7226 | else if (NewVD->hasExternalFormalLinkage()) | ||||||
7227 | Diag(D.getBeginLoc(), diag::warn_main_redefined); | ||||||
7228 | } | ||||||
7229 | |||||||
7230 | if (D.isRedeclaration() && !Previous.empty()) { | ||||||
7231 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||||
7232 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, | ||||||
7233 | D.isFunctionDefinition()); | ||||||
7234 | } | ||||||
7235 | |||||||
7236 | if (NewTemplate) { | ||||||
7237 | if (NewVD->isInvalidDecl()) | ||||||
7238 | NewTemplate->setInvalidDecl(); | ||||||
7239 | ActOnDocumentableDecl(NewTemplate); | ||||||
7240 | return NewTemplate; | ||||||
7241 | } | ||||||
7242 | |||||||
7243 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) | ||||||
7244 | CompleteMemberSpecialization(NewVD, Previous); | ||||||
7245 | |||||||
7246 | return NewVD; | ||||||
7247 | } | ||||||
7248 | |||||||
7249 | /// Enum describing the %select options in diag::warn_decl_shadow. | ||||||
7250 | enum ShadowedDeclKind { | ||||||
7251 | SDK_Local, | ||||||
7252 | SDK_Global, | ||||||
7253 | SDK_StaticMember, | ||||||
7254 | SDK_Field, | ||||||
7255 | SDK_Typedef, | ||||||
7256 | SDK_Using | ||||||
7257 | }; | ||||||
7258 | |||||||
7259 | /// Determine what kind of declaration we're shadowing. | ||||||
7260 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, | ||||||
7261 | const DeclContext *OldDC) { | ||||||
7262 | if (isa<TypeAliasDecl>(ShadowedDecl)) | ||||||
7263 | return SDK_Using; | ||||||
7264 | else if (isa<TypedefDecl>(ShadowedDecl)) | ||||||
7265 | return SDK_Typedef; | ||||||
7266 | else if (isa<RecordDecl>(OldDC)) | ||||||
7267 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; | ||||||
7268 | |||||||
7269 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; | ||||||
7270 | } | ||||||
7271 | |||||||
7272 | /// Return the location of the capture if the given lambda captures the given | ||||||
7273 | /// variable \p VD, or an invalid source location otherwise. | ||||||
7274 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, | ||||||
7275 | const VarDecl *VD) { | ||||||
7276 | for (const Capture &Capture : LSI->Captures) { | ||||||
7277 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) | ||||||
7278 | return Capture.getLocation(); | ||||||
7279 | } | ||||||
7280 | return SourceLocation(); | ||||||
7281 | } | ||||||
7282 | |||||||
7283 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, | ||||||
7284 | const LookupResult &R) { | ||||||
7285 | // Only diagnose if we're shadowing an unambiguous field or variable. | ||||||
7286 | if (R.getResultKind() != LookupResult::Found) | ||||||
7287 | return false; | ||||||
7288 | |||||||
7289 | // Return false if warning is ignored. | ||||||
7290 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); | ||||||
7291 | } | ||||||
7292 | |||||||
7293 | /// Return the declaration shadowed by the given variable \p D, or null | ||||||
7294 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||||
7295 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, | ||||||
7296 | const LookupResult &R) { | ||||||
7297 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||||
7298 | return nullptr; | ||||||
7299 | |||||||
7300 | // Don't diagnose declarations at file scope. | ||||||
7301 | if (D->hasGlobalStorage()) | ||||||
7302 | return nullptr; | ||||||
7303 | |||||||
7304 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||||
7305 | return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) | ||||||
7306 | ? ShadowedDecl | ||||||
7307 | : nullptr; | ||||||
7308 | } | ||||||
7309 | |||||||
7310 | /// Return the declaration shadowed by the given typedef \p D, or null | ||||||
7311 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||||
7312 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, | ||||||
7313 | const LookupResult &R) { | ||||||
7314 | // Don't warn if typedef declaration is part of a class | ||||||
7315 | if (D->getDeclContext()->isRecord()) | ||||||
7316 | return nullptr; | ||||||
7317 | |||||||
7318 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||||
7319 | return nullptr; | ||||||
7320 | |||||||
7321 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||||
7322 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; | ||||||
7323 | } | ||||||
7324 | |||||||
7325 | /// Diagnose variable or built-in function shadowing. Implements | ||||||
7326 | /// -Wshadow. | ||||||
7327 | /// | ||||||
7328 | /// This method is called whenever a VarDecl is added to a "useful" | ||||||
7329 | /// scope. | ||||||
7330 | /// | ||||||
7331 | /// \param ShadowedDecl the declaration that is shadowed by the given variable | ||||||
7332 | /// \param R the lookup of the name | ||||||
7333 | /// | ||||||
7334 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | ||||||
7335 | const LookupResult &R) { | ||||||
7336 | DeclContext *NewDC = D->getDeclContext(); | ||||||
7337 | |||||||
7338 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { | ||||||
7339 | // Fields are not shadowed by variables in C++ static methods. | ||||||
7340 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) | ||||||
7341 | if (MD->isStatic()) | ||||||
7342 | return; | ||||||
7343 | |||||||
7344 | // Fields shadowed by constructor parameters are a special case. Usually | ||||||
7345 | // the constructor initializes the field with the parameter. | ||||||
7346 | if (isa<CXXConstructorDecl>(NewDC)) | ||||||
7347 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { | ||||||
7348 | // Remember that this was shadowed so we can either warn about its | ||||||
7349 | // modification or its existence depending on warning settings. | ||||||
7350 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); | ||||||
7351 | return; | ||||||
7352 | } | ||||||
7353 | } | ||||||
7354 | |||||||
7355 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) | ||||||
7356 | if (shadowedVar->isExternC()) { | ||||||
7357 | // For shadowing external vars, make sure that we point to the global | ||||||
7358 | // declaration, not a locally scoped extern declaration. | ||||||
7359 | for (auto I : shadowedVar->redecls()) | ||||||
7360 | if (I->isFileVarDecl()) { | ||||||
7361 | ShadowedDecl = I; | ||||||
7362 | break; | ||||||
7363 | } | ||||||
7364 | } | ||||||
7365 | |||||||
7366 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); | ||||||
7367 | |||||||
7368 | unsigned WarningDiag = diag::warn_decl_shadow; | ||||||
7369 | SourceLocation CaptureLoc; | ||||||
7370 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && | ||||||
7371 | isa<CXXMethodDecl>(NewDC)) { | ||||||
7372 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { | ||||||
7373 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { | ||||||
7374 | if (RD->getLambdaCaptureDefault() == LCD_None) { | ||||||
7375 | // Try to avoid warnings for lambdas with an explicit capture list. | ||||||
7376 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); | ||||||
7377 | // Warn only when the lambda captures the shadowed decl explicitly. | ||||||
7378 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); | ||||||
7379 | if (CaptureLoc.isInvalid()) | ||||||
7380 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; | ||||||
7381 | } else { | ||||||
7382 | // Remember that this was shadowed so we can avoid the warning if the | ||||||
7383 | // shadowed decl isn't captured and the warning settings allow it. | ||||||
7384 | cast<LambdaScopeInfo>(getCurFunction()) | ||||||
7385 | ->ShadowingDecls.push_back( | ||||||
7386 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); | ||||||
7387 | return; | ||||||
7388 | } | ||||||
7389 | } | ||||||
7390 | |||||||
7391 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { | ||||||
7392 | // A variable can't shadow a local variable in an enclosing scope, if | ||||||
7393 | // they are separated by a non-capturing declaration context. | ||||||
7394 | for (DeclContext *ParentDC = NewDC; | ||||||
7395 | ParentDC && !ParentDC->Equals(OldDC); | ||||||
7396 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { | ||||||
7397 | // Only block literals, captured statements, and lambda expressions | ||||||
7398 | // can capture; other scopes don't. | ||||||
7399 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && | ||||||
7400 | !isLambdaCallOperator(ParentDC)) { | ||||||
7401 | return; | ||||||
7402 | } | ||||||
7403 | } | ||||||
7404 | } | ||||||
7405 | } | ||||||
7406 | } | ||||||
7407 | |||||||
7408 | // Only warn about certain kinds of shadowing for class members. | ||||||
7409 | if (NewDC && NewDC->isRecord()) { | ||||||
7410 | // In particular, don't warn about shadowing non-class members. | ||||||
7411 | if (!OldDC->isRecord()) | ||||||
7412 | return; | ||||||
7413 | |||||||
7414 | // TODO: should we warn about static data members shadowing | ||||||
7415 | // static data members from base classes? | ||||||
7416 | |||||||
7417 | // TODO: don't diagnose for inaccessible shadowed members. | ||||||
7418 | // This is hard to do perfectly because we might friend the | ||||||
7419 | // shadowing context, but that's just a false negative. | ||||||
7420 | } | ||||||
7421 | |||||||
7422 | |||||||
7423 | DeclarationName Name = R.getLookupName(); | ||||||
7424 | |||||||
7425 | // Emit warning and note. | ||||||
7426 | if (getSourceManager().isInSystemMacro(R.getNameLoc())) | ||||||
7427 | return; | ||||||
7428 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); | ||||||
7429 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; | ||||||
7430 | if (!CaptureLoc.isInvalid()) | ||||||
7431 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||||
7432 | << Name << /*explicitly*/ 1; | ||||||
7433 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7434 | } | ||||||
7435 | |||||||
7436 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD | ||||||
7437 | /// when these variables are captured by the lambda. | ||||||
7438 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { | ||||||
7439 | for (const auto &Shadow : LSI->ShadowingDecls) { | ||||||
7440 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; | ||||||
7441 | // Try to avoid the warning when the shadowed decl isn't captured. | ||||||
7442 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); | ||||||
7443 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||||
7444 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() | ||||||
7445 | ? diag::warn_decl_shadow_uncaptured_local | ||||||
7446 | : diag::warn_decl_shadow) | ||||||
7447 | << Shadow.VD->getDeclName() | ||||||
7448 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; | ||||||
7449 | if (!CaptureLoc.isInvalid()) | ||||||
7450 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||||
7451 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; | ||||||
7452 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7453 | } | ||||||
7454 | } | ||||||
7455 | |||||||
7456 | /// Check -Wshadow without the advantage of a previous lookup. | ||||||
7457 | void Sema::CheckShadow(Scope *S, VarDecl *D) { | ||||||
7458 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) | ||||||
7459 | return; | ||||||
7460 | |||||||
7461 | LookupResult R(*this, D->getDeclName(), D->getLocation(), | ||||||
7462 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); | ||||||
7463 | LookupName(R, S); | ||||||
7464 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) | ||||||
7465 | CheckShadow(D, ShadowedDecl, R); | ||||||
7466 | } | ||||||
7467 | |||||||
7468 | /// Check if 'E', which is an expression that is about to be modified, refers | ||||||
7469 | /// to a constructor parameter that shadows a field. | ||||||
7470 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { | ||||||
7471 | // Quickly ignore expressions that can't be shadowing ctor parameters. | ||||||
7472 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) | ||||||
7473 | return; | ||||||
7474 | E = E->IgnoreParenImpCasts(); | ||||||
7475 | auto *DRE = dyn_cast<DeclRefExpr>(E); | ||||||
7476 | if (!DRE) | ||||||
7477 | return; | ||||||
7478 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); | ||||||
7479 | auto I = ShadowingDecls.find(D); | ||||||
7480 | if (I == ShadowingDecls.end()) | ||||||
7481 | return; | ||||||
7482 | const NamedDecl *ShadowedDecl = I->second; | ||||||
7483 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||||
7484 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; | ||||||
7485 | Diag(D->getLocation(), diag::note_var_declared_here) << D; | ||||||
7486 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7487 | |||||||
7488 | // Avoid issuing multiple warnings about the same decl. | ||||||
7489 | ShadowingDecls.erase(I); | ||||||
7490 | } | ||||||
7491 | |||||||
7492 | /// Check for conflict between this global or extern "C" declaration and | ||||||
7493 | /// previous global or extern "C" declarations. This is only used in C++. | ||||||
7494 | template<typename T> | ||||||
7495 | static bool checkGlobalOrExternCConflict( | ||||||
7496 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { | ||||||
7497 | assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"" ) ? static_cast<void> (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 7497, __PRETTY_FUNCTION__)); | ||||||
7498 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); | ||||||
7499 | |||||||
7500 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { | ||||||
7501 | // The common case: this global doesn't conflict with any extern "C" | ||||||
7502 | // declaration. | ||||||
7503 | return false; | ||||||
7504 | } | ||||||
7505 | |||||||
7506 | if (Prev) { | ||||||
7507 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { | ||||||
7508 | // Both the old and new declarations have C language linkage. This is a | ||||||
7509 | // redeclaration. | ||||||
7510 | Previous.clear(); | ||||||
7511 | Previous.addDecl(Prev); | ||||||
7512 | return true; | ||||||
7513 | } | ||||||
7514 | |||||||
7515 | // This is a global, non-extern "C" declaration, and there is a previous | ||||||
7516 | // non-global extern "C" declaration. Diagnose if this is a variable | ||||||
7517 | // declaration. | ||||||
7518 | if (!isa<VarDecl>(ND)) | ||||||
7519 | return false; | ||||||
7520 | } else { | ||||||
7521 | // The declaration is extern "C". Check for any declaration in the | ||||||
7522 | // translation unit which might conflict. | ||||||
7523 | if (IsGlobal) { | ||||||
7524 | // We have already performed the lookup into the translation unit. | ||||||
7525 | IsGlobal = false; | ||||||
7526 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||||
7527 | I != E; ++I) { | ||||||
7528 | if (isa<VarDecl>(*I)) { | ||||||
7529 | Prev = *I; | ||||||
7530 | break; | ||||||
7531 | } | ||||||
7532 | } | ||||||
7533 | } else { | ||||||
7534 | DeclContext::lookup_result R = | ||||||
7535 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); | ||||||
7536 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); | ||||||
7537 | I != E; ++I) { | ||||||
7538 | if (isa<VarDecl>(*I)) { | ||||||
7539 | Prev = *I; | ||||||
7540 | break; | ||||||
7541 | } | ||||||
7542 | // FIXME: If we have any other entity with this name in global scope, | ||||||
7543 | // the declaration is ill-formed, but that is a defect: it breaks the | ||||||
7544 | // 'stat' hack, for instance. Only variables can have mangled name | ||||||
7545 | // clashes with extern "C" declarations, so only they deserve a | ||||||
7546 | // diagnostic. | ||||||
7547 | } | ||||||
7548 | } | ||||||
7549 | |||||||
7550 | if (!Prev) | ||||||
7551 | return false; | ||||||
7552 | } | ||||||
7553 | |||||||
7554 | // Use the first declaration's location to ensure we point at something which | ||||||
7555 | // is lexically inside an extern "C" linkage-spec. | ||||||
7556 | assert(Prev && "should have found a previous declaration to diagnose")((Prev && "should have found a previous declaration to diagnose" ) ? static_cast<void> (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 7556, __PRETTY_FUNCTION__)); | ||||||
7557 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) | ||||||
7558 | Prev = FD->getFirstDecl(); | ||||||
7559 | else | ||||||
7560 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); | ||||||
7561 | |||||||
7562 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) | ||||||
7563 | << IsGlobal << ND; | ||||||
7564 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) | ||||||
7565 | << IsGlobal; | ||||||
7566 | return false; | ||||||
7567 | } | ||||||
7568 | |||||||
7569 | /// Apply special rules for handling extern "C" declarations. Returns \c true | ||||||
7570 | /// if we have found that this is a redeclaration of some prior entity. | ||||||
7571 | /// | ||||||
7572 | /// Per C++ [dcl.link]p6: | ||||||
7573 | /// Two declarations [for a function or variable] with C language linkage | ||||||
7574 | /// with the same name that appear in different scopes refer to the same | ||||||
7575 | /// [entity]. An entity with C language linkage shall not be declared with | ||||||
7576 | /// the same name as an entity in global scope. | ||||||
7577 | template<typename T> | ||||||
7578 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, | ||||||
7579 | LookupResult &Previous) { | ||||||
7580 | if (!S.getLangOpts().CPlusPlus) { | ||||||
7581 | // In C, when declaring a global variable, look for a corresponding 'extern' | ||||||
7582 | // variable declared in function scope. We don't need this in C++, because | ||||||
7583 | // we find local extern decls in the surrounding file-scope DeclContext. | ||||||
7584 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
7585 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { | ||||||
7586 | Previous.clear(); | ||||||
7587 | Previous.addDecl(Prev); | ||||||
7588 | return true; | ||||||
7589 | } | ||||||
7590 | } | ||||||
7591 | return false; | ||||||
7592 | } | ||||||
7593 | |||||||
7594 | // A declaration in the translation unit can conflict with an extern "C" | ||||||
7595 | // declaration. | ||||||
7596 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||||
7597 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); | ||||||
7598 | |||||||
7599 | // An extern "C" declaration can conflict with a declaration in the | ||||||
7600 | // translation unit or can be a redeclaration of an extern "C" declaration | ||||||
7601 | // in another scope. | ||||||
7602 | if (isIncompleteDeclExternC(S,ND)) | ||||||
7603 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); | ||||||
7604 | |||||||
7605 | // Neither global nor extern "C": nothing to do. | ||||||
7606 | return false; | ||||||
7607 | } | ||||||
7608 | |||||||
7609 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { | ||||||
7610 | // If the decl is already known invalid, don't check it. | ||||||
7611 | if (NewVD->isInvalidDecl()) | ||||||
7612 | return; | ||||||
7613 | |||||||
7614 | QualType T = NewVD->getType(); | ||||||
7615 | |||||||
7616 | // Defer checking an 'auto' type until its initializer is attached. | ||||||
7617 | if (T->isUndeducedType()) | ||||||
7618 | return; | ||||||
7619 | |||||||
7620 | if (NewVD->hasAttrs()) | ||||||
7621 | CheckAlignasUnderalignment(NewVD); | ||||||
7622 | |||||||
7623 | if (T->isObjCObjectType()) { | ||||||
7624 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) | ||||||
7625 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); | ||||||
7626 | T = Context.getObjCObjectPointerType(T); | ||||||
7627 | NewVD->setType(T); | ||||||
7628 | } | ||||||
7629 | |||||||
7630 | // Emit an error if an address space was applied to decl with local storage. | ||||||
7631 | // This includes arrays of objects with address space qualifiers, but not | ||||||
7632 | // automatic variables that point to other address spaces. | ||||||
7633 | // ISO/IEC TR 18037 S5.1.2 | ||||||
7634 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && | ||||||
7635 | T.getAddressSpace() != LangAS::Default) { | ||||||
7636 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; | ||||||
7637 | NewVD->setInvalidDecl(); | ||||||
7638 | return; | ||||||
7639 | } | ||||||
7640 | |||||||
7641 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program | ||||||
7642 | // scope. | ||||||
7643 | if (getLangOpts().OpenCLVersion == 120 && | ||||||
7644 | !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && | ||||||
7645 | NewVD->isStaticLocal()) { | ||||||
7646 | Diag(NewVD->getLocation(), diag::err_static_function_scope); | ||||||
7647 | NewVD->setInvalidDecl(); | ||||||
7648 | return; | ||||||
7649 | } | ||||||
7650 | |||||||
7651 | if (getLangOpts().OpenCL) { | ||||||
7652 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. | ||||||
7653 | if (NewVD->hasAttr<BlocksAttr>()) { | ||||||
7654 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); | ||||||
7655 | return; | ||||||
7656 | } | ||||||
7657 | |||||||
7658 | if (T->isBlockPointerType()) { | ||||||
7659 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and | ||||||
7660 | // can't use 'extern' storage class. | ||||||
7661 | if (!T.isConstQualified()) { | ||||||
7662 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||||
7663 | << 0 /*const*/; | ||||||
7664 | NewVD->setInvalidDecl(); | ||||||
7665 | return; | ||||||
7666 | } | ||||||
7667 | if (NewVD->hasExternalStorage()) { | ||||||
7668 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); | ||||||
7669 | NewVD->setInvalidDecl(); | ||||||
7670 | return; | ||||||
7671 | } | ||||||
7672 | } | ||||||
7673 | // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the | ||||||
7674 | // __constant address space. | ||||||
7675 | // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static | ||||||
7676 | // variables inside a function can also be declared in the global | ||||||
7677 | // address space. | ||||||
7678 | // C++ for OpenCL inherits rule from OpenCL C v2.0. | ||||||
7679 | // FIXME: Adding local AS in C++ for OpenCL might make sense. | ||||||
7680 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || | ||||||
7681 | NewVD->hasExternalStorage()) { | ||||||
7682 | if (!T->isSamplerT() && | ||||||
7683 | !(T.getAddressSpace() == LangAS::opencl_constant || | ||||||
7684 | (T.getAddressSpace() == LangAS::opencl_global && | ||||||
7685 | (getLangOpts().OpenCLVersion == 200 || | ||||||
7686 | getLangOpts().OpenCLCPlusPlus)))) { | ||||||
7687 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; | ||||||
7688 | if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) | ||||||
7689 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||||
7690 | << Scope << "global or constant"; | ||||||
7691 | else | ||||||
7692 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||||
7693 | << Scope << "constant"; | ||||||
7694 | NewVD->setInvalidDecl(); | ||||||
7695 | return; | ||||||
7696 | } | ||||||
7697 | } else { | ||||||
7698 | if (T.getAddressSpace() == LangAS::opencl_global) { | ||||||
7699 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7700 | << 1 /*is any function*/ << "global"; | ||||||
7701 | NewVD->setInvalidDecl(); | ||||||
7702 | return; | ||||||
7703 | } | ||||||
7704 | if (T.getAddressSpace() == LangAS::opencl_constant || | ||||||
7705 | T.getAddressSpace() == LangAS::opencl_local) { | ||||||
7706 | FunctionDecl *FD = getCurFunctionDecl(); | ||||||
7707 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables | ||||||
7708 | // in functions. | ||||||
7709 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { | ||||||
7710 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||||
7711 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7712 | << 0 /*non-kernel only*/ << "constant"; | ||||||
7713 | else | ||||||
7714 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7715 | << 0 /*non-kernel only*/ << "local"; | ||||||
7716 | NewVD->setInvalidDecl(); | ||||||
7717 | return; | ||||||
7718 | } | ||||||
7719 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be | ||||||
7720 | // in the outermost scope of a kernel function. | ||||||
7721 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { | ||||||
7722 | if (!getCurScope()->isFunctionScope()) { | ||||||
7723 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||||
7724 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||||
7725 | << "constant"; | ||||||
7726 | else | ||||||
7727 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||||
7728 | << "local"; | ||||||
7729 | NewVD->setInvalidDecl(); | ||||||
7730 | return; | ||||||
7731 | } | ||||||
7732 | } | ||||||
7733 | } else if (T.getAddressSpace() != LangAS::opencl_private && | ||||||
7734 | // If we are parsing a template we didn't deduce an addr | ||||||
7735 | // space yet. | ||||||
7736 | T.getAddressSpace() != LangAS::Default) { | ||||||
7737 | // Do not allow other address spaces on automatic variable. | ||||||
7738 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; | ||||||
7739 | NewVD->setInvalidDecl(); | ||||||
7740 | return; | ||||||
7741 | } | ||||||
7742 | } | ||||||
7743 | } | ||||||
7744 | |||||||
7745 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() | ||||||
7746 | && !NewVD->hasAttr<BlocksAttr>()) { | ||||||
7747 | if (getLangOpts().getGC() != LangOptions::NonGC) | ||||||
7748 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); | ||||||
7749 | else { | ||||||
7750 | assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> ( 0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 7750, __PRETTY_FUNCTION__)); | ||||||
7751 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); | ||||||
7752 | } | ||||||
7753 | } | ||||||
7754 | |||||||
7755 | bool isVM = T->isVariablyModifiedType(); | ||||||
7756 | if (isVM || NewVD->hasAttr<CleanupAttr>() || | ||||||
7757 | NewVD->hasAttr<BlocksAttr>()) | ||||||
7758 | setFunctionHasBranchProtectedScope(); | ||||||
7759 | |||||||
7760 | if ((isVM && NewVD->hasLinkage()) || | ||||||
7761 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { | ||||||
7762 | bool SizeIsNegative; | ||||||
7763 | llvm::APSInt Oversized; | ||||||
7764 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | ||||||
7765 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); | ||||||
7766 | QualType FixedT; | ||||||
7767 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) | ||||||
7768 | FixedT = FixedTInfo->getType(); | ||||||
7769 | else if (FixedTInfo) { | ||||||
7770 | // Type and type-as-written are canonically different. We need to fix up | ||||||
7771 | // both types separately. | ||||||
7772 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, | ||||||
7773 | Oversized); | ||||||
7774 | } | ||||||
7775 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { | ||||||
7776 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); | ||||||
7777 | // FIXME: This won't give the correct result for | ||||||
7778 | // int a[10][n]; | ||||||
7779 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); | ||||||
7780 | |||||||
7781 | if (NewVD->isFileVarDecl()) | ||||||
7782 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) | ||||||
7783 | << SizeRange; | ||||||
7784 | else if (NewVD->isStaticLocal()) | ||||||
7785 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) | ||||||
7786 | << SizeRange; | ||||||
7787 | else | ||||||
7788 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) | ||||||
7789 | << SizeRange; | ||||||
7790 | NewVD->setInvalidDecl(); | ||||||
7791 | return; | ||||||
7792 | } | ||||||
7793 | |||||||
7794 | if (!FixedTInfo) { | ||||||
7795 | if (NewVD->isFileVarDecl()) | ||||||
7796 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||||
7797 | else | ||||||
7798 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); | ||||||
7799 | NewVD->setInvalidDecl(); | ||||||
7800 | return; | ||||||
7801 | } | ||||||
7802 | |||||||
7803 | Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); | ||||||
7804 | NewVD->setType(FixedT); | ||||||
7805 | NewVD->setTypeSourceInfo(FixedTInfo); | ||||||
7806 | } | ||||||
7807 | |||||||
7808 | if (T->isVoidType()) { | ||||||
7809 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names | ||||||
7810 | // of objects and functions. | ||||||
7811 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { | ||||||
7812 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) | ||||||
7813 | << T; | ||||||
7814 | NewVD->setInvalidDecl(); | ||||||
7815 | return; | ||||||
7816 | } | ||||||
7817 | } | ||||||
7818 | |||||||
7819 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { | ||||||
7820 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); | ||||||
7821 | NewVD->setInvalidDecl(); | ||||||
7822 | return; | ||||||
7823 | } | ||||||
7824 | |||||||
7825 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { | ||||||
7826 | Diag(NewVD->getLocation(), diag::err_block_on_vm); | ||||||
7827 | NewVD->setInvalidDecl(); | ||||||
7828 | return; | ||||||
7829 | } | ||||||
7830 | |||||||
7831 | if (NewVD->isConstexpr() && !T->isDependentType() && | ||||||
7832 | RequireLiteralType(NewVD->getLocation(), T, | ||||||
7833 | diag::err_constexpr_var_non_literal)) { | ||||||
7834 | NewVD->setInvalidDecl(); | ||||||
7835 | return; | ||||||
7836 | } | ||||||
7837 | } | ||||||
7838 | |||||||
7839 | /// Perform semantic checking on a newly-created variable | ||||||
7840 | /// declaration. | ||||||
7841 | /// | ||||||
7842 | /// This routine performs all of the type-checking required for a | ||||||
7843 | /// variable declaration once it has been built. It is used both to | ||||||
7844 | /// check variables after they have been parsed and their declarators | ||||||
7845 | /// have been translated into a declaration, and to check variables | ||||||
7846 | /// that have been instantiated from a template. | ||||||
7847 | /// | ||||||
7848 | /// Sets NewVD->isInvalidDecl() if an error was encountered. | ||||||
7849 | /// | ||||||
7850 | /// Returns true if the variable declaration is a redeclaration. | ||||||
7851 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { | ||||||
7852 | CheckVariableDeclarationType(NewVD); | ||||||
7853 | |||||||
7854 | // If the decl is already known invalid, don't check it. | ||||||
7855 | if (NewVD->isInvalidDecl()) | ||||||
7856 | return false; | ||||||
7857 | |||||||
7858 | // If we did not find anything by this name, look for a non-visible | ||||||
7859 | // extern "C" declaration with the same name. | ||||||
7860 | if (Previous.empty() && | ||||||
7861 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) | ||||||
7862 | Previous.setShadowed(); | ||||||
7863 | |||||||
7864 | if (!Previous.empty()) { | ||||||
7865 | MergeVarDecl(NewVD, Previous); | ||||||
7866 | return true; | ||||||
7867 | } | ||||||
7868 | return false; | ||||||
7869 | } | ||||||
7870 | |||||||
7871 | namespace { | ||||||
7872 | struct FindOverriddenMethod { | ||||||
7873 | Sema *S; | ||||||
7874 | CXXMethodDecl *Method; | ||||||
7875 | |||||||
7876 | /// Member lookup function that determines whether a given C++ | ||||||
7877 | /// method overrides a method in a base class, to be used with | ||||||
7878 | /// CXXRecordDecl::lookupInBases(). | ||||||
7879 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | ||||||
7880 | RecordDecl *BaseRecord = | ||||||
7881 | Specifier->getType()->castAs<RecordType>()->getDecl(); | ||||||
7882 | |||||||
7883 | DeclarationName Name = Method->getDeclName(); | ||||||
7884 | |||||||
7885 | // FIXME: Do we care about other names here too? | ||||||
7886 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
7887 | // We really want to find the base class destructor here. | ||||||
7888 | QualType T = S->Context.getTypeDeclType(BaseRecord); | ||||||
7889 | CanQualType CT = S->Context.getCanonicalType(T); | ||||||
7890 | |||||||
7891 | Name = S->Context.DeclarationNames.getCXXDestructorName(CT); | ||||||
7892 | } | ||||||
7893 | |||||||
7894 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | ||||||
7895 | Path.Decls = Path.Decls.slice(1)) { | ||||||
7896 | NamedDecl *D = Path.Decls.front(); | ||||||
7897 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||||
7898 | if (MD->isVirtual() && | ||||||
7899 | !S->IsOverload( | ||||||
7900 | Method, MD, /*UseMemberUsingDeclRules=*/false, | ||||||
7901 | /*ConsiderCudaAttrs=*/true, | ||||||
7902 | // C++2a [class.virtual]p2 does not consider requires clauses | ||||||
7903 | // when overriding. | ||||||
7904 | /*ConsiderRequiresClauses=*/false)) | ||||||
7905 | return true; | ||||||
7906 | } | ||||||
7907 | } | ||||||
7908 | |||||||
7909 | return false; | ||||||
7910 | } | ||||||
7911 | }; | ||||||
7912 | |||||||
7913 | enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; | ||||||
7914 | } // end anonymous namespace | ||||||
7915 | |||||||
7916 | /// Report an error regarding overriding, along with any relevant | ||||||
7917 | /// overridden methods. | ||||||
7918 | /// | ||||||
7919 | /// \param DiagID the primary error to report. | ||||||
7920 | /// \param MD the overriding method. | ||||||
7921 | /// \param OEK which overrides to include as notes. | ||||||
7922 | static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, | ||||||
7923 | OverrideErrorKind OEK = OEK_All) { | ||||||
7924 | S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); | ||||||
7925 | for (const CXXMethodDecl *O : MD->overridden_methods()) { | ||||||
7926 | // This check (& the OEK parameter) could be replaced by a predicate, but | ||||||
7927 | // without lambdas that would be overkill. This is still nicer than writing | ||||||
7928 | // out the diag loop 3 times. | ||||||
7929 | if ((OEK == OEK_All) || | ||||||
7930 | (OEK == OEK_NonDeleted && !O->isDeleted()) || | ||||||
7931 | (OEK == OEK_Deleted && O->isDeleted())) | ||||||
7932 | S.Diag(O->getLocation(), diag::note_overridden_virtual_function); | ||||||
7933 | } | ||||||
7934 | } | ||||||
7935 | |||||||
7936 | /// AddOverriddenMethods - See if a method overrides any in the base classes, | ||||||
7937 | /// and if so, check that it's a valid override and remember it. | ||||||
7938 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { | ||||||
7939 | // Look for methods in base classes that this method might override. | ||||||
7940 | CXXBasePaths Paths; | ||||||
7941 | FindOverriddenMethod FOM; | ||||||
7942 | FOM.Method = MD; | ||||||
7943 | FOM.S = this; | ||||||
7944 | bool hasDeletedOverridenMethods = false; | ||||||
7945 | bool hasNonDeletedOverridenMethods = false; | ||||||
7946 | bool AddedAny = false; | ||||||
7947 | if (DC->lookupInBases(FOM, Paths)) { | ||||||
7948 | for (auto *I : Paths.found_decls()) { | ||||||
7949 | if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { | ||||||
7950 | MD->addOverriddenMethod(OldMD->getCanonicalDecl()); | ||||||
7951 | if (!CheckOverridingFunctionReturnType(MD, OldMD) && | ||||||
7952 | !CheckOverridingFunctionAttributes(MD, OldMD) && | ||||||
7953 | !CheckOverridingFunctionExceptionSpec(MD, OldMD) && | ||||||
7954 | !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { | ||||||
7955 | hasDeletedOverridenMethods |= OldMD->isDeleted(); | ||||||
7956 | hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); | ||||||
7957 | AddedAny = true; | ||||||
7958 | } | ||||||
7959 | } | ||||||
7960 | } | ||||||
7961 | } | ||||||
7962 | |||||||
7963 | if (hasDeletedOverridenMethods && !MD->isDeleted()) { | ||||||
7964 | ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); | ||||||
7965 | } | ||||||
7966 | if (hasNonDeletedOverridenMethods && MD->isDeleted()) { | ||||||
7967 | ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); | ||||||
7968 | } | ||||||
7969 | |||||||
7970 | return AddedAny; | ||||||
7971 | } | ||||||
7972 | |||||||
7973 | namespace { | ||||||
7974 | // Struct for holding all of the extra arguments needed by | ||||||
7975 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. | ||||||
7976 | struct ActOnFDArgs { | ||||||
7977 | Scope *S; | ||||||
7978 | Declarator &D; | ||||||
7979 | MultiTemplateParamsArg TemplateParamLists; | ||||||
7980 | bool AddToScope; | ||||||
7981 | }; | ||||||
7982 | } // end anonymous namespace | ||||||
7983 | |||||||
7984 | namespace { | ||||||
7985 | |||||||
7986 | // Callback to only accept typo corrections that have a non-zero edit distance. | ||||||
7987 | // Also only accept corrections that have the same parent decl. | ||||||
7988 | class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { | ||||||
7989 | public: | ||||||
7990 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, | ||||||
7991 | CXXRecordDecl *Parent) | ||||||
7992 | : Context(Context), OriginalFD(TypoFD), | ||||||
7993 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} | ||||||
7994 | |||||||
7995 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||
7996 | if (candidate.getEditDistance() == 0) | ||||||
7997 | return false; | ||||||
7998 | |||||||
7999 | SmallVector<unsigned, 1> MismatchedParams; | ||||||
8000 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), | ||||||
8001 | CDeclEnd = candidate.end(); | ||||||
8002 | CDecl != CDeclEnd; ++CDecl) { | ||||||
8003 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||||
8004 | |||||||
8005 | if (FD && !FD->hasBody() && | ||||||
8006 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { | ||||||
8007 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
8008 | CXXRecordDecl *Parent = MD->getParent(); | ||||||
8009 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) | ||||||
8010 | return true; | ||||||
8011 | } else if (!ExpectedParent) { | ||||||
8012 | return true; | ||||||
8013 | } | ||||||
8014 | } | ||||||
8015 | } | ||||||
8016 | |||||||
8017 | return false; | ||||||
8018 | } | ||||||
8019 | |||||||
8020 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||
8021 | return std::make_unique<DifferentNameValidatorCCC>(*this); | ||||||
8022 | } | ||||||
8023 | |||||||
8024 | private: | ||||||
8025 | ASTContext &Context; | ||||||
8026 | FunctionDecl *OriginalFD; | ||||||
8027 | CXXRecordDecl *ExpectedParent; | ||||||
8028 | }; | ||||||
8029 | |||||||
8030 | } // end anonymous namespace | ||||||
8031 | |||||||
8032 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { | ||||||
8033 | TypoCorrectedFunctionDefinitions.insert(F); | ||||||
8034 | } | ||||||
8035 | |||||||
8036 | /// Generate diagnostics for an invalid function redeclaration. | ||||||
8037 | /// | ||||||
8038 | /// This routine handles generating the diagnostic messages for an invalid | ||||||
8039 | /// function redeclaration, including finding possible similar declarations | ||||||
8040 | /// or performing typo correction if there are no previous declarations with | ||||||
8041 | /// the same name. | ||||||
8042 | /// | ||||||
8043 | /// Returns a NamedDecl iff typo correction was performed and substituting in | ||||||
8044 | /// the new declaration name does not cause new errors. | ||||||
8045 | static NamedDecl *DiagnoseInvalidRedeclaration( | ||||||
8046 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, | ||||||
8047 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { | ||||||
8048 | DeclarationName Name = NewFD->getDeclName(); | ||||||
8049 | DeclContext *NewDC = NewFD->getDeclContext(); | ||||||
8050 | SmallVector<unsigned, 1> MismatchedParams; | ||||||
8051 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; | ||||||
8052 | TypoCorrection Correction; | ||||||
8053 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); | ||||||
8054 | unsigned DiagMsg = | ||||||
8055 | IsLocalFriend ? diag::err_no_matching_local_friend : | ||||||
8056 | NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : | ||||||
8057 | diag::err_member_decl_does_not_match; | ||||||
8058 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), | ||||||
8059 | IsLocalFriend ? Sema::LookupLocalFriendName | ||||||
8060 | : Sema::LookupOrdinaryName, | ||||||
8061 | Sema::ForVisibleRedeclaration); | ||||||
8062 | |||||||
8063 | NewFD->setInvalidDecl(); | ||||||
8064 | if (IsLocalFriend) | ||||||
8065 | SemaRef.LookupName(Prev, S); | ||||||
8066 | else | ||||||
8067 | SemaRef.LookupQualifiedName(Prev, NewDC); | ||||||
8068 | assert(!Prev.isAmbiguous() &&((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8069, __PRETTY_FUNCTION__)) | ||||||
8069 | "Cannot have an ambiguity in previous-declaration lookup")((!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup" ) ? static_cast<void> (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8069, __PRETTY_FUNCTION__)); | ||||||
8070 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||||
8071 | DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, | ||||||
8072 | MD ? MD->getParent() : nullptr); | ||||||
8073 | if (!Prev.empty()) { | ||||||
8074 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); | ||||||
8075 | Func != FuncEnd; ++Func) { | ||||||
8076 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); | ||||||
8077 | if (FD && | ||||||
8078 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||||
8079 | // Add 1 to the index so that 0 can mean the mismatch didn't | ||||||
8080 | // involve a parameter | ||||||
8081 | unsigned ParamNum = | ||||||
8082 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; | ||||||
8083 | NearMatches.push_back(std::make_pair(FD, ParamNum)); | ||||||
8084 | } | ||||||
8085 | } | ||||||
8086 | // If the qualified name lookup yielded nothing, try typo correction | ||||||
8087 | } else if ((Correction = SemaRef.CorrectTypo( | ||||||
8088 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, | ||||||
8089 | &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, | ||||||
8090 | IsLocalFriend ? nullptr : NewDC))) { | ||||||
8091 | // Set up everything for the call to ActOnFunctionDeclarator | ||||||
8092 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), | ||||||
8093 | ExtraArgs.D.getIdentifierLoc()); | ||||||
8094 | Previous.clear(); | ||||||
8095 | Previous.setLookupName(Correction.getCorrection()); | ||||||
8096 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), | ||||||
8097 | CDeclEnd = Correction.end(); | ||||||
8098 | CDecl != CDeclEnd; ++CDecl) { | ||||||
8099 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||||
8100 | if (FD && !FD->hasBody() && | ||||||
8101 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||||
8102 | Previous.addDecl(FD); | ||||||
8103 | } | ||||||
8104 | } | ||||||
8105 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); | ||||||
8106 | |||||||
8107 | NamedDecl *Result; | ||||||
8108 | // Retry building the function declaration with the new previous | ||||||
8109 | // declarations, and with errors suppressed. | ||||||
8110 | { | ||||||
8111 | // Trap errors. | ||||||
8112 | Sema::SFINAETrap Trap(SemaRef); | ||||||
8113 | |||||||
8114 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the | ||||||
8115 | // pieces need to verify the typo-corrected C++ declaration and hopefully | ||||||
8116 | // eliminate the need for the parameter pack ExtraArgs. | ||||||
8117 | Result = SemaRef.ActOnFunctionDeclarator( | ||||||
8118 | ExtraArgs.S, ExtraArgs.D, | ||||||
8119 | Correction.getCorrectionDecl()->getDeclContext(), | ||||||
8120 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, | ||||||
8121 | ExtraArgs.AddToScope); | ||||||
8122 | |||||||
8123 | if (Trap.hasErrorOccurred()) | ||||||
8124 | Result = nullptr; | ||||||
8125 | } | ||||||
8126 | |||||||
8127 | if (Result) { | ||||||
8128 | // Determine which correction we picked. | ||||||
8129 | Decl *Canonical = Result->getCanonicalDecl(); | ||||||
8130 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||||
8131 | I != E; ++I) | ||||||
8132 | if ((*I)->getCanonicalDecl() == Canonical) | ||||||
8133 | Correction.setCorrectionDecl(*I); | ||||||
8134 | |||||||
8135 | // Let Sema know about the correction. | ||||||
8136 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); | ||||||
8137 | SemaRef.diagnoseTypo( | ||||||
8138 | Correction, | ||||||
8139 | SemaRef.PDiag(IsLocalFriend | ||||||
8140 | ? diag::err_no_matching_local_friend_suggest | ||||||
8141 | : diag::err_member_decl_does_not_match_suggest) | ||||||
8142 | << Name << NewDC << IsDefinition); | ||||||
8143 | return Result; | ||||||
8144 | } | ||||||
8145 | |||||||
8146 | // Pretend the typo correction never occurred | ||||||
8147 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), | ||||||
8148 | ExtraArgs.D.getIdentifierLoc()); | ||||||
8149 | ExtraArgs.D.setRedeclaration(wasRedeclaration); | ||||||
8150 | Previous.clear(); | ||||||
8151 | Previous.setLookupName(Name); | ||||||
8152 | } | ||||||
8153 | |||||||
8154 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) | ||||||
8155 | << Name << NewDC << IsDefinition << NewFD->getLocation(); | ||||||
8156 | |||||||
8157 | bool NewFDisConst = false; | ||||||
8158 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) | ||||||
8159 | NewFDisConst = NewMD->isConst(); | ||||||
8160 | |||||||
8161 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator | ||||||
8162 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); | ||||||
8163 | NearMatch != NearMatchEnd; ++NearMatch) { | ||||||
8164 | FunctionDecl *FD = NearMatch->first; | ||||||
8165 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||||
8166 | bool FDisConst = MD && MD->isConst(); | ||||||
8167 | bool IsMember = MD || !IsLocalFriend; | ||||||
8168 | |||||||
8169 | // FIXME: These notes are poorly worded for the local friend case. | ||||||
8170 | if (unsigned Idx = NearMatch->second) { | ||||||
8171 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); | ||||||
8172 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); | ||||||
8173 | if (Loc.isInvalid()) Loc = FD->getLocation(); | ||||||
8174 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match | ||||||
8175 | : diag::note_local_decl_close_param_match) | ||||||
8176 | << Idx << FDParam->getType() | ||||||
8177 | << NewFD->getParamDecl(Idx - 1)->getType(); | ||||||
8178 | } else if (FDisConst != NewFDisConst) { | ||||||
8179 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) | ||||||
8180 | << NewFDisConst << FD->getSourceRange().getEnd(); | ||||||
8181 | } else | ||||||
8182 | SemaRef.Diag(FD->getLocation(), | ||||||
8183 | IsMember ? diag::note_member_def_close_match | ||||||
8184 | : diag::note_local_decl_close_match); | ||||||
8185 | } | ||||||
8186 | return nullptr; | ||||||
8187 | } | ||||||
8188 | |||||||
8189 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { | ||||||
8190 | switch (D.getDeclSpec().getStorageClassSpec()) { | ||||||
8191 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8191); | ||||||
8192 | case DeclSpec::SCS_auto: | ||||||
8193 | case DeclSpec::SCS_register: | ||||||
8194 | case DeclSpec::SCS_mutable: | ||||||
8195 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
8196 | diag::err_typecheck_sclass_func); | ||||||
8197 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||||
8198 | D.setInvalidType(); | ||||||
8199 | break; | ||||||
8200 | case DeclSpec::SCS_unspecified: break; | ||||||
8201 | case DeclSpec::SCS_extern: | ||||||
8202 | if (D.getDeclSpec().isExternInLinkageSpec()) | ||||||
8203 | return SC_None; | ||||||
8204 | return SC_Extern; | ||||||
8205 | case DeclSpec::SCS_static: { | ||||||
8206 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { | ||||||
8207 | // C99 6.7.1p5: | ||||||
8208 | // The declaration of an identifier for a function that has | ||||||
8209 | // block scope shall have no explicit storage-class specifier | ||||||
8210 | // other than extern | ||||||
8211 | // See also (C++ [dcl.stc]p4). | ||||||
8212 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
8213 | diag::err_static_block_func); | ||||||
8214 | break; | ||||||
8215 | } else | ||||||
8216 | return SC_Static; | ||||||
8217 | } | ||||||
8218 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||||
8219 | } | ||||||
8220 | |||||||
8221 | // No explicit storage class has already been returned | ||||||
8222 | return SC_None; | ||||||
8223 | } | ||||||
8224 | |||||||
8225 | static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, | ||||||
8226 | DeclContext *DC, QualType &R, | ||||||
8227 | TypeSourceInfo *TInfo, | ||||||
8228 | StorageClass SC, | ||||||
8229 | bool &IsVirtualOkay) { | ||||||
8230 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); | ||||||
8231 | DeclarationName Name = NameInfo.getName(); | ||||||
8232 | |||||||
8233 | FunctionDecl *NewFD = nullptr; | ||||||
8234 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||||
8235 | |||||||
8236 | if (!SemaRef.getLangOpts().CPlusPlus) { | ||||||
8237 | // Determine whether the function was written with a | ||||||
8238 | // prototype. This true when: | ||||||
8239 | // - there is a prototype in the declarator, or | ||||||
8240 | // - the type R of the function is some kind of typedef or other non- | ||||||
8241 | // attributed reference to a type name (which eventually refers to a | ||||||
8242 | // function type). | ||||||
8243 | bool HasPrototype = | ||||||
8244 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || | ||||||
8245 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); | ||||||
8246 | |||||||
8247 | NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | ||||||
8248 | R, TInfo, SC, isInline, HasPrototype, | ||||||
8249 | CSK_unspecified, | ||||||
8250 | /*TrailingRequiresClause=*/nullptr); | ||||||
8251 | if (D.isInvalidType()) | ||||||
8252 | NewFD->setInvalidDecl(); | ||||||
8253 | |||||||
8254 | return NewFD; | ||||||
8255 | } | ||||||
8256 | |||||||
8257 | ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); | ||||||
8258 | |||||||
8259 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); | ||||||
8260 | if (ConstexprKind == CSK_constinit) { | ||||||
8261 | SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
8262 | diag::err_constexpr_wrong_decl_kind) | ||||||
8263 | << ConstexprKind; | ||||||
8264 | ConstexprKind = CSK_unspecified; | ||||||
8265 | D.getMutableDeclSpec().ClearConstexprSpec(); | ||||||
8266 | } | ||||||
8267 | Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); | ||||||
8268 | |||||||
8269 | // Check that the return type is not an abstract class type. | ||||||
8270 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||||
8271 | // the class has been completely parsed. | ||||||
8272 | if (!DC->isRecord() && | ||||||
8273 | SemaRef.RequireNonAbstractType( | ||||||
8274 | D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), | ||||||
8275 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) | ||||||
8276 | D.setInvalidType(); | ||||||
8277 | |||||||
8278 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { | ||||||
8279 | // This is a C++ constructor declaration. | ||||||
8280 | assert(DC->isRecord() &&((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8281, __PRETTY_FUNCTION__)) | ||||||
8281 | "Constructors can only be declared in a member context")((DC->isRecord() && "Constructors can only be declared in a member context" ) ? static_cast<void> (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8281, __PRETTY_FUNCTION__)); | ||||||
8282 | |||||||
8283 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); | ||||||
8284 | return CXXConstructorDecl::Create( | ||||||
8285 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8286 | TInfo, ExplicitSpecifier, isInline, | ||||||
8287 | /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), | ||||||
8288 | TrailingRequiresClause); | ||||||
8289 | |||||||
8290 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
8291 | // This is a C++ destructor declaration. | ||||||
8292 | if (DC->isRecord()) { | ||||||
8293 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); | ||||||
8294 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); | ||||||
8295 | CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( | ||||||
8296 | SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, | ||||||
8297 | isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, | ||||||
8298 | TrailingRequiresClause); | ||||||
8299 | |||||||
8300 | // If the destructor needs an implicit exception specification, set it | ||||||
8301 | // now. FIXME: It'd be nice to be able to create the right type to start | ||||||
8302 | // with, but the type needs to reference the destructor declaration. | ||||||
8303 | if (SemaRef.getLangOpts().CPlusPlus11) | ||||||
8304 | SemaRef.AdjustDestructorExceptionSpec(NewDD); | ||||||
8305 | |||||||
8306 | IsVirtualOkay = true; | ||||||
8307 | return NewDD; | ||||||
8308 | |||||||
8309 | } else { | ||||||
8310 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); | ||||||
8311 | D.setInvalidType(); | ||||||
8312 | |||||||
8313 | // Create a FunctionDecl to satisfy the function definition parsing | ||||||
8314 | // code path. | ||||||
8315 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||||
8316 | D.getIdentifierLoc(), Name, R, TInfo, SC, | ||||||
8317 | isInline, | ||||||
8318 | /*hasPrototype=*/true, ConstexprKind, | ||||||
8319 | TrailingRequiresClause); | ||||||
8320 | } | ||||||
8321 | |||||||
8322 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||||
8323 | if (!DC->isRecord()) { | ||||||
8324 | SemaRef.Diag(D.getIdentifierLoc(), | ||||||
8325 | diag::err_conv_function_not_member); | ||||||
8326 | return nullptr; | ||||||
8327 | } | ||||||
8328 | |||||||
8329 | SemaRef.CheckConversionDeclarator(D, R, SC); | ||||||
8330 | if (D.isInvalidType()) | ||||||
8331 | return nullptr; | ||||||
8332 | |||||||
8333 | IsVirtualOkay = true; | ||||||
8334 | return CXXConversionDecl::Create( | ||||||
8335 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8336 | TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), | ||||||
8337 | TrailingRequiresClause); | ||||||
8338 | |||||||
8339 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { | ||||||
8340 | if (TrailingRequiresClause) | ||||||
8341 | SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), | ||||||
8342 | diag::err_trailing_requires_clause_on_deduction_guide) | ||||||
8343 | << TrailingRequiresClause->getSourceRange(); | ||||||
8344 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); | ||||||
8345 | |||||||
8346 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||||
8347 | ExplicitSpecifier, NameInfo, R, TInfo, | ||||||
8348 | D.getEndLoc()); | ||||||
8349 | } else if (DC->isRecord()) { | ||||||
8350 | // If the name of the function is the same as the name of the record, | ||||||
8351 | // then this must be an invalid constructor that has a return type. | ||||||
8352 | // (The parser checks for a return type and makes the declarator a | ||||||
8353 | // constructor if it has no return type). | ||||||
8354 | if (Name.getAsIdentifierInfo() && | ||||||
8355 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ | ||||||
8356 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) | ||||||
8357 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | ||||||
8358 | << SourceRange(D.getIdentifierLoc()); | ||||||
8359 | return nullptr; | ||||||
8360 | } | ||||||
8361 | |||||||
8362 | // This is a C++ method declaration. | ||||||
8363 | CXXMethodDecl *Ret = CXXMethodDecl::Create( | ||||||
8364 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8365 | TInfo, SC, isInline, ConstexprKind, SourceLocation(), | ||||||
8366 | TrailingRequiresClause); | ||||||
8367 | IsVirtualOkay = !Ret->isStatic(); | ||||||
8368 | return Ret; | ||||||
8369 | } else { | ||||||
8370 | bool isFriend = | ||||||
8371 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); | ||||||
8372 | if (!isFriend && SemaRef.CurContext->isRecord()) | ||||||
8373 | return nullptr; | ||||||
8374 | |||||||
8375 | // Determine whether the function was written with a | ||||||
8376 | // prototype. This true when: | ||||||
8377 | // - we're in C++ (where every function has a prototype), | ||||||
8378 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | ||||||
8379 | R, TInfo, SC, isInline, true /*HasPrototype*/, | ||||||
8380 | ConstexprKind, TrailingRequiresClause); | ||||||
8381 | } | ||||||
8382 | } | ||||||
8383 | |||||||
8384 | enum OpenCLParamType { | ||||||
8385 | ValidKernelParam, | ||||||
8386 | PtrPtrKernelParam, | ||||||
8387 | PtrKernelParam, | ||||||
8388 | InvalidAddrSpacePtrKernelParam, | ||||||
8389 | InvalidKernelParam, | ||||||
8390 | RecordKernelParam | ||||||
8391 | }; | ||||||
8392 | |||||||
8393 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { | ||||||
8394 | // Size dependent types are just typedefs to normal integer types | ||||||
8395 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to | ||||||
8396 | // integers other than by their names. | ||||||
8397 | StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; | ||||||
8398 | |||||||
8399 | // Remove typedefs one by one until we reach a typedef | ||||||
8400 | // for a size dependent type. | ||||||
8401 | QualType DesugaredTy = Ty; | ||||||
8402 | do { | ||||||
8403 | ArrayRef<StringRef> Names(SizeTypeNames); | ||||||
8404 | auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); | ||||||
8405 | if (Names.end() != Match) | ||||||
8406 | return true; | ||||||
8407 | |||||||
8408 | Ty = DesugaredTy; | ||||||
8409 | DesugaredTy = Ty.getSingleStepDesugaredType(C); | ||||||
8410 | } while (DesugaredTy != Ty); | ||||||
8411 | |||||||
8412 | return false; | ||||||
8413 | } | ||||||
8414 | |||||||
8415 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { | ||||||
8416 | if (PT->isPointerType()) { | ||||||
8417 | QualType PointeeType = PT->getPointeeType(); | ||||||
8418 | if (PointeeType->isPointerType()) | ||||||
8419 | return PtrPtrKernelParam; | ||||||
8420 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || | ||||||
8421 | PointeeType.getAddressSpace() == LangAS::opencl_private || | ||||||
8422 | PointeeType.getAddressSpace() == LangAS::Default) | ||||||
8423 | return InvalidAddrSpacePtrKernelParam; | ||||||
8424 | return PtrKernelParam; | ||||||
8425 | } | ||||||
8426 | |||||||
8427 | // OpenCL v1.2 s6.9.k: | ||||||
8428 | // Arguments to kernel functions in a program cannot be declared with the | ||||||
8429 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||||
8430 | // uintptr_t or a struct and/or union that contain fields declared to be one | ||||||
8431 | // of these built-in scalar types. | ||||||
8432 | if (isOpenCLSizeDependentType(S.getASTContext(), PT)) | ||||||
8433 | return InvalidKernelParam; | ||||||
8434 | |||||||
8435 | if (PT->isImageType()) | ||||||
8436 | return PtrKernelParam; | ||||||
8437 | |||||||
8438 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) | ||||||
8439 | return InvalidKernelParam; | ||||||
8440 | |||||||
8441 | // OpenCL extension spec v1.2 s9.5: | ||||||
8442 | // This extension adds support for half scalar and vector types as built-in | ||||||
8443 | // types that can be used for arithmetic operations, conversions etc. | ||||||
8444 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) | ||||||
8445 | return InvalidKernelParam; | ||||||
8446 | |||||||
8447 | if (PT->isRecordType()) | ||||||
8448 | return RecordKernelParam; | ||||||
8449 | |||||||
8450 | // Look into an array argument to check if it has a forbidden type. | ||||||
8451 | if (PT->isArrayType()) { | ||||||
8452 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); | ||||||
8453 | // Call ourself to check an underlying type of an array. Since the | ||||||
8454 | // getPointeeOrArrayElementType returns an innermost type which is not an | ||||||
8455 | // array, this recursive call only happens once. | ||||||
8456 | return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); | ||||||
8457 | } | ||||||
8458 | |||||||
8459 | return ValidKernelParam; | ||||||
8460 | } | ||||||
8461 | |||||||
8462 | static void checkIsValidOpenCLKernelParameter( | ||||||
8463 | Sema &S, | ||||||
8464 | Declarator &D, | ||||||
8465 | ParmVarDecl *Param, | ||||||
8466 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { | ||||||
8467 | QualType PT = Param->getType(); | ||||||
8468 | |||||||
8469 | // Cache the valid types we encounter to avoid rechecking structs that are | ||||||
8470 | // used again | ||||||
8471 | if (ValidTypes.count(PT.getTypePtr())) | ||||||
8472 | return; | ||||||
8473 | |||||||
8474 | switch (getOpenCLKernelParameterType(S, PT)) { | ||||||
8475 | case PtrPtrKernelParam: | ||||||
8476 | // OpenCL v1.2 s6.9.a: | ||||||
8477 | // A kernel function argument cannot be declared as a | ||||||
8478 | // pointer to a pointer type. | ||||||
8479 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); | ||||||
8480 | D.setInvalidType(); | ||||||
8481 | return; | ||||||
8482 | |||||||
8483 | case InvalidAddrSpacePtrKernelParam: | ||||||
8484 | // OpenCL v1.0 s6.5: | ||||||
8485 | // __kernel function arguments declared to be a pointer of a type can point | ||||||
8486 | // to one of the following address spaces only : __global, __local or | ||||||
8487 | // __constant. | ||||||
8488 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); | ||||||
8489 | D.setInvalidType(); | ||||||
8490 | return; | ||||||
8491 | |||||||
8492 | // OpenCL v1.2 s6.9.k: | ||||||
8493 | // Arguments to kernel functions in a program cannot be declared with the | ||||||
8494 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||||
8495 | // uintptr_t or a struct and/or union that contain fields declared to be | ||||||
8496 | // one of these built-in scalar types. | ||||||
8497 | |||||||
8498 | case InvalidKernelParam: | ||||||
8499 | // OpenCL v1.2 s6.8 n: | ||||||
8500 | // A kernel function argument cannot be declared | ||||||
8501 | // of event_t type. | ||||||
8502 | // Do not diagnose half type since it is diagnosed as invalid argument | ||||||
8503 | // type for any function elsewhere. | ||||||
8504 | if (!PT->isHalfType()) { | ||||||
8505 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||||
8506 | |||||||
8507 | // Explain what typedefs are involved. | ||||||
8508 | const TypedefType *Typedef = nullptr; | ||||||
8509 | while ((Typedef = PT->getAs<TypedefType>())) { | ||||||
8510 | SourceLocation Loc = Typedef->getDecl()->getLocation(); | ||||||
8511 | // SourceLocation may be invalid for a built-in type. | ||||||
8512 | if (Loc.isValid()) | ||||||
8513 | S.Diag(Loc, diag::note_entity_declared_at) << PT; | ||||||
8514 | PT = Typedef->desugar(); | ||||||
8515 | } | ||||||
8516 | } | ||||||
8517 | |||||||
8518 | D.setInvalidType(); | ||||||
8519 | return; | ||||||
8520 | |||||||
8521 | case PtrKernelParam: | ||||||
8522 | case ValidKernelParam: | ||||||
8523 | ValidTypes.insert(PT.getTypePtr()); | ||||||
8524 | return; | ||||||
8525 | |||||||
8526 | case RecordKernelParam: | ||||||
8527 | break; | ||||||
8528 | } | ||||||
8529 | |||||||
8530 | // Track nested structs we will inspect | ||||||
8531 | SmallVector<const Decl *, 4> VisitStack; | ||||||
8532 | |||||||
8533 | // Track where we are in the nested structs. Items will migrate from | ||||||
8534 | // VisitStack to HistoryStack as we do the DFS for bad field. | ||||||
8535 | SmallVector<const FieldDecl *, 4> HistoryStack; | ||||||
8536 | HistoryStack.push_back(nullptr); | ||||||
8537 | |||||||
8538 | // At this point we already handled everything except of a RecordType or | ||||||
8539 | // an ArrayType of a RecordType. | ||||||
8540 | assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")(((PT->isArrayType() || PT->isRecordType()) && "Unexpected type." ) ? static_cast<void> (0) : __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8540, __PRETTY_FUNCTION__)); | ||||||
8541 | const RecordType *RecTy = | ||||||
8542 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); | ||||||
8543 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); | ||||||
8544 | |||||||
8545 | VisitStack.push_back(RecTy->getDecl()); | ||||||
8546 | assert(VisitStack.back() && "First decl null?")((VisitStack.back() && "First decl null?") ? static_cast <void> (0) : __assert_fail ("VisitStack.back() && \"First decl null?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8546, __PRETTY_FUNCTION__)); | ||||||
8547 | |||||||
8548 | do { | ||||||
8549 | const Decl *Next = VisitStack.pop_back_val(); | ||||||
8550 | if (!Next) { | ||||||
8551 | assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8551, __PRETTY_FUNCTION__)); | ||||||
8552 | // Found a marker, we have gone up a level | ||||||
8553 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) | ||||||
8554 | ValidTypes.insert(Hist->getType().getTypePtr()); | ||||||
8555 | |||||||
8556 | continue; | ||||||
8557 | } | ||||||
8558 | |||||||
8559 | // Adds everything except the original parameter declaration (which is not a | ||||||
8560 | // field itself) to the history stack. | ||||||
8561 | const RecordDecl *RD; | ||||||
8562 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { | ||||||
8563 | HistoryStack.push_back(Field); | ||||||
8564 | |||||||
8565 | QualType FieldTy = Field->getType(); | ||||||
8566 | // Other field types (known to be valid or invalid) are handled while we | ||||||
8567 | // walk around RecordDecl::fields(). | ||||||
8568 | assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8569, __PRETTY_FUNCTION__)) | ||||||
8569 | "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8569, __PRETTY_FUNCTION__)); | ||||||
8570 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); | ||||||
8571 | |||||||
8572 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); | ||||||
8573 | } else { | ||||||
8574 | RD = cast<RecordDecl>(Next); | ||||||
8575 | } | ||||||
8576 | |||||||
8577 | // Add a null marker so we know when we've gone back up a level | ||||||
8578 | VisitStack.push_back(nullptr); | ||||||
8579 | |||||||
8580 | for (const auto *FD : RD->fields()) { | ||||||
8581 | QualType QT = FD->getType(); | ||||||
8582 | |||||||
8583 | if (ValidTypes.count(QT.getTypePtr())) | ||||||
8584 | continue; | ||||||
8585 | |||||||
8586 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); | ||||||
8587 | if (ParamType == ValidKernelParam) | ||||||
8588 | continue; | ||||||
8589 | |||||||
8590 | if (ParamType == RecordKernelParam) { | ||||||
8591 | VisitStack.push_back(FD); | ||||||
8592 | continue; | ||||||
8593 | } | ||||||
8594 | |||||||
8595 | // OpenCL v1.2 s6.9.p: | ||||||
8596 | // Arguments to kernel functions that are declared to be a struct or union | ||||||
8597 | // do not allow OpenCL objects to be passed as elements of the struct or | ||||||
8598 | // union. | ||||||
8599 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || | ||||||
8600 | ParamType == InvalidAddrSpacePtrKernelParam) { | ||||||
8601 | S.Diag(Param->getLocation(), | ||||||
8602 | diag::err_record_with_pointers_kernel_param) | ||||||
8603 | << PT->isUnionType() | ||||||
8604 | << PT; | ||||||
8605 | } else { | ||||||
8606 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||||
8607 | } | ||||||
8608 | |||||||
8609 | S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) | ||||||
8610 | << OrigRecDecl->getDeclName(); | ||||||
8611 | |||||||
8612 | // We have an error, now let's go back up through history and show where | ||||||
8613 | // the offending field came from | ||||||
8614 | for (ArrayRef<const FieldDecl *>::const_iterator | ||||||
8615 | I = HistoryStack.begin() + 1, | ||||||
8616 | E = HistoryStack.end(); | ||||||
8617 | I != E; ++I) { | ||||||
8618 | const FieldDecl *OuterField = *I; | ||||||
8619 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) | ||||||
8620 | << OuterField->getType(); | ||||||
8621 | } | ||||||
8622 | |||||||
8623 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) | ||||||
8624 | << QT->isPointerType() | ||||||
8625 | << QT; | ||||||
8626 | D.setInvalidType(); | ||||||
8627 | return; | ||||||
8628 | } | ||||||
8629 | } while (!VisitStack.empty()); | ||||||
8630 | } | ||||||
8631 | |||||||
8632 | /// Find the DeclContext in which a tag is implicitly declared if we see an | ||||||
8633 | /// elaborated type specifier in the specified context, and lookup finds | ||||||
8634 | /// nothing. | ||||||
8635 | static DeclContext *getTagInjectionContext(DeclContext *DC) { | ||||||
8636 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) | ||||||
8637 | DC = DC->getParent(); | ||||||
8638 | return DC; | ||||||
8639 | } | ||||||
8640 | |||||||
8641 | /// Find the Scope in which a tag is implicitly declared if we see an | ||||||
8642 | /// elaborated type specifier in the specified context, and lookup finds | ||||||
8643 | /// nothing. | ||||||
8644 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { | ||||||
8645 | while (S->isClassScope() || | ||||||
8646 | (LangOpts.CPlusPlus && | ||||||
8647 | S->isFunctionPrototypeScope()) || | ||||||
8648 | ((S->getFlags() & Scope::DeclScope) == 0) || | ||||||
8649 | (S->getEntity() && S->getEntity()->isTransparentContext())) | ||||||
8650 | S = S->getParent(); | ||||||
8651 | return S; | ||||||
8652 | } | ||||||
8653 | |||||||
8654 | NamedDecl* | ||||||
8655 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, | ||||||
8656 | TypeSourceInfo *TInfo, LookupResult &Previous, | ||||||
8657 | MultiTemplateParamsArg TemplateParamLists, | ||||||
8658 | bool &AddToScope) { | ||||||
8659 | QualType R = TInfo->getType(); | ||||||
8660 | |||||||
8661 | assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 8661, __PRETTY_FUNCTION__)); | ||||||
8662 | |||||||
8663 | // TODO: consider using NameInfo for diagnostic. | ||||||
8664 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||||
8665 | DeclarationName Name = NameInfo.getName(); | ||||||
8666 | StorageClass SC = getFunctionStorageClass(*this, D); | ||||||
8667 | |||||||
8668 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||||
8669 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
8670 | diag::err_invalid_thread) | ||||||
8671 | << DeclSpec::getSpecifierName(TSCS); | ||||||
8672 | |||||||
8673 | if (D.isFirstDeclarationOfMember()) | ||||||
8674 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), | ||||||
8675 | D.getIdentifierLoc()); | ||||||
8676 | |||||||
8677 | bool isFriend = false; | ||||||
8678 | FunctionTemplateDecl *FunctionTemplate = nullptr; | ||||||
8679 | bool isMemberSpecialization = false; | ||||||
8680 | bool isFunctionTemplateSpecialization = false; | ||||||
8681 | |||||||
8682 | bool isDependentClassScopeExplicitSpecialization = false; | ||||||
8683 | bool HasExplicitTemplateArgs = false; | ||||||
8684 | TemplateArgumentListInfo TemplateArgs; | ||||||
8685 | |||||||
8686 | bool isVirtualOkay = false; | ||||||
8687 | |||||||
8688 | DeclContext *OriginalDC = DC; | ||||||
8689 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); | ||||||
8690 | |||||||
8691 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, | ||||||
8692 | isVirtualOkay); | ||||||
8693 | if (!NewFD) return nullptr; | ||||||
8694 | |||||||
8695 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) | ||||||
8696 | NewFD->setTopLevelDeclInObjCContainer(); | ||||||
8697 | |||||||
8698 | // Set the lexical context. If this is a function-scope declaration, or has a | ||||||
8699 | // C++ scope specifier, or is the object of a friend declaration, the lexical | ||||||
8700 | // context will be different from the semantic context. | ||||||
8701 | NewFD->setLexicalDeclContext(CurContext); | ||||||
8702 | |||||||
8703 | if (IsLocalExternDecl) | ||||||
8704 | NewFD->setLocalExternDecl(); | ||||||
8705 | |||||||
8706 | if (getLangOpts().CPlusPlus) { | ||||||
8707 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||||
8708 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | ||||||
8709 | bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); | ||||||
8710 | isFriend = D.getDeclSpec().isFriendSpecified(); | ||||||
8711 | if (isFriend && !isInline && D.isFunctionDefinition()) { | ||||||
8712 | // C++ [class.friend]p5 | ||||||
8713 | // A function can be defined in a friend declaration of a | ||||||
8714 | // class . . . . Such a function is implicitly inline. | ||||||
8715 | NewFD->setImplicitlyInline(); | ||||||
8716 | } | ||||||
8717 | |||||||
8718 | // If this is a method defined in an __interface, and is not a constructor | ||||||
8719 | // or an overloaded operator, then set the pure flag (isVirtual will already | ||||||
8720 | // return true). | ||||||
8721 | if (const CXXRecordDecl *Parent = | ||||||
8722 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { | ||||||
8723 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) | ||||||
8724 | NewFD->setPure(true); | ||||||
8725 | |||||||
8726 | // C++ [class.union]p2 | ||||||
8727 | // A union can have member functions, but not virtual functions. | ||||||
8728 | if (isVirtual && Parent->isUnion()) | ||||||
8729 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); | ||||||
8730 | } | ||||||
8731 | |||||||
8732 | SetNestedNameSpecifier(*this, NewFD, D); | ||||||
8733 | isMemberSpecialization = false; | ||||||
8734 | isFunctionTemplateSpecialization = false; | ||||||
8735 | if (D.isInvalidType()) | ||||||
8736 | NewFD->setInvalidDecl(); | ||||||
8737 | |||||||
8738 | // Match up the template parameter lists with the scope specifier, then | ||||||
8739 | // determine whether we have a template or a template specialization. | ||||||
8740 | bool Invalid = false; | ||||||
8741 | if (TemplateParameterList *TemplateParams = | ||||||
8742 | MatchTemplateParametersToScopeSpecifier( | ||||||
8743 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||||
8744 | D.getCXXScopeSpec(), | ||||||
8745 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||||
8746 | ? D.getName().TemplateId | ||||||
8747 | : nullptr, | ||||||
8748 | TemplateParamLists, isFriend, isMemberSpecialization, | ||||||
8749 | Invalid)) { | ||||||
8750 | if (TemplateParams->size() > 0) { | ||||||
8751 | // This is a function template | ||||||
8752 | |||||||
8753 | // Check that we can declare a template here. | ||||||
8754 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||||
8755 | NewFD->setInvalidDecl(); | ||||||
8756 | |||||||
8757 | // A destructor cannot be a template. | ||||||
8758 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
8759 | Diag(NewFD->getLocation(), diag::err_destructor_template); | ||||||
8760 | NewFD->setInvalidDecl(); | ||||||
8761 | } | ||||||
8762 | |||||||
8763 | // If we're adding a template to a dependent context, we may need to | ||||||
8764 | // rebuilding some of the types used within the template parameter list, | ||||||
8765 | // now that we know what the current instantiation is. | ||||||
8766 | if (DC->isDependentContext()) { | ||||||
8767 | ContextRAII SavedContext(*this, DC); | ||||||
8768 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) | ||||||
8769 | Invalid = true; | ||||||
8770 | } | ||||||
8771 | |||||||
8772 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, | ||||||
8773 | NewFD->getLocation(), | ||||||
8774 | Name, TemplateParams, | ||||||
8775 | NewFD); | ||||||
8776 | FunctionTemplate->setLexicalDeclContext(CurContext); | ||||||
8777 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); | ||||||
8778 | |||||||
8779 | // For source fidelity, store the other template param lists. | ||||||
8780 | if (TemplateParamLists.size() > 1) { | ||||||
8781 | NewFD->setTemplateParameterListsInfo(Context, | ||||||
8782 | TemplateParamLists.drop_back(1)); | ||||||
8783 | } | ||||||
8784 | } else { | ||||||
8785 | // This is a function template specialization. | ||||||
8786 | isFunctionTemplateSpecialization = true; | ||||||
8787 | // For source fidelity, store all the template param lists. | ||||||
8788 | if (TemplateParamLists.size() > 0) | ||||||
8789 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||||
8790 | |||||||
8791 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". | ||||||
8792 | if (isFriend) { | ||||||
8793 | // We want to remove the "template<>", found here. | ||||||
8794 | SourceRange RemoveRange = TemplateParams->getSourceRange(); | ||||||
8795 | |||||||
8796 | // If we remove the template<> and the name is not a | ||||||
8797 | // template-id, we're actually silently creating a problem: | ||||||
8798 | // the friend declaration will refer to an untemplated decl, | ||||||
8799 | // and clearly the user wants a template specialization. So | ||||||
8800 | // we need to insert '<>' after the name. | ||||||
8801 | SourceLocation InsertLoc; | ||||||
8802 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||||
8803 | InsertLoc = D.getName().getSourceRange().getEnd(); | ||||||
8804 | InsertLoc = getLocForEndOfToken(InsertLoc); | ||||||
8805 | } | ||||||
8806 | |||||||
8807 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) | ||||||
8808 | << Name << RemoveRange | ||||||
8809 | << FixItHint::CreateRemoval(RemoveRange) | ||||||
8810 | << FixItHint::CreateInsertion(InsertLoc, "<>"); | ||||||
8811 | } | ||||||
8812 | } | ||||||
8813 | } else { | ||||||
8814 | // All template param lists were matched against the scope specifier: | ||||||
8815 | // this is NOT (an explicit specialization of) a template. | ||||||
8816 | if (TemplateParamLists.size() > 0) | ||||||
8817 | // For source fidelity, store all the template param lists. | ||||||
8818 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||||
8819 | } | ||||||
8820 | |||||||
8821 | if (Invalid) { | ||||||
8822 | NewFD->setInvalidDecl(); | ||||||
8823 | if (FunctionTemplate) | ||||||
8824 | FunctionTemplate->setInvalidDecl(); | ||||||
8825 | } | ||||||
8826 | |||||||
8827 | // C++ [dcl.fct.spec]p5: | ||||||
8828 | // The virtual specifier shall only be used in declarations of | ||||||
8829 | // nonstatic class member functions that appear within a | ||||||
8830 | // member-specification of a class declaration; see 10.3. | ||||||
8831 | // | ||||||
8832 | if (isVirtual && !NewFD->isInvalidDecl()) { | ||||||
8833 | if (!isVirtualOkay) { | ||||||
8834 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
8835 | diag::err_virtual_non_function); | ||||||
8836 | } else if (!CurContext->isRecord()) { | ||||||
8837 | // 'virtual' was specified outside of the class. | ||||||
8838 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
8839 | diag::err_virtual_out_of_class) | ||||||
8840 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||||
8841 | } else if (NewFD->getDescribedFunctionTemplate()) { | ||||||
8842 | // C++ [temp.mem]p3: | ||||||
8843 | // A member function template shall not be virtual. | ||||||
8844 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
8845 | diag::err_virtual_member_function_template) | ||||||
8846 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||||
8847 | } else { | ||||||
8848 | // Okay: Add virtual to the method. | ||||||
8849 | NewFD->setVirtualAsWritten(true); | ||||||
8850 | } | ||||||
8851 | |||||||
8852 | if (getLangOpts().CPlusPlus14 && | ||||||
8853 | NewFD->getReturnType()->isUndeducedType()) | ||||||
8854 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); | ||||||
8855 | } | ||||||
8856 | |||||||
8857 | if (getLangOpts().CPlusPlus14 && | ||||||
8858 | (NewFD->isDependentContext() || | ||||||
8859 | (isFriend && CurContext->isDependentContext())) && | ||||||
8860 | NewFD->getReturnType()->isUndeducedType()) { | ||||||
8861 | // If the function template is referenced directly (for instance, as a | ||||||
8862 | // member of the current instantiation), pretend it has a dependent type. | ||||||
8863 | // This is not really justified by the standard, but is the only sane | ||||||
8864 | // thing to do. | ||||||
8865 | // FIXME: For a friend function, we have not marked the function as being | ||||||
8866 | // a friend yet, so 'isDependentContext' on the FD doesn't work. | ||||||
8867 | const FunctionProtoType *FPT = | ||||||
8868 | NewFD->getType()->castAs<FunctionProtoType>(); | ||||||
8869 | QualType Result = | ||||||
8870 | SubstAutoType(FPT->getReturnType(), Context.DependentTy); | ||||||
8871 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), | ||||||
8872 | FPT->getExtProtoInfo())); | ||||||
8873 | } | ||||||
8874 | |||||||
8875 | // C++ [dcl.fct.spec]p3: | ||||||
8876 | // The inline specifier shall not appear on a block scope function | ||||||
8877 | // declaration. | ||||||
8878 | if (isInline && !NewFD->isInvalidDecl()) { | ||||||
8879 | if (CurContext->isFunctionOrMethod()) { | ||||||
8880 | // 'inline' is not allowed on block scope function declaration. | ||||||
8881 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
8882 | diag::err_inline_declaration_block_scope) << Name | ||||||
8883 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||||
8884 | } | ||||||
8885 | } | ||||||
8886 | |||||||
8887 | // C++ [dcl.fct.spec]p6: | ||||||
8888 | // The explicit specifier shall be used only in the declaration of a | ||||||
8889 | // constructor or conversion function within its class definition; | ||||||
8890 | // see 12.3.1 and 12.3.2. | ||||||
8891 | if (hasExplicit && !NewFD->isInvalidDecl() && | ||||||
8892 | !isa<CXXDeductionGuideDecl>(NewFD)) { | ||||||
8893 | if (!CurContext->isRecord()) { | ||||||
8894 | // 'explicit' was specified outside of the class. | ||||||
8895 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||||
8896 | diag::err_explicit_out_of_class) | ||||||
8897 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||||
8898 | } else if (!isa<CXXConstructorDecl>(NewFD) && | ||||||
8899 | !isa<CXXConversionDecl>(NewFD)) { | ||||||
8900 | // 'explicit' was specified on a function that wasn't a constructor | ||||||
8901 | // or conversion function. | ||||||
8902 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||||
8903 | diag::err_explicit_non_ctor_or_conv_function) | ||||||
8904 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||||
8905 | } | ||||||
8906 | } | ||||||
8907 | |||||||
8908 | if (ConstexprSpecKind ConstexprKind = | ||||||
8909 | D.getDeclSpec().getConstexprSpecifier()) { | ||||||
8910 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors | ||||||
8911 | // are implicitly inline. | ||||||
8912 | NewFD->setImplicitlyInline(); | ||||||
8913 | |||||||
8914 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to | ||||||
8915 | // be either constructors or to return a literal type. Therefore, | ||||||
8916 | // destructors cannot be declared constexpr. | ||||||
8917 | if (isa<CXXDestructorDecl>(NewFD) && !getLangOpts().CPlusPlus2a) { | ||||||
8918 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) | ||||||
8919 | << ConstexprKind; | ||||||
8920 | } | ||||||
8921 | } | ||||||
8922 | |||||||
8923 | // If __module_private__ was specified, mark the function accordingly. | ||||||
8924 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
8925 | if (isFunctionTemplateSpecialization) { | ||||||
8926 | SourceLocation ModulePrivateLoc | ||||||
8927 | = D.getDeclSpec().getModulePrivateSpecLoc(); | ||||||
8928 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) | ||||||
8929 | << 0 | ||||||
8930 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||||
8931 | } else { | ||||||
8932 | NewFD->setModulePrivate(); | ||||||
8933 | if (FunctionTemplate) | ||||||
8934 | FunctionTemplate->setModulePrivate(); | ||||||
8935 | } | ||||||
8936 | } | ||||||
8937 | |||||||
8938 | if (isFriend) { | ||||||
8939 | if (FunctionTemplate) { | ||||||
8940 | FunctionTemplate->setObjectOfFriendDecl(); | ||||||
8941 | FunctionTemplate->setAccess(AS_public); | ||||||
8942 | } | ||||||
8943 | NewFD->setObjectOfFriendDecl(); | ||||||
8944 | NewFD->setAccess(AS_public); | ||||||
8945 | } | ||||||
8946 | |||||||
8947 | // If a function is defined as defaulted or deleted, mark it as such now. | ||||||
8948 | // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function | ||||||
8949 | // definition kind to FDK_Definition. | ||||||
8950 | switch (D.getFunctionDefinitionKind()) { | ||||||
8951 | case FDK_Declaration: | ||||||
8952 | case FDK_Definition: | ||||||
8953 | break; | ||||||
8954 | |||||||
8955 | case FDK_Defaulted: | ||||||
8956 | NewFD->setDefaulted(); | ||||||
8957 | break; | ||||||
8958 | |||||||
8959 | case FDK_Deleted: | ||||||
8960 | NewFD->setDeletedAsWritten(); | ||||||
8961 | break; | ||||||
8962 | } | ||||||
8963 | |||||||
8964 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && | ||||||
8965 | D.isFunctionDefinition()) { | ||||||
8966 | // C++ [class.mfct]p2: | ||||||
8967 | // A member function may be defined (8.4) in its class definition, in | ||||||
8968 | // which case it is an inline member function (7.1.2) | ||||||
8969 | NewFD->setImplicitlyInline(); | ||||||
8970 | } | ||||||
8971 | |||||||
8972 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && | ||||||
8973 | !CurContext->isRecord()) { | ||||||
8974 | // C++ [class.static]p1: | ||||||
8975 | // A data or function member of a class may be declared static | ||||||
8976 | // in a class definition, in which case it is a static member of | ||||||
8977 | // the class. | ||||||
8978 | |||||||
8979 | // Complain about the 'static' specifier if it's on an out-of-line | ||||||
8980 | // member function definition. | ||||||
8981 | |||||||
8982 | // MSVC permits the use of a 'static' storage specifier on an out-of-line | ||||||
8983 | // member function template declaration and class member template | ||||||
8984 | // declaration (MSVC versions before 2015), warn about this. | ||||||
8985 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
8986 | ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | ||||||
8987 | cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || | ||||||
8988 | (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) | ||||||
8989 | ? diag::ext_static_out_of_line : diag::err_static_out_of_line) | ||||||
8990 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
8991 | } | ||||||
8992 | |||||||
8993 | // C++11 [except.spec]p15: | ||||||
8994 | // A deallocation function with no exception-specification is treated | ||||||
8995 | // as if it were specified with noexcept(true). | ||||||
8996 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); | ||||||
8997 | if ((Name.getCXXOverloadedOperator() == OO_Delete || | ||||||
8998 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && | ||||||
8999 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) | ||||||
9000 | NewFD->setType(Context.getFunctionType( | ||||||
9001 | FPT->getReturnType(), FPT->getParamTypes(), | ||||||
9002 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); | ||||||
9003 | } | ||||||
9004 | |||||||
9005 | // Filter out previous declarations that don't match the scope. | ||||||
9006 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), | ||||||
9007 | D.getCXXScopeSpec().isNotEmpty() || | ||||||
9008 | isMemberSpecialization || | ||||||
9009 | isFunctionTemplateSpecialization); | ||||||
9010 | |||||||
9011 | // Handle GNU asm-label extension (encoded as an attribute). | ||||||
9012 | if (Expr *E = (Expr*) D.getAsmLabel()) { | ||||||
9013 | // The parser guarantees this is a string. | ||||||
9014 | StringLiteral *SE = cast<StringLiteral>(E); | ||||||
9015 | NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), | ||||||
9016 | /*IsLiteralLabel=*/true, | ||||||
9017 | SE->getStrTokenLoc(0))); | ||||||
9018 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||||
9019 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||||
9020 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); | ||||||
9021 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||||
9022 | if (isDeclExternC(NewFD)) { | ||||||
9023 | NewFD->addAttr(I->second); | ||||||
9024 | ExtnameUndeclaredIdentifiers.erase(I); | ||||||
9025 | } else | ||||||
9026 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
9027 | << /*Variable*/0 << NewFD; | ||||||
9028 | } | ||||||
9029 | } | ||||||
9030 | |||||||
9031 | // Copy the parameter declarations from the declarator D to the function | ||||||
9032 | // declaration NewFD, if they are available. First scavenge them into Params. | ||||||
9033 | SmallVector<ParmVarDecl*, 16> Params; | ||||||
9034 | unsigned FTIIdx; | ||||||
9035 | if (D.isFunctionDeclarator(FTIIdx)) { | ||||||
9036 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; | ||||||
9037 | |||||||
9038 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs | ||||||
9039 | // function that takes no arguments, not a function that takes a | ||||||
9040 | // single void argument. | ||||||
9041 | // We let through "const void" here because Sema::GetTypeForDeclarator | ||||||
9042 | // already checks for that case. | ||||||
9043 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { | ||||||
9044 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | ||||||
9045 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | ||||||
9046 | assert(Param->getDeclContext() != NewFD && "Was set before ?")((Param->getDeclContext() != NewFD && "Was set before ?" ) ? static_cast<void> (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9046, __PRETTY_FUNCTION__)); | ||||||
9047 | Param->setDeclContext(NewFD); | ||||||
9048 | Params.push_back(Param); | ||||||
9049 | |||||||
9050 | if (Param->isInvalidDecl()) | ||||||
9051 | NewFD->setInvalidDecl(); | ||||||
9052 | } | ||||||
9053 | } | ||||||
9054 | |||||||
9055 | if (!getLangOpts().CPlusPlus) { | ||||||
9056 | // In C, find all the tag declarations from the prototype and move them | ||||||
9057 | // into the function DeclContext. Remove them from the surrounding tag | ||||||
9058 | // injection context of the function, which is typically but not always | ||||||
9059 | // the TU. | ||||||
9060 | DeclContext *PrototypeTagContext = | ||||||
9061 | getTagInjectionContext(NewFD->getLexicalDeclContext()); | ||||||
9062 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { | ||||||
9063 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); | ||||||
9064 | |||||||
9065 | // We don't want to reparent enumerators. Look at their parent enum | ||||||
9066 | // instead. | ||||||
9067 | if (!TD) { | ||||||
9068 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) | ||||||
9069 | TD = cast<EnumDecl>(ECD->getDeclContext()); | ||||||
9070 | } | ||||||
9071 | if (!TD) | ||||||
9072 | continue; | ||||||
9073 | DeclContext *TagDC = TD->getLexicalDeclContext(); | ||||||
9074 | if (!TagDC->containsDecl(TD)) | ||||||
9075 | continue; | ||||||
9076 | TagDC->removeDecl(TD); | ||||||
9077 | TD->setDeclContext(NewFD); | ||||||
9078 | NewFD->addDecl(TD); | ||||||
9079 | |||||||
9080 | // Preserve the lexical DeclContext if it is not the surrounding tag | ||||||
9081 | // injection context of the FD. In this example, the semantic context of | ||||||
9082 | // E will be f and the lexical context will be S, while both the | ||||||
9083 | // semantic and lexical contexts of S will be f: | ||||||
9084 | // void f(struct S { enum E { a } f; } s); | ||||||
9085 | if (TagDC != PrototypeTagContext) | ||||||
9086 | TD->setLexicalDeclContext(TagDC); | ||||||
9087 | } | ||||||
9088 | } | ||||||
9089 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { | ||||||
9090 | // When we're declaring a function with a typedef, typeof, etc as in the | ||||||
9091 | // following example, we'll need to synthesize (unnamed) | ||||||
9092 | // parameters for use in the declaration. | ||||||
9093 | // | ||||||
9094 | // @code | ||||||
9095 | // typedef void fn(int); | ||||||
9096 | // fn f; | ||||||
9097 | // @endcode | ||||||
9098 | |||||||
9099 | // Synthesize a parameter for each argument type. | ||||||
9100 | for (const auto &AI : FT->param_types()) { | ||||||
9101 | ParmVarDecl *Param = | ||||||
9102 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); | ||||||
9103 | Param->setScopeInfo(0, Params.size()); | ||||||
9104 | Params.push_back(Param); | ||||||
9105 | } | ||||||
9106 | } else { | ||||||
9107 | assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9108, __PRETTY_FUNCTION__)) | ||||||
9108 | "Should not need args for typedef of non-prototype fn")((R->isFunctionNoProtoType() && NewFD->getNumParams () == 0 && "Should not need args for typedef of non-prototype fn" ) ? static_cast<void> (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9108, __PRETTY_FUNCTION__)); | ||||||
9109 | } | ||||||
9110 | |||||||
9111 | // Finally, we know we have the right number of parameters, install them. | ||||||
9112 | NewFD->setParams(Params); | ||||||
9113 | |||||||
9114 | if (D.getDeclSpec().isNoreturnSpecified()) | ||||||
9115 | NewFD->addAttr(C11NoReturnAttr::Create(Context, | ||||||
9116 | D.getDeclSpec().getNoreturnSpecLoc(), | ||||||
9117 | AttributeCommonInfo::AS_Keyword)); | ||||||
9118 | |||||||
9119 | // Functions returning a variably modified type violate C99 6.7.5.2p2 | ||||||
9120 | // because all functions have linkage. | ||||||
9121 | if (!NewFD->isInvalidDecl() && | ||||||
9122 | NewFD->getReturnType()->isVariablyModifiedType()) { | ||||||
9123 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); | ||||||
9124 | NewFD->setInvalidDecl(); | ||||||
9125 | } | ||||||
9126 | |||||||
9127 | // Apply an implicit SectionAttr if '#pragma clang section text' is active | ||||||
9128 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && | ||||||
9129 | !NewFD->hasAttr<SectionAttr>()) | ||||||
9130 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( | ||||||
9131 | Context, PragmaClangTextSection.SectionName, | ||||||
9132 | PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); | ||||||
9133 | |||||||
9134 | // Apply an implicit SectionAttr if #pragma code_seg is active. | ||||||
9135 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && | ||||||
9136 | !NewFD->hasAttr<SectionAttr>()) { | ||||||
9137 | NewFD->addAttr(SectionAttr::CreateImplicit( | ||||||
9138 | Context, CodeSegStack.CurrentValue->getString(), | ||||||
9139 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||||
9140 | SectionAttr::Declspec_allocate)); | ||||||
9141 | if (UnifySection(CodeSegStack.CurrentValue->getString(), | ||||||
9142 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | | ||||||
9143 | ASTContext::PSF_Read, | ||||||
9144 | NewFD)) | ||||||
9145 | NewFD->dropAttr<SectionAttr>(); | ||||||
9146 | } | ||||||
9147 | |||||||
9148 | // Apply an implicit CodeSegAttr from class declspec or | ||||||
9149 | // apply an implicit SectionAttr from #pragma code_seg if active. | ||||||
9150 | if (!NewFD->hasAttr<CodeSegAttr>()) { | ||||||
9151 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, | ||||||
9152 | D.isFunctionDefinition())) { | ||||||
9153 | NewFD->addAttr(SAttr); | ||||||
9154 | } | ||||||
9155 | } | ||||||
9156 | |||||||
9157 | // Handle attributes. | ||||||
9158 | ProcessDeclAttributes(S, NewFD, D); | ||||||
9159 | |||||||
9160 | if (getLangOpts().OpenCL) { | ||||||
9161 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return | ||||||
9162 | // type declaration will generate a compilation error. | ||||||
9163 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); | ||||||
9164 | if (AddressSpace != LangAS::Default) { | ||||||
9165 | Diag(NewFD->getLocation(), | ||||||
9166 | diag::err_opencl_return_value_with_address_space); | ||||||
9167 | NewFD->setInvalidDecl(); | ||||||
9168 | } | ||||||
9169 | } | ||||||
9170 | |||||||
9171 | if (!getLangOpts().CPlusPlus) { | ||||||
9172 | // Perform semantic checking on the function declaration. | ||||||
9173 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||||
9174 | CheckMain(NewFD, D.getDeclSpec()); | ||||||
9175 | |||||||
9176 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||||
9177 | CheckMSVCRTEntryPoint(NewFD); | ||||||
9178 | |||||||
9179 | if (!NewFD->isInvalidDecl()) | ||||||
9180 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||||
9181 | isMemberSpecialization)); | ||||||
9182 | else if (!Previous.empty()) | ||||||
9183 | // Recover gracefully from an invalid redeclaration. | ||||||
9184 | D.setRedeclaration(true); | ||||||
9185 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9187, __PRETTY_FUNCTION__)) | ||||||
9186 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9187, __PRETTY_FUNCTION__)) | ||||||
9187 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9187, __PRETTY_FUNCTION__)); | ||||||
9188 | |||||||
9189 | // Diagnose no-prototype function declarations with calling conventions that | ||||||
9190 | // don't support variadic calls. Only do this in C and do it after merging | ||||||
9191 | // possibly prototyped redeclarations. | ||||||
9192 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); | ||||||
9193 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { | ||||||
9194 | CallingConv CC = FT->getExtInfo().getCC(); | ||||||
9195 | if (!supportsVariadicCall(CC)) { | ||||||
9196 | // Windows system headers sometimes accidentally use stdcall without | ||||||
9197 | // (void) parameters, so we relax this to a warning. | ||||||
9198 | int DiagID = | ||||||
9199 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; | ||||||
9200 | Diag(NewFD->getLocation(), DiagID) | ||||||
9201 | << FunctionType::getNameForCallConv(CC); | ||||||
9202 | } | ||||||
9203 | } | ||||||
9204 | |||||||
9205 | if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||||
9206 | NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
9207 | checkNonTrivialCUnion(NewFD->getReturnType(), | ||||||
9208 | NewFD->getReturnTypeSourceRange().getBegin(), | ||||||
9209 | NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); | ||||||
9210 | } else { | ||||||
9211 | // C++11 [replacement.functions]p3: | ||||||
9212 | // The program's definitions shall not be specified as inline. | ||||||
9213 | // | ||||||
9214 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. | ||||||
9215 | // | ||||||
9216 | // Suppress the diagnostic if the function is __attribute__((used)), since | ||||||
9217 | // that forces an external definition to be emitted. | ||||||
9218 | if (D.getDeclSpec().isInlineSpecified() && | ||||||
9219 | NewFD->isReplaceableGlobalAllocationFunction() && | ||||||
9220 | !NewFD->hasAttr<UsedAttr>()) | ||||||
9221 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
9222 | diag::ext_operator_new_delete_declared_inline) | ||||||
9223 | << NewFD->getDeclName(); | ||||||
9224 | |||||||
9225 | // If the declarator is a template-id, translate the parser's template | ||||||
9226 | // argument list into our AST format. | ||||||
9227 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||
9228 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; | ||||||
9229 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); | ||||||
9230 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); | ||||||
9231 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | ||||||
9232 | TemplateId->NumArgs); | ||||||
9233 | translateTemplateArguments(TemplateArgsPtr, | ||||||
9234 | TemplateArgs); | ||||||
9235 | |||||||
9236 | HasExplicitTemplateArgs = true; | ||||||
9237 | |||||||
9238 | if (NewFD->isInvalidDecl()) { | ||||||
9239 | HasExplicitTemplateArgs = false; | ||||||
9240 | } else if (FunctionTemplate) { | ||||||
9241 | // Function template with explicit template arguments. | ||||||
9242 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) | ||||||
9243 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); | ||||||
9244 | |||||||
9245 | HasExplicitTemplateArgs = false; | ||||||
9246 | } else { | ||||||
9247 | assert((isFunctionTemplateSpecialization ||(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9249, __PRETTY_FUNCTION__)) | ||||||
9248 | D.getDeclSpec().isFriendSpecified()) &&(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9249, __PRETTY_FUNCTION__)) | ||||||
9249 | "should have a 'template<>' for this decl")(((isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified ()) && "should have a 'template<>' for this decl" ) ? static_cast<void> (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9249, __PRETTY_FUNCTION__)); | ||||||
9250 | // "friend void foo<>(int);" is an implicit specialization decl. | ||||||
9251 | isFunctionTemplateSpecialization = true; | ||||||
9252 | } | ||||||
9253 | } else if (isFriend && isFunctionTemplateSpecialization) { | ||||||
9254 | // This combination is only possible in a recovery case; the user | ||||||
9255 | // wrote something like: | ||||||
9256 | // template <> friend void foo(int); | ||||||
9257 | // which we're recovering from as if the user had written: | ||||||
9258 | // friend void foo<>(int); | ||||||
9259 | // Go ahead and fake up a template id. | ||||||
9260 | HasExplicitTemplateArgs = true; | ||||||
9261 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); | ||||||
9262 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); | ||||||
9263 | } | ||||||
9264 | |||||||
9265 | // We do not add HD attributes to specializations here because | ||||||
9266 | // they may have different constexpr-ness compared to their | ||||||
9267 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, | ||||||
9268 | // may end up with different effective targets. Instead, a | ||||||
9269 | // specialization inherits its target attributes from its template | ||||||
9270 | // in the CheckFunctionTemplateSpecialization() call below. | ||||||
9271 | if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) | ||||||
9272 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); | ||||||
9273 | |||||||
9274 | // If it's a friend (and only if it's a friend), it's possible | ||||||
9275 | // that either the specialized function type or the specialized | ||||||
9276 | // template is dependent, and therefore matching will fail. In | ||||||
9277 | // this case, don't check the specialization yet. | ||||||
9278 | bool InstantiationDependent = false; | ||||||
9279 | if (isFunctionTemplateSpecialization && isFriend && | ||||||
9280 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || | ||||||
9281 | TemplateSpecializationType::anyDependentTemplateArguments( | ||||||
9282 | TemplateArgs, | ||||||
9283 | InstantiationDependent))) { | ||||||
9284 | assert(HasExplicitTemplateArgs &&((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9285, __PRETTY_FUNCTION__)) | ||||||
9285 | "friend function specialization without template args")((HasExplicitTemplateArgs && "friend function specialization without template args" ) ? static_cast<void> (0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9285, __PRETTY_FUNCTION__)); | ||||||
9286 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, | ||||||
9287 | Previous)) | ||||||
9288 | NewFD->setInvalidDecl(); | ||||||
9289 | } else if (isFunctionTemplateSpecialization) { | ||||||
9290 | if (CurContext->isDependentContext() && CurContext->isRecord() | ||||||
9291 | && !isFriend) { | ||||||
9292 | isDependentClassScopeExplicitSpecialization = true; | ||||||
9293 | } else if (!NewFD->isInvalidDecl() && | ||||||
9294 | CheckFunctionTemplateSpecialization( | ||||||
9295 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), | ||||||
9296 | Previous)) | ||||||
9297 | NewFD->setInvalidDecl(); | ||||||
9298 | |||||||
9299 | // C++ [dcl.stc]p1: | ||||||
9300 | // A storage-class-specifier shall not be specified in an explicit | ||||||
9301 | // specialization (14.7.3) | ||||||
9302 | FunctionTemplateSpecializationInfo *Info = | ||||||
9303 | NewFD->getTemplateSpecializationInfo(); | ||||||
9304 | if (Info && SC != SC_None) { | ||||||
9305 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) | ||||||
9306 | Diag(NewFD->getLocation(), | ||||||
9307 | diag::err_explicit_specialization_inconsistent_storage_class) | ||||||
9308 | << SC | ||||||
9309 | << FixItHint::CreateRemoval( | ||||||
9310 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
9311 | |||||||
9312 | else | ||||||
9313 | Diag(NewFD->getLocation(), | ||||||
9314 | diag::ext_explicit_specialization_storage_class) | ||||||
9315 | << FixItHint::CreateRemoval( | ||||||
9316 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
9317 | } | ||||||
9318 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { | ||||||
9319 | if (CheckMemberSpecialization(NewFD, Previous)) | ||||||
9320 | NewFD->setInvalidDecl(); | ||||||
9321 | } | ||||||
9322 | |||||||
9323 | // Perform semantic checking on the function declaration. | ||||||
9324 | if (!isDependentClassScopeExplicitSpecialization) { | ||||||
9325 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||||
9326 | CheckMain(NewFD, D.getDeclSpec()); | ||||||
9327 | |||||||
9328 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||||
9329 | CheckMSVCRTEntryPoint(NewFD); | ||||||
9330 | |||||||
9331 | if (!NewFD->isInvalidDecl()) | ||||||
9332 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||||
9333 | isMemberSpecialization)); | ||||||
9334 | else if (!Previous.empty()) | ||||||
9335 | // Recover gracefully from an invalid redeclaration. | ||||||
9336 | D.setRedeclaration(true); | ||||||
9337 | } | ||||||
9338 | |||||||
9339 | assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9341, __PRETTY_FUNCTION__)) | ||||||
9340 | Previous.getResultKind() != LookupResult::FoundOverloaded) &&(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9341, __PRETTY_FUNCTION__)) | ||||||
9341 | "previous declaration set still overloaded")(((NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous .getResultKind() != LookupResult::FoundOverloaded) && "previous declaration set still overloaded") ? static_cast< void> (0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9341, __PRETTY_FUNCTION__)); | ||||||
9342 | |||||||
9343 | NamedDecl *PrincipalDecl = (FunctionTemplate | ||||||
9344 | ? cast<NamedDecl>(FunctionTemplate) | ||||||
9345 | : NewFD); | ||||||
9346 | |||||||
9347 | if (isFriend && NewFD->getPreviousDecl()) { | ||||||
9348 | AccessSpecifier Access = AS_public; | ||||||
9349 | if (!NewFD->isInvalidDecl()) | ||||||
9350 | Access = NewFD->getPreviousDecl()->getAccess(); | ||||||
9351 | |||||||
9352 | NewFD->setAccess(Access); | ||||||
9353 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); | ||||||
9354 | } | ||||||
9355 | |||||||
9356 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && | ||||||
9357 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | ||||||
9358 | PrincipalDecl->setNonMemberOperator(); | ||||||
9359 | |||||||
9360 | // If we have a function template, check the template parameter | ||||||
9361 | // list. This will check and merge default template arguments. | ||||||
9362 | if (FunctionTemplate) { | ||||||
9363 | FunctionTemplateDecl *PrevTemplate = | ||||||
9364 | FunctionTemplate->getPreviousDecl(); | ||||||
9365 | CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), | ||||||
9366 | PrevTemplate ? PrevTemplate->getTemplateParameters() | ||||||
9367 | : nullptr, | ||||||
9368 | D.getDeclSpec().isFriendSpecified() | ||||||
9369 | ? (D.isFunctionDefinition() | ||||||
9370 | ? TPC_FriendFunctionTemplateDefinition | ||||||
9371 | : TPC_FriendFunctionTemplate) | ||||||
9372 | : (D.getCXXScopeSpec().isSet() && | ||||||
9373 | DC && DC->isRecord() && | ||||||
9374 | DC->isDependentContext()) | ||||||
9375 | ? TPC_ClassTemplateMember | ||||||
9376 | : TPC_FunctionTemplate); | ||||||
9377 | } | ||||||
9378 | |||||||
9379 | if (NewFD->isInvalidDecl()) { | ||||||
9380 | // Ignore all the rest of this. | ||||||
9381 | } else if (!D.isRedeclaration()) { | ||||||
9382 | struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, | ||||||
9383 | AddToScope }; | ||||||
9384 | // Fake up an access specifier if it's supposed to be a class member. | ||||||
9385 | if (isa<CXXRecordDecl>(NewFD->getDeclContext())) | ||||||
9386 | NewFD->setAccess(AS_public); | ||||||
9387 | |||||||
9388 | // Qualified decls generally require a previous declaration. | ||||||
9389 | if (D.getCXXScopeSpec().isSet()) { | ||||||
9390 | // ...with the major exception of templated-scope or | ||||||
9391 | // dependent-scope friend declarations. | ||||||
9392 | |||||||
9393 | // TODO: we currently also suppress this check in dependent | ||||||
9394 | // contexts because (1) the parameter depth will be off when | ||||||
9395 | // matching friend templates and (2) we might actually be | ||||||
9396 | // selecting a friend based on a dependent factor. But there | ||||||
9397 | // are situations where these conditions don't apply and we | ||||||
9398 | // can actually do this check immediately. | ||||||
9399 | // | ||||||
9400 | // Unless the scope is dependent, it's always an error if qualified | ||||||
9401 | // redeclaration lookup found nothing at all. Diagnose that now; | ||||||
9402 | // nothing will diagnose that error later. | ||||||
9403 | if (isFriend && | ||||||
9404 | (D.getCXXScopeSpec().getScopeRep()->isDependent() || | ||||||
9405 | (!Previous.empty() && CurContext->isDependentContext()))) { | ||||||
9406 | // ignore these | ||||||
9407 | } else { | ||||||
9408 | // The user tried to provide an out-of-line definition for a | ||||||
9409 | // function that is a member of a class or namespace, but there | ||||||
9410 | // was no such member function declared (C++ [class.mfct]p2, | ||||||
9411 | // C++ [namespace.memdef]p2). For example: | ||||||
9412 | // | ||||||
9413 | // class X { | ||||||
9414 | // void f() const; | ||||||
9415 | // }; | ||||||
9416 | // | ||||||
9417 | // void X::f() { } // ill-formed | ||||||
9418 | // | ||||||
9419 | // Complain about this problem, and attempt to suggest close | ||||||
9420 | // matches (e.g., those that differ only in cv-qualifiers and | ||||||
9421 | // whether the parameter types are references). | ||||||
9422 | |||||||
9423 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | ||||||
9424 | *this, Previous, NewFD, ExtraArgs, false, nullptr)) { | ||||||
9425 | AddToScope = ExtraArgs.AddToScope; | ||||||
9426 | return Result; | ||||||
9427 | } | ||||||
9428 | } | ||||||
9429 | |||||||
9430 | // Unqualified local friend declarations are required to resolve | ||||||
9431 | // to something. | ||||||
9432 | } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { | ||||||
9433 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | ||||||
9434 | *this, Previous, NewFD, ExtraArgs, true, S)) { | ||||||
9435 | AddToScope = ExtraArgs.AddToScope; | ||||||
9436 | return Result; | ||||||
9437 | } | ||||||
9438 | } | ||||||
9439 | } else if (!D.isFunctionDefinition() && | ||||||
9440 | isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && | ||||||
9441 | !isFriend && !isFunctionTemplateSpecialization && | ||||||
9442 | !isMemberSpecialization) { | ||||||
9443 | // An out-of-line member function declaration must also be a | ||||||
9444 | // definition (C++ [class.mfct]p2). | ||||||
9445 | // Note that this is not the case for explicit specializations of | ||||||
9446 | // function templates or member functions of class templates, per | ||||||
9447 | // C++ [temp.expl.spec]p2. We also allow these declarations as an | ||||||
9448 | // extension for compatibility with old SWIG code which likes to | ||||||
9449 | // generate them. | ||||||
9450 | Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) | ||||||
9451 | << D.getCXXScopeSpec().getRange(); | ||||||
9452 | } | ||||||
9453 | } | ||||||
9454 | |||||||
9455 | ProcessPragmaWeak(S, NewFD); | ||||||
9456 | checkAttributesAfterMerging(*this, *NewFD); | ||||||
9457 | |||||||
9458 | AddKnownFunctionAttributes(NewFD); | ||||||
9459 | |||||||
9460 | if (NewFD->hasAttr<OverloadableAttr>() && | ||||||
9461 | !NewFD->getType()->getAs<FunctionProtoType>()) { | ||||||
9462 | Diag(NewFD->getLocation(), | ||||||
9463 | diag::err_attribute_overloadable_no_prototype) | ||||||
9464 | << NewFD; | ||||||
9465 | |||||||
9466 | // Turn this into a variadic function with no parameters. | ||||||
9467 | const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); | ||||||
9468 | FunctionProtoType::ExtProtoInfo EPI( | ||||||
9469 | Context.getDefaultCallingConvention(true, false)); | ||||||
9470 | EPI.Variadic = true; | ||||||
9471 | EPI.ExtInfo = FT->getExtInfo(); | ||||||
9472 | |||||||
9473 | QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); | ||||||
9474 | NewFD->setType(R); | ||||||
9475 | } | ||||||
9476 | |||||||
9477 | // If there's a #pragma GCC visibility in scope, and this isn't a class | ||||||
9478 | // member, set the visibility of this function. | ||||||
9479 | if (!DC->isRecord() && NewFD->isExternallyVisible()) | ||||||
9480 | AddPushedVisibilityAttribute(NewFD); | ||||||
9481 | |||||||
9482 | // If there's a #pragma clang arc_cf_code_audited in scope, consider | ||||||
9483 | // marking the function. | ||||||
9484 | AddCFAuditedAttribute(NewFD); | ||||||
9485 | |||||||
9486 | // If this is a function definition, check if we have to apply optnone due to | ||||||
9487 | // a pragma. | ||||||
9488 | if(D.isFunctionDefinition()) | ||||||
9489 | AddRangeBasedOptnone(NewFD); | ||||||
9490 | |||||||
9491 | // If this is the first declaration of an extern C variable, update | ||||||
9492 | // the map of such variables. | ||||||
9493 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && | ||||||
9494 | isIncompleteDeclExternC(*this, NewFD)) | ||||||
9495 | RegisterLocallyScopedExternCDecl(NewFD, S); | ||||||
9496 | |||||||
9497 | // Set this FunctionDecl's range up to the right paren. | ||||||
9498 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); | ||||||
9499 | |||||||
9500 | if (D.isRedeclaration() && !Previous.empty()) { | ||||||
9501 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||||
9502 | checkDLLAttributeRedeclaration(*this, Prev, NewFD, | ||||||
9503 | isMemberSpecialization || | ||||||
9504 | isFunctionTemplateSpecialization, | ||||||
9505 | D.isFunctionDefinition()); | ||||||
9506 | } | ||||||
9507 | |||||||
9508 | if (getLangOpts().CUDA) { | ||||||
9509 | IdentifierInfo *II = NewFD->getIdentifier(); | ||||||
9510 | if (II && II->isStr(getCudaConfigureFuncName()) && | ||||||
9511 | !NewFD->isInvalidDecl() && | ||||||
9512 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
9513 | if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) | ||||||
9514 | Diag(NewFD->getLocation(), diag::err_config_scalar_return) | ||||||
9515 | << getCudaConfigureFuncName(); | ||||||
9516 | Context.setcudaConfigureCallDecl(NewFD); | ||||||
9517 | } | ||||||
9518 | |||||||
9519 | // Variadic functions, other than a *declaration* of printf, are not allowed | ||||||
9520 | // in device-side CUDA code, unless someone passed | ||||||
9521 | // -fcuda-allow-variadic-functions. | ||||||
9522 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && | ||||||
9523 | (NewFD->hasAttr<CUDADeviceAttr>() || | ||||||
9524 | NewFD->hasAttr<CUDAGlobalAttr>()) && | ||||||
9525 | !(II && II->isStr("printf") && NewFD->isExternC() && | ||||||
9526 | !D.isFunctionDefinition())) { | ||||||
9527 | Diag(NewFD->getLocation(), diag::err_variadic_device_fn); | ||||||
9528 | } | ||||||
9529 | } | ||||||
9530 | |||||||
9531 | MarkUnusedFileScopedDecl(NewFD); | ||||||
9532 | |||||||
9533 | |||||||
9534 | |||||||
9535 | if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { | ||||||
9536 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. | ||||||
9537 | if ((getLangOpts().OpenCLVersion >= 120) | ||||||
9538 | && (SC == SC_Static)) { | ||||||
9539 | Diag(D.getIdentifierLoc(), diag::err_static_kernel); | ||||||
9540 | D.setInvalidType(); | ||||||
9541 | } | ||||||
9542 | |||||||
9543 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. | ||||||
9544 | if (!NewFD->getReturnType()->isVoidType()) { | ||||||
9545 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); | ||||||
9546 | Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) | ||||||
9547 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") | ||||||
9548 | : FixItHint()); | ||||||
9549 | D.setInvalidType(); | ||||||
9550 | } | ||||||
9551 | |||||||
9552 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; | ||||||
9553 | for (auto Param : NewFD->parameters()) | ||||||
9554 | checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); | ||||||
9555 | |||||||
9556 | if (getLangOpts().OpenCLCPlusPlus) { | ||||||
9557 | if (DC->isRecord()) { | ||||||
9558 | Diag(D.getIdentifierLoc(), diag::err_method_kernel); | ||||||
9559 | D.setInvalidType(); | ||||||
9560 | } | ||||||
9561 | if (FunctionTemplate) { | ||||||
9562 | Diag(D.getIdentifierLoc(), diag::err_template_kernel); | ||||||
9563 | D.setInvalidType(); | ||||||
9564 | } | ||||||
9565 | } | ||||||
9566 | } | ||||||
9567 | |||||||
9568 | if (getLangOpts().CPlusPlus) { | ||||||
9569 | if (FunctionTemplate) { | ||||||
9570 | if (NewFD->isInvalidDecl()) | ||||||
9571 | FunctionTemplate->setInvalidDecl(); | ||||||
9572 | return FunctionTemplate; | ||||||
9573 | } | ||||||
9574 | |||||||
9575 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) | ||||||
9576 | CompleteMemberSpecialization(NewFD, Previous); | ||||||
9577 | } | ||||||
9578 | |||||||
9579 | for (const ParmVarDecl *Param : NewFD->parameters()) { | ||||||
9580 | QualType PT = Param->getType(); | ||||||
9581 | |||||||
9582 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value | ||||||
9583 | // types. | ||||||
9584 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | ||||||
9585 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { | ||||||
9586 | QualType ElemTy = PipeTy->getElementType(); | ||||||
9587 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { | ||||||
9588 | Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); | ||||||
9589 | D.setInvalidType(); | ||||||
9590 | } | ||||||
9591 | } | ||||||
9592 | } | ||||||
9593 | } | ||||||
9594 | |||||||
9595 | // Here we have an function template explicit specialization at class scope. | ||||||
9596 | // The actual specialization will be postponed to template instatiation | ||||||
9597 | // time via the ClassScopeFunctionSpecializationDecl node. | ||||||
9598 | if (isDependentClassScopeExplicitSpecialization) { | ||||||
9599 | ClassScopeFunctionSpecializationDecl *NewSpec = | ||||||
9600 | ClassScopeFunctionSpecializationDecl::Create( | ||||||
9601 | Context, CurContext, NewFD->getLocation(), | ||||||
9602 | cast<CXXMethodDecl>(NewFD), | ||||||
9603 | HasExplicitTemplateArgs, TemplateArgs); | ||||||
9604 | CurContext->addDecl(NewSpec); | ||||||
9605 | AddToScope = false; | ||||||
9606 | } | ||||||
9607 | |||||||
9608 | // Diagnose availability attributes. Availability cannot be used on functions | ||||||
9609 | // that are run during load/unload. | ||||||
9610 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { | ||||||
9611 | if (NewFD->hasAttr<ConstructorAttr>()) { | ||||||
9612 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | ||||||
9613 | << 1; | ||||||
9614 | NewFD->dropAttr<AvailabilityAttr>(); | ||||||
9615 | } | ||||||
9616 | if (NewFD->hasAttr<DestructorAttr>()) { | ||||||
9617 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | ||||||
9618 | << 2; | ||||||
9619 | NewFD->dropAttr<AvailabilityAttr>(); | ||||||
9620 | } | ||||||
9621 | } | ||||||
9622 | |||||||
9623 | // Diagnose no_builtin attribute on function declaration that are not a | ||||||
9624 | // definition. | ||||||
9625 | // FIXME: We should really be doing this in | ||||||
9626 | // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to | ||||||
9627 | // the FunctionDecl and at this point of the code | ||||||
9628 | // FunctionDecl::isThisDeclarationADefinition() which always returns `false` | ||||||
9629 | // because Sema::ActOnStartOfFunctionDef has not been called yet. | ||||||
9630 | if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) | ||||||
9631 | switch (D.getFunctionDefinitionKind()) { | ||||||
9632 | case FDK_Defaulted: | ||||||
9633 | case FDK_Deleted: | ||||||
9634 | Diag(NBA->getLocation(), | ||||||
9635 | diag::err_attribute_no_builtin_on_defaulted_deleted_function) | ||||||
9636 | << NBA->getSpelling(); | ||||||
9637 | break; | ||||||
9638 | case FDK_Declaration: | ||||||
9639 | Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) | ||||||
9640 | << NBA->getSpelling(); | ||||||
9641 | break; | ||||||
9642 | case FDK_Definition: | ||||||
9643 | break; | ||||||
9644 | } | ||||||
9645 | |||||||
9646 | return NewFD; | ||||||
9647 | } | ||||||
9648 | |||||||
9649 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say | ||||||
9650 | /// when __declspec(code_seg) "is applied to a class, all member functions of | ||||||
9651 | /// the class and nested classes -- this includes compiler-generated special | ||||||
9652 | /// member functions -- are put in the specified segment." | ||||||
9653 | /// The actual behavior is a little more complicated. The Microsoft compiler | ||||||
9654 | /// won't check outer classes if there is an active value from #pragma code_seg. | ||||||
9655 | /// The CodeSeg is always applied from the direct parent but only from outer | ||||||
9656 | /// classes when the #pragma code_seg stack is empty. See: | ||||||
9657 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer | ||||||
9658 | /// available since MS has removed the page. | ||||||
9659 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { | ||||||
9660 | const auto *Method = dyn_cast<CXXMethodDecl>(FD); | ||||||
9661 | if (!Method) | ||||||
9662 | return nullptr; | ||||||
9663 | const CXXRecordDecl *Parent = Method->getParent(); | ||||||
9664 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | ||||||
9665 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | ||||||
9666 | NewAttr->setImplicit(true); | ||||||
9667 | return NewAttr; | ||||||
9668 | } | ||||||
9669 | |||||||
9670 | // The Microsoft compiler won't check outer classes for the CodeSeg | ||||||
9671 | // when the #pragma code_seg stack is active. | ||||||
9672 | if (S.CodeSegStack.CurrentValue) | ||||||
9673 | return nullptr; | ||||||
9674 | |||||||
9675 | while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { | ||||||
9676 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | ||||||
9677 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | ||||||
9678 | NewAttr->setImplicit(true); | ||||||
9679 | return NewAttr; | ||||||
9680 | } | ||||||
9681 | } | ||||||
9682 | return nullptr; | ||||||
9683 | } | ||||||
9684 | |||||||
9685 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a | ||||||
9686 | /// containing class. Otherwise it will return implicit SectionAttr if the | ||||||
9687 | /// function is a definition and there is an active value on CodeSegStack | ||||||
9688 | /// (from the current #pragma code-seg value). | ||||||
9689 | /// | ||||||
9690 | /// \param FD Function being declared. | ||||||
9691 | /// \param IsDefinition Whether it is a definition or just a declarartion. | ||||||
9692 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or | ||||||
9693 | /// nullptr if no attribute should be added. | ||||||
9694 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, | ||||||
9695 | bool IsDefinition) { | ||||||
9696 | if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) | ||||||
9697 | return A; | ||||||
9698 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && | ||||||
9699 | CodeSegStack.CurrentValue) | ||||||
9700 | return SectionAttr::CreateImplicit( | ||||||
9701 | getASTContext(), CodeSegStack.CurrentValue->getString(), | ||||||
9702 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||||
9703 | SectionAttr::Declspec_allocate); | ||||||
9704 | return nullptr; | ||||||
9705 | } | ||||||
9706 | |||||||
9707 | /// Determines if we can perform a correct type check for \p D as a | ||||||
9708 | /// redeclaration of \p PrevDecl. If not, we can generally still perform a | ||||||
9709 | /// best-effort check. | ||||||
9710 | /// | ||||||
9711 | /// \param NewD The new declaration. | ||||||
9712 | /// \param OldD The old declaration. | ||||||
9713 | /// \param NewT The portion of the type of the new declaration to check. | ||||||
9714 | /// \param OldT The portion of the type of the old declaration to check. | ||||||
9715 | bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, | ||||||
9716 | QualType NewT, QualType OldT) { | ||||||
9717 | if (!NewD->getLexicalDeclContext()->isDependentContext()) | ||||||
9718 | return true; | ||||||
9719 | |||||||
9720 | // For dependently-typed local extern declarations and friends, we can't | ||||||
9721 | // perform a correct type check in general until instantiation: | ||||||
9722 | // | ||||||
9723 | // int f(); | ||||||
9724 | // template<typename T> void g() { T f(); } | ||||||
9725 | // | ||||||
9726 | // (valid if g() is only instantiated with T = int). | ||||||
9727 | if (NewT->isDependentType() && | ||||||
9728 | (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) | ||||||
9729 | return false; | ||||||
9730 | |||||||
9731 | // Similarly, if the previous declaration was a dependent local extern | ||||||
9732 | // declaration, we don't really know its type yet. | ||||||
9733 | if (OldT->isDependentType() && OldD->isLocalExternDecl()) | ||||||
9734 | return false; | ||||||
9735 | |||||||
9736 | return true; | ||||||
9737 | } | ||||||
9738 | |||||||
9739 | /// Checks if the new declaration declared in dependent context must be | ||||||
9740 | /// put in the same redeclaration chain as the specified declaration. | ||||||
9741 | /// | ||||||
9742 | /// \param D Declaration that is checked. | ||||||
9743 | /// \param PrevDecl Previous declaration found with proper lookup method for the | ||||||
9744 | /// same declaration name. | ||||||
9745 | /// \returns True if D must be added to the redeclaration chain which PrevDecl | ||||||
9746 | /// belongs to. | ||||||
9747 | /// | ||||||
9748 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { | ||||||
9749 | if (!D->getLexicalDeclContext()->isDependentContext()) | ||||||
9750 | return true; | ||||||
9751 | |||||||
9752 | // Don't chain dependent friend function definitions until instantiation, to | ||||||
9753 | // permit cases like | ||||||
9754 | // | ||||||
9755 | // void func(); | ||||||
9756 | // template<typename T> class C1 { friend void func() {} }; | ||||||
9757 | // template<typename T> class C2 { friend void func() {} }; | ||||||
9758 | // | ||||||
9759 | // ... which is valid if only one of C1 and C2 is ever instantiated. | ||||||
9760 | // | ||||||
9761 | // FIXME: This need only apply to function definitions. For now, we proxy | ||||||
9762 | // this by checking for a file-scope function. We do not want this to apply | ||||||
9763 | // to friend declarations nominating member functions, because that gets in | ||||||
9764 | // the way of access checks. | ||||||
9765 | if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) | ||||||
9766 | return false; | ||||||
9767 | |||||||
9768 | auto *VD = dyn_cast<ValueDecl>(D); | ||||||
9769 | auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); | ||||||
9770 | return !VD || !PrevVD || | ||||||
9771 | canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), | ||||||
9772 | PrevVD->getType()); | ||||||
9773 | } | ||||||
9774 | |||||||
9775 | /// Check the target attribute of the function for MultiVersion | ||||||
9776 | /// validity. | ||||||
9777 | /// | ||||||
9778 | /// Returns true if there was an error, false otherwise. | ||||||
9779 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { | ||||||
9780 | const auto *TA = FD->getAttr<TargetAttr>(); | ||||||
9781 | assert(TA && "MultiVersion Candidate requires a target attribute")((TA && "MultiVersion Candidate requires a target attribute" ) ? static_cast<void> (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 9781, __PRETTY_FUNCTION__)); | ||||||
9782 | ParsedTargetAttr ParseInfo = TA->parse(); | ||||||
9783 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); | ||||||
9784 | enum ErrType { Feature = 0, Architecture = 1 }; | ||||||
9785 | |||||||
9786 | if (!ParseInfo.Architecture.empty() && | ||||||
9787 | !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { | ||||||
9788 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
9789 | << Architecture << ParseInfo.Architecture; | ||||||
9790 | return true; | ||||||
9791 | } | ||||||
9792 | |||||||
9793 | for (const auto &Feat : ParseInfo.Features) { | ||||||
9794 | auto BareFeat = StringRef{Feat}.substr(1); | ||||||
9795 | if (Feat[0] == '-') { | ||||||
9796 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
9797 | << Feature << ("no-" + BareFeat).str(); | ||||||
9798 | return true; | ||||||
9799 | } | ||||||
9800 | |||||||
9801 | if (!TargetInfo.validateCpuSupports(BareFeat) || | ||||||
9802 | !TargetInfo.isValidFeatureName(BareFeat)) { | ||||||
9803 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
9804 | << Feature << BareFeat; | ||||||
9805 | return true; | ||||||
9806 | } | ||||||
9807 | } | ||||||
9808 | return false; | ||||||
9809 | } | ||||||
9810 | |||||||
9811 | static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, | ||||||
9812 | MultiVersionKind MVType) { | ||||||
9813 | for (const Attr *A : FD->attrs()) { | ||||||
9814 | switch (A->getKind()) { | ||||||
9815 | case attr::CPUDispatch: | ||||||
9816 | case attr::CPUSpecific: | ||||||
9817 | if (MVType != MultiVersionKind::CPUDispatch && | ||||||
9818 | MVType != MultiVersionKind::CPUSpecific) | ||||||
9819 | return true; | ||||||
9820 | break; | ||||||
9821 | case attr::Target: | ||||||
9822 | if (MVType != MultiVersionKind::Target) | ||||||
9823 | return true; | ||||||
9824 | break; | ||||||
9825 | default: | ||||||
9826 | return true; | ||||||
9827 | } | ||||||
9828 | } | ||||||
9829 | return false; | ||||||
9830 | } | ||||||
9831 | |||||||
9832 | bool Sema::areMultiversionVariantFunctionsCompatible( | ||||||
9833 | const FunctionDecl *OldFD, const FunctionDecl *NewFD, | ||||||
9834 | const PartialDiagnostic &NoProtoDiagID, | ||||||
9835 | const PartialDiagnosticAt &NoteCausedDiagIDAt, | ||||||
9836 | const PartialDiagnosticAt &NoSupportDiagIDAt, | ||||||
9837 | const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, | ||||||
9838 | bool ConstexprSupported, bool CLinkageMayDiffer) { | ||||||
9839 | enum DoesntSupport { | ||||||
9840 | FuncTemplates = 0, | ||||||
9841 | VirtFuncs = 1, | ||||||
9842 | DeducedReturn = 2, | ||||||
9843 | Constructors = 3, | ||||||
9844 | Destructors = 4, | ||||||
9845 | DeletedFuncs = 5, | ||||||
9846 | DefaultedFuncs = 6, | ||||||
9847 | ConstexprFuncs = 7, | ||||||
9848 | ConstevalFuncs = 8, | ||||||
9849 | }; | ||||||
9850 | enum Different { | ||||||
9851 | CallingConv = 0, | ||||||
9852 | ReturnType = 1, | ||||||
9853 | ConstexprSpec = 2, | ||||||
9854 | InlineSpec = 3, | ||||||
9855 | StorageClass = 4, | ||||||
9856 | Linkage = 5, | ||||||
9857 | }; | ||||||
9858 | |||||||
9859 | if (NoProtoDiagID.getDiagID() != 0 && OldFD && | ||||||
9860 | !OldFD->getType()->getAs<FunctionProtoType>()) { | ||||||
9861 | Diag(OldFD->getLocation(), NoProtoDiagID); | ||||||
9862 | Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); | ||||||
9863 | return true; | ||||||
9864 | } | ||||||
9865 | |||||||
9866 | if (NoProtoDiagID.getDiagID() != 0 && | ||||||
9867 | !NewFD->getType()->getAs<FunctionProtoType>()) | ||||||
9868 | return Diag(NewFD->getLocation(), NoProtoDiagID); | ||||||
9869 | |||||||
9870 | if (!TemplatesSupported && | ||||||
9871 | NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) | ||||||
9872 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9873 | << FuncTemplates; | ||||||
9874 | |||||||
9875 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { | ||||||
9876 | if (NewCXXFD->isVirtual()) | ||||||
9877 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9878 | << VirtFuncs; | ||||||
9879 | |||||||
9880 | if (isa<CXXConstructorDecl>(NewCXXFD)) | ||||||
9881 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9882 | << Constructors; | ||||||
9883 | |||||||
9884 | if (isa<CXXDestructorDecl>(NewCXXFD)) | ||||||
9885 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9886 | << Destructors; | ||||||
9887 | } | ||||||
9888 | |||||||
9889 | if (NewFD->isDeleted()) | ||||||
9890 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9891 | << DeletedFuncs; | ||||||
9892 | |||||||
9893 | if (NewFD->isDefaulted()) | ||||||
9894 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9895 | << DefaultedFuncs; | ||||||
9896 | |||||||
9897 | if (!ConstexprSupported && NewFD->isConstexpr()) | ||||||
9898 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9899 | << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); | ||||||
9900 | |||||||
9901 | QualType NewQType = Context.getCanonicalType(NewFD->getType()); | ||||||
9902 | const auto *NewType = cast<FunctionType>(NewQType); | ||||||
9903 | QualType NewReturnType = NewType->getReturnType(); | ||||||
9904 | |||||||
9905 | if (NewReturnType->isUndeducedType()) | ||||||
9906 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
9907 | << DeducedReturn; | ||||||
9908 | |||||||
9909 | // Ensure the return type is identical. | ||||||
9910 | if (OldFD) { | ||||||
9911 | QualType OldQType = Context.getCanonicalType(OldFD->getType()); | ||||||
9912 | const auto *OldType = cast<FunctionType>(OldQType); | ||||||
9913 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||||
9914 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||||
9915 | |||||||
9916 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) | ||||||
9917 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; | ||||||
9918 | |||||||
9919 | QualType OldReturnType = OldType->getReturnType(); | ||||||
9920 | |||||||
9921 | if (OldReturnType != NewReturnType) | ||||||
9922 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; | ||||||
9923 | |||||||
9924 | if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) | ||||||
9925 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; | ||||||
9926 | |||||||
9927 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) | ||||||
9928 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; | ||||||
9929 | |||||||
9930 | if (OldFD->getStorageClass() != NewFD->getStorageClass()) | ||||||
9931 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; | ||||||
9932 | |||||||
9933 | if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) | ||||||
9934 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; | ||||||
9935 | |||||||
9936 | if (CheckEquivalentExceptionSpec( | ||||||
9937 | OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), | ||||||
9938 | NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) | ||||||
9939 | return true; | ||||||
9940 | } | ||||||
9941 | return false; | ||||||
9942 | } | ||||||
9943 | |||||||
9944 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, | ||||||
9945 | const FunctionDecl *NewFD, | ||||||
9946 | bool CausesMV, | ||||||
9947 | MultiVersionKind MVType) { | ||||||
9948 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | ||||||
9949 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | ||||||
9950 | if (OldFD) | ||||||
9951 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
9952 | return true; | ||||||
9953 | } | ||||||
9954 | |||||||
9955 | bool IsCPUSpecificCPUDispatchMVType = | ||||||
9956 | MVType == MultiVersionKind::CPUDispatch || | ||||||
9957 | MVType == MultiVersionKind::CPUSpecific; | ||||||
9958 | |||||||
9959 | // For now, disallow all other attributes. These should be opt-in, but | ||||||
9960 | // an analysis of all of them is a future FIXME. | ||||||
9961 | if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { | ||||||
9962 | S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) | ||||||
9963 | << IsCPUSpecificCPUDispatchMVType; | ||||||
9964 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
9965 | return true; | ||||||
9966 | } | ||||||
9967 | |||||||
9968 | if (HasNonMultiVersionAttributes(NewFD, MVType)) | ||||||
9969 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) | ||||||
9970 | << IsCPUSpecificCPUDispatchMVType; | ||||||
9971 | |||||||
9972 | // Only allow transition to MultiVersion if it hasn't been used. | ||||||
9973 | if (OldFD && CausesMV && OldFD->isUsed(false)) | ||||||
9974 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); | ||||||
9975 | |||||||
9976 | return S.areMultiversionVariantFunctionsCompatible( | ||||||
9977 | OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), | ||||||
9978 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
9979 | S.PDiag(diag::note_multiversioning_caused_here)), | ||||||
9980 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
9981 | S.PDiag(diag::err_multiversion_doesnt_support) | ||||||
9982 | << IsCPUSpecificCPUDispatchMVType), | ||||||
9983 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
9984 | S.PDiag(diag::err_multiversion_diff)), | ||||||
9985 | /*TemplatesSupported=*/false, | ||||||
9986 | /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, | ||||||
9987 | /*CLinkageMayDiffer=*/false); | ||||||
9988 | } | ||||||
9989 | |||||||
9990 | /// Check the validity of a multiversion function declaration that is the | ||||||
9991 | /// first of its kind. Also sets the multiversion'ness' of the function itself. | ||||||
9992 | /// | ||||||
9993 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
9994 | /// | ||||||
9995 | /// Returns true if there was an error, false otherwise. | ||||||
9996 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, | ||||||
9997 | MultiVersionKind MVType, | ||||||
9998 | const TargetAttr *TA) { | ||||||
9999 | assert(MVType != MultiVersionKind::None &&((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10000, __PRETTY_FUNCTION__)) | ||||||
10000 | "Function lacks multiversion attribute")((MVType != MultiVersionKind::None && "Function lacks multiversion attribute" ) ? static_cast<void> (0) : __assert_fail ("MVType != MultiVersionKind::None && \"Function lacks multiversion attribute\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10000, __PRETTY_FUNCTION__)); | ||||||
10001 | |||||||
10002 | // Target only causes MV if it is default, otherwise this is a normal | ||||||
10003 | // function. | ||||||
10004 | if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) | ||||||
10005 | return false; | ||||||
10006 | |||||||
10007 | if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { | ||||||
10008 | FD->setInvalidDecl(); | ||||||
10009 | return true; | ||||||
10010 | } | ||||||
10011 | |||||||
10012 | if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { | ||||||
10013 | FD->setInvalidDecl(); | ||||||
10014 | return true; | ||||||
10015 | } | ||||||
10016 | |||||||
10017 | FD->setIsMultiVersion(); | ||||||
10018 | return false; | ||||||
10019 | } | ||||||
10020 | |||||||
10021 | static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { | ||||||
10022 | for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { | ||||||
10023 | if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) | ||||||
10024 | return true; | ||||||
10025 | } | ||||||
10026 | |||||||
10027 | return false; | ||||||
10028 | } | ||||||
10029 | |||||||
10030 | static bool CheckTargetCausesMultiVersioning( | ||||||
10031 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, | ||||||
10032 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | ||||||
10033 | LookupResult &Previous) { | ||||||
10034 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); | ||||||
10035 | ParsedTargetAttr NewParsed = NewTA->parse(); | ||||||
10036 | // Sort order doesn't matter, it just needs to be consistent. | ||||||
10037 | llvm::sort(NewParsed.Features); | ||||||
10038 | |||||||
10039 | // If the old decl is NOT MultiVersioned yet, and we don't cause that | ||||||
10040 | // to change, this is a simple redeclaration. | ||||||
10041 | if (!NewTA->isDefaultVersion() && | ||||||
10042 | (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) | ||||||
10043 | return false; | ||||||
10044 | |||||||
10045 | // Otherwise, this decl causes MultiVersioning. | ||||||
10046 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | ||||||
10047 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | ||||||
10048 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10049 | NewFD->setInvalidDecl(); | ||||||
10050 | return true; | ||||||
10051 | } | ||||||
10052 | |||||||
10053 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, | ||||||
10054 | MultiVersionKind::Target)) { | ||||||
10055 | NewFD->setInvalidDecl(); | ||||||
10056 | return true; | ||||||
10057 | } | ||||||
10058 | |||||||
10059 | if (CheckMultiVersionValue(S, NewFD)) { | ||||||
10060 | NewFD->setInvalidDecl(); | ||||||
10061 | return true; | ||||||
10062 | } | ||||||
10063 | |||||||
10064 | // If this is 'default', permit the forward declaration. | ||||||
10065 | if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { | ||||||
10066 | Redeclaration = true; | ||||||
10067 | OldDecl = OldFD; | ||||||
10068 | OldFD->setIsMultiVersion(); | ||||||
10069 | NewFD->setIsMultiVersion(); | ||||||
10070 | return false; | ||||||
10071 | } | ||||||
10072 | |||||||
10073 | if (CheckMultiVersionValue(S, OldFD)) { | ||||||
10074 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
10075 | NewFD->setInvalidDecl(); | ||||||
10076 | return true; | ||||||
10077 | } | ||||||
10078 | |||||||
10079 | ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); | ||||||
10080 | |||||||
10081 | if (OldParsed == NewParsed) { | ||||||
10082 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | ||||||
10083 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10084 | NewFD->setInvalidDecl(); | ||||||
10085 | return true; | ||||||
10086 | } | ||||||
10087 | |||||||
10088 | for (const auto *FD : OldFD->redecls()) { | ||||||
10089 | const auto *CurTA = FD->getAttr<TargetAttr>(); | ||||||
10090 | // We allow forward declarations before ANY multiversioning attributes, but | ||||||
10091 | // nothing after the fact. | ||||||
10092 | if (PreviousDeclsHaveMultiVersionAttribute(FD) && | ||||||
10093 | (!CurTA || CurTA->isInherited())) { | ||||||
10094 | S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) | ||||||
10095 | << 0; | ||||||
10096 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
10097 | NewFD->setInvalidDecl(); | ||||||
10098 | return true; | ||||||
10099 | } | ||||||
10100 | } | ||||||
10101 | |||||||
10102 | OldFD->setIsMultiVersion(); | ||||||
10103 | NewFD->setIsMultiVersion(); | ||||||
10104 | Redeclaration = false; | ||||||
10105 | MergeTypeWithPrevious = false; | ||||||
10106 | OldDecl = nullptr; | ||||||
10107 | Previous.clear(); | ||||||
10108 | return false; | ||||||
10109 | } | ||||||
10110 | |||||||
10111 | /// Check the validity of a new function declaration being added to an existing | ||||||
10112 | /// multiversioned declaration collection. | ||||||
10113 | static bool CheckMultiVersionAdditionalDecl( | ||||||
10114 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, | ||||||
10115 | MultiVersionKind NewMVType, const TargetAttr *NewTA, | ||||||
10116 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, | ||||||
10117 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | ||||||
10118 | LookupResult &Previous) { | ||||||
10119 | |||||||
10120 | MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); | ||||||
10121 | // Disallow mixing of multiversioning types. | ||||||
10122 | if ((OldMVType == MultiVersionKind::Target && | ||||||
10123 | NewMVType != MultiVersionKind::Target) || | ||||||
10124 | (NewMVType == MultiVersionKind::Target && | ||||||
10125 | OldMVType != MultiVersionKind::Target)) { | ||||||
10126 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | ||||||
10127 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10128 | NewFD->setInvalidDecl(); | ||||||
10129 | return true; | ||||||
10130 | } | ||||||
10131 | |||||||
10132 | ParsedTargetAttr NewParsed; | ||||||
10133 | if (NewTA) { | ||||||
10134 | NewParsed = NewTA->parse(); | ||||||
10135 | llvm::sort(NewParsed.Features); | ||||||
10136 | } | ||||||
10137 | |||||||
10138 | bool UseMemberUsingDeclRules = | ||||||
10139 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); | ||||||
10140 | |||||||
10141 | // Next, check ALL non-overloads to see if this is a redeclaration of a | ||||||
10142 | // previous member of the MultiVersion set. | ||||||
10143 | for (NamedDecl *ND : Previous) { | ||||||
10144 | FunctionDecl *CurFD = ND->getAsFunction(); | ||||||
10145 | if (!CurFD) | ||||||
10146 | continue; | ||||||
10147 | if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) | ||||||
10148 | continue; | ||||||
10149 | |||||||
10150 | if (NewMVType == MultiVersionKind::Target) { | ||||||
10151 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); | ||||||
10152 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { | ||||||
10153 | NewFD->setIsMultiVersion(); | ||||||
10154 | Redeclaration = true; | ||||||
10155 | OldDecl = ND; | ||||||
10156 | return false; | ||||||
10157 | } | ||||||
10158 | |||||||
10159 | ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); | ||||||
10160 | if (CurParsed == NewParsed) { | ||||||
10161 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | ||||||
10162 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10163 | NewFD->setInvalidDecl(); | ||||||
10164 | return true; | ||||||
10165 | } | ||||||
10166 | } else { | ||||||
10167 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); | ||||||
10168 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); | ||||||
10169 | // Handle CPUDispatch/CPUSpecific versions. | ||||||
10170 | // Only 1 CPUDispatch function is allowed, this will make it go through | ||||||
10171 | // the redeclaration errors. | ||||||
10172 | if (NewMVType == MultiVersionKind::CPUDispatch && | ||||||
10173 | CurFD->hasAttr<CPUDispatchAttr>()) { | ||||||
10174 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && | ||||||
10175 | std::equal( | ||||||
10176 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), | ||||||
10177 | NewCPUDisp->cpus_begin(), | ||||||
10178 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | ||||||
10179 | return Cur->getName() == New->getName(); | ||||||
10180 | })) { | ||||||
10181 | NewFD->setIsMultiVersion(); | ||||||
10182 | Redeclaration = true; | ||||||
10183 | OldDecl = ND; | ||||||
10184 | return false; | ||||||
10185 | } | ||||||
10186 | |||||||
10187 | // If the declarations don't match, this is an error condition. | ||||||
10188 | S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); | ||||||
10189 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10190 | NewFD->setInvalidDecl(); | ||||||
10191 | return true; | ||||||
10192 | } | ||||||
10193 | if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { | ||||||
10194 | |||||||
10195 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && | ||||||
10196 | std::equal( | ||||||
10197 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), | ||||||
10198 | NewCPUSpec->cpus_begin(), | ||||||
10199 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | ||||||
10200 | return Cur->getName() == New->getName(); | ||||||
10201 | })) { | ||||||
10202 | NewFD->setIsMultiVersion(); | ||||||
10203 | Redeclaration = true; | ||||||
10204 | OldDecl = ND; | ||||||
10205 | return false; | ||||||
10206 | } | ||||||
10207 | |||||||
10208 | // Only 1 version of CPUSpecific is allowed for each CPU. | ||||||
10209 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { | ||||||
10210 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { | ||||||
10211 | if (CurII == NewII) { | ||||||
10212 | S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) | ||||||
10213 | << NewII; | ||||||
10214 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10215 | NewFD->setInvalidDecl(); | ||||||
10216 | return true; | ||||||
10217 | } | ||||||
10218 | } | ||||||
10219 | } | ||||||
10220 | } | ||||||
10221 | // If the two decls aren't the same MVType, there is no possible error | ||||||
10222 | // condition. | ||||||
10223 | } | ||||||
10224 | } | ||||||
10225 | |||||||
10226 | // Else, this is simply a non-redecl case. Checking the 'value' is only | ||||||
10227 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are | ||||||
10228 | // handled in the attribute adding step. | ||||||
10229 | if (NewMVType == MultiVersionKind::Target && | ||||||
10230 | CheckMultiVersionValue(S, NewFD)) { | ||||||
10231 | NewFD->setInvalidDecl(); | ||||||
10232 | return true; | ||||||
10233 | } | ||||||
10234 | |||||||
10235 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, | ||||||
10236 | !OldFD->isMultiVersion(), NewMVType)) { | ||||||
10237 | NewFD->setInvalidDecl(); | ||||||
10238 | return true; | ||||||
10239 | } | ||||||
10240 | |||||||
10241 | // Permit forward declarations in the case where these two are compatible. | ||||||
10242 | if (!OldFD->isMultiVersion()) { | ||||||
10243 | OldFD->setIsMultiVersion(); | ||||||
10244 | NewFD->setIsMultiVersion(); | ||||||
10245 | Redeclaration = true; | ||||||
10246 | OldDecl = OldFD; | ||||||
10247 | return false; | ||||||
10248 | } | ||||||
10249 | |||||||
10250 | NewFD->setIsMultiVersion(); | ||||||
10251 | Redeclaration = false; | ||||||
10252 | MergeTypeWithPrevious = false; | ||||||
10253 | OldDecl = nullptr; | ||||||
10254 | Previous.clear(); | ||||||
10255 | return false; | ||||||
10256 | } | ||||||
10257 | |||||||
10258 | |||||||
10259 | /// Check the validity of a mulitversion function declaration. | ||||||
10260 | /// Also sets the multiversion'ness' of the function itself. | ||||||
10261 | /// | ||||||
10262 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
10263 | /// | ||||||
10264 | /// Returns true if there was an error, false otherwise. | ||||||
10265 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, | ||||||
10266 | bool &Redeclaration, NamedDecl *&OldDecl, | ||||||
10267 | bool &MergeTypeWithPrevious, | ||||||
10268 | LookupResult &Previous) { | ||||||
10269 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); | ||||||
10270 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); | ||||||
10271 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); | ||||||
10272 | |||||||
10273 | // Mixing Multiversioning types is prohibited. | ||||||
10274 | if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || | ||||||
10275 | (NewCPUDisp && NewCPUSpec)) { | ||||||
10276 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | ||||||
10277 | NewFD->setInvalidDecl(); | ||||||
10278 | return true; | ||||||
10279 | } | ||||||
10280 | |||||||
10281 | MultiVersionKind MVType = NewFD->getMultiVersionKind(); | ||||||
10282 | |||||||
10283 | // Main isn't allowed to become a multiversion function, however it IS | ||||||
10284 | // permitted to have 'main' be marked with the 'target' optimization hint. | ||||||
10285 | if (NewFD->isMain()) { | ||||||
10286 | if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || | ||||||
10287 | MVType == MultiVersionKind::CPUDispatch || | ||||||
10288 | MVType == MultiVersionKind::CPUSpecific) { | ||||||
10289 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); | ||||||
10290 | NewFD->setInvalidDecl(); | ||||||
10291 | return true; | ||||||
10292 | } | ||||||
10293 | return false; | ||||||
10294 | } | ||||||
10295 | |||||||
10296 | if (!OldDecl || !OldDecl->getAsFunction() || | ||||||
10297 | OldDecl->getDeclContext()->getRedeclContext() != | ||||||
10298 | NewFD->getDeclContext()->getRedeclContext()) { | ||||||
10299 | // If there's no previous declaration, AND this isn't attempting to cause | ||||||
10300 | // multiversioning, this isn't an error condition. | ||||||
10301 | if (MVType == MultiVersionKind::None) | ||||||
10302 | return false; | ||||||
10303 | return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); | ||||||
10304 | } | ||||||
10305 | |||||||
10306 | FunctionDecl *OldFD = OldDecl->getAsFunction(); | ||||||
10307 | |||||||
10308 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) | ||||||
10309 | return false; | ||||||
10310 | |||||||
10311 | if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { | ||||||
10312 | S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) | ||||||
10313 | << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); | ||||||
10314 | NewFD->setInvalidDecl(); | ||||||
10315 | return true; | ||||||
10316 | } | ||||||
10317 | |||||||
10318 | // Handle the target potentially causes multiversioning case. | ||||||
10319 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) | ||||||
10320 | return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, | ||||||
10321 | Redeclaration, OldDecl, | ||||||
10322 | MergeTypeWithPrevious, Previous); | ||||||
10323 | |||||||
10324 | // At this point, we have a multiversion function decl (in OldFD) AND an | ||||||
10325 | // appropriate attribute in the current function decl. Resolve that these are | ||||||
10326 | // still compatible with previous declarations. | ||||||
10327 | return CheckMultiVersionAdditionalDecl( | ||||||
10328 | S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, | ||||||
10329 | OldDecl, MergeTypeWithPrevious, Previous); | ||||||
10330 | } | ||||||
10331 | |||||||
10332 | /// Perform semantic checking of a new function declaration. | ||||||
10333 | /// | ||||||
10334 | /// Performs semantic analysis of the new function declaration | ||||||
10335 | /// NewFD. This routine performs all semantic checking that does not | ||||||
10336 | /// require the actual declarator involved in the declaration, and is | ||||||
10337 | /// used both for the declaration of functions as they are parsed | ||||||
10338 | /// (called via ActOnDeclarator) and for the declaration of functions | ||||||
10339 | /// that have been instantiated via C++ template instantiation (called | ||||||
10340 | /// via InstantiateDecl). | ||||||
10341 | /// | ||||||
10342 | /// \param IsMemberSpecialization whether this new function declaration is | ||||||
10343 | /// a member specialization (that replaces any definition provided by the | ||||||
10344 | /// previous declaration). | ||||||
10345 | /// | ||||||
10346 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
10347 | /// | ||||||
10348 | /// \returns true if the function declaration is a redeclaration. | ||||||
10349 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, | ||||||
10350 | LookupResult &Previous, | ||||||
10351 | bool IsMemberSpecialization) { | ||||||
10352 | assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10353, __PRETTY_FUNCTION__)) | ||||||
10353 | "Variably modified return types are not handled here")((!NewFD->getReturnType()->isVariablyModifiedType() && "Variably modified return types are not handled here") ? static_cast <void> (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10353, __PRETTY_FUNCTION__)); | ||||||
10354 | |||||||
10355 | // Determine whether the type of this function should be merged with | ||||||
10356 | // a previous visible declaration. This never happens for functions in C++, | ||||||
10357 | // and always happens in C if the previous declaration was visible. | ||||||
10358 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && | ||||||
10359 | !Previous.isShadowed(); | ||||||
10360 | |||||||
10361 | bool Redeclaration = false; | ||||||
10362 | NamedDecl *OldDecl = nullptr; | ||||||
10363 | bool MayNeedOverloadableChecks = false; | ||||||
10364 | |||||||
10365 | // Merge or overload the declaration with an existing declaration of | ||||||
10366 | // the same name, if appropriate. | ||||||
10367 | if (!Previous.empty()) { | ||||||
10368 | // Determine whether NewFD is an overload of PrevDecl or | ||||||
10369 | // a declaration that requires merging. If it's an overload, | ||||||
10370 | // there's no more work to do here; we'll just add the new | ||||||
10371 | // function to the scope. | ||||||
10372 | if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { | ||||||
10373 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); | ||||||
10374 | if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { | ||||||
10375 | Redeclaration = true; | ||||||
10376 | OldDecl = Candidate; | ||||||
10377 | } | ||||||
10378 | } else { | ||||||
10379 | MayNeedOverloadableChecks = true; | ||||||
10380 | switch (CheckOverload(S, NewFD, Previous, OldDecl, | ||||||
10381 | /*NewIsUsingDecl*/ false)) { | ||||||
10382 | case Ovl_Match: | ||||||
10383 | Redeclaration = true; | ||||||
10384 | break; | ||||||
10385 | |||||||
10386 | case Ovl_NonFunction: | ||||||
10387 | Redeclaration = true; | ||||||
10388 | break; | ||||||
10389 | |||||||
10390 | case Ovl_Overload: | ||||||
10391 | Redeclaration = false; | ||||||
10392 | break; | ||||||
10393 | } | ||||||
10394 | } | ||||||
10395 | } | ||||||
10396 | |||||||
10397 | // Check for a previous extern "C" declaration with this name. | ||||||
10398 | if (!Redeclaration && | ||||||
10399 | checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { | ||||||
10400 | if (!Previous.empty()) { | ||||||
10401 | // This is an extern "C" declaration with the same name as a previous | ||||||
10402 | // declaration, and thus redeclares that entity... | ||||||
10403 | Redeclaration = true; | ||||||
10404 | OldDecl = Previous.getFoundDecl(); | ||||||
10405 | MergeTypeWithPrevious = false; | ||||||
10406 | |||||||
10407 | // ... except in the presence of __attribute__((overloadable)). | ||||||
10408 | if (OldDecl->hasAttr<OverloadableAttr>() || | ||||||
10409 | NewFD->hasAttr<OverloadableAttr>()) { | ||||||
10410 | if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { | ||||||
10411 | MayNeedOverloadableChecks = true; | ||||||
10412 | Redeclaration = false; | ||||||
10413 | OldDecl = nullptr; | ||||||
10414 | } | ||||||
10415 | } | ||||||
10416 | } | ||||||
10417 | } | ||||||
10418 | |||||||
10419 | if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, | ||||||
10420 | MergeTypeWithPrevious, Previous)) | ||||||
10421 | return Redeclaration; | ||||||
10422 | |||||||
10423 | // C++11 [dcl.constexpr]p8: | ||||||
10424 | // A constexpr specifier for a non-static member function that is not | ||||||
10425 | // a constructor declares that member function to be const. | ||||||
10426 | // | ||||||
10427 | // This needs to be delayed until we know whether this is an out-of-line | ||||||
10428 | // definition of a static member function. | ||||||
10429 | // | ||||||
10430 | // This rule is not present in C++1y, so we produce a backwards | ||||||
10431 | // compatibility warning whenever it happens in C++11. | ||||||
10432 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||||
10433 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && | ||||||
10434 | !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && | ||||||
10435 | !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { | ||||||
10436 | CXXMethodDecl *OldMD = nullptr; | ||||||
10437 | if (OldDecl) | ||||||
10438 | OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); | ||||||
10439 | if (!OldMD || !OldMD->isStatic()) { | ||||||
10440 | const FunctionProtoType *FPT = | ||||||
10441 | MD->getType()->castAs<FunctionProtoType>(); | ||||||
10442 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||||
10443 | EPI.TypeQuals.addConst(); | ||||||
10444 | MD->setType(Context.getFunctionType(FPT->getReturnType(), | ||||||
10445 | FPT->getParamTypes(), EPI)); | ||||||
10446 | |||||||
10447 | // Warn that we did this, if we're not performing template instantiation. | ||||||
10448 | // In that case, we'll have warned already when the template was defined. | ||||||
10449 | if (!inTemplateInstantiation()) { | ||||||
10450 | SourceLocation AddConstLoc; | ||||||
10451 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() | ||||||
10452 | .IgnoreParens().getAs<FunctionTypeLoc>()) | ||||||
10453 | AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); | ||||||
10454 | |||||||
10455 | Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) | ||||||
10456 | << FixItHint::CreateInsertion(AddConstLoc, " const"); | ||||||
10457 | } | ||||||
10458 | } | ||||||
10459 | } | ||||||
10460 | |||||||
10461 | if (Redeclaration) { | ||||||
10462 | // NewFD and OldDecl represent declarations that need to be | ||||||
10463 | // merged. | ||||||
10464 | if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { | ||||||
10465 | NewFD->setInvalidDecl(); | ||||||
10466 | return Redeclaration; | ||||||
10467 | } | ||||||
10468 | |||||||
10469 | Previous.clear(); | ||||||
10470 | Previous.addDecl(OldDecl); | ||||||
10471 | |||||||
10472 | if (FunctionTemplateDecl *OldTemplateDecl = | ||||||
10473 | dyn_cast<FunctionTemplateDecl>(OldDecl)) { | ||||||
10474 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); | ||||||
10475 | FunctionTemplateDecl *NewTemplateDecl | ||||||
10476 | = NewFD->getDescribedFunctionTemplate(); | ||||||
10477 | assert(NewTemplateDecl && "Template/non-template mismatch")((NewTemplateDecl && "Template/non-template mismatch" ) ? static_cast<void> (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10477, __PRETTY_FUNCTION__)); | ||||||
10478 | |||||||
10479 | // The call to MergeFunctionDecl above may have created some state in | ||||||
10480 | // NewTemplateDecl that needs to be merged with OldTemplateDecl before we | ||||||
10481 | // can add it as a redeclaration. | ||||||
10482 | NewTemplateDecl->mergePrevDecl(OldTemplateDecl); | ||||||
10483 | |||||||
10484 | NewFD->setPreviousDeclaration(OldFD); | ||||||
10485 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | ||||||
10486 | if (NewFD->isCXXClassMember()) { | ||||||
10487 | NewFD->setAccess(OldTemplateDecl->getAccess()); | ||||||
10488 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); | ||||||
10489 | } | ||||||
10490 | |||||||
10491 | // If this is an explicit specialization of a member that is a function | ||||||
10492 | // template, mark it as a member specialization. | ||||||
10493 | if (IsMemberSpecialization && | ||||||
10494 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { | ||||||
10495 | NewTemplateDecl->setMemberSpecialization(); | ||||||
10496 | assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast <void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10496, __PRETTY_FUNCTION__)); | ||||||
10497 | // Explicit specializations of a member template do not inherit deleted | ||||||
10498 | // status from the parent member template that they are specializing. | ||||||
10499 | if (OldFD->isDeleted()) { | ||||||
10500 | // FIXME: This assert will not hold in the presence of modules. | ||||||
10501 | assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void > (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10501, __PRETTY_FUNCTION__)); | ||||||
10502 | // FIXME: We need an update record for this AST mutation. | ||||||
10503 | OldFD->setDeletedAsWritten(false); | ||||||
10504 | } | ||||||
10505 | } | ||||||
10506 | |||||||
10507 | } else { | ||||||
10508 | if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { | ||||||
10509 | auto *OldFD = cast<FunctionDecl>(OldDecl); | ||||||
10510 | // This needs to happen first so that 'inline' propagates. | ||||||
10511 | NewFD->setPreviousDeclaration(OldFD); | ||||||
10512 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | ||||||
10513 | if (NewFD->isCXXClassMember()) | ||||||
10514 | NewFD->setAccess(OldFD->getAccess()); | ||||||
10515 | } | ||||||
10516 | } | ||||||
10517 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && | ||||||
10518 | !NewFD->getAttr<OverloadableAttr>()) { | ||||||
10519 | assert((Previous.empty() ||(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10520 | llvm::any_of(Previous,(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10521 | [](const NamedDecl *ND) {(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10522 | return ND->hasAttr<OverloadableAttr>();(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10523 | })) &&(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)) | ||||||
10524 | "Non-redecls shouldn't happen without overloadable present")(((Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present") ? static_cast<void> (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10524, __PRETTY_FUNCTION__)); | ||||||
10525 | |||||||
10526 | auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { | ||||||
10527 | const auto *FD = dyn_cast<FunctionDecl>(ND); | ||||||
10528 | return FD && !FD->hasAttr<OverloadableAttr>(); | ||||||
10529 | }); | ||||||
10530 | |||||||
10531 | if (OtherUnmarkedIter != Previous.end()) { | ||||||
10532 | Diag(NewFD->getLocation(), | ||||||
10533 | diag::err_attribute_overloadable_multiple_unmarked_overloads); | ||||||
10534 | Diag((*OtherUnmarkedIter)->getLocation(), | ||||||
10535 | diag::note_attribute_overloadable_prev_overload) | ||||||
10536 | << false; | ||||||
10537 | |||||||
10538 | NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||||
10539 | } | ||||||
10540 | } | ||||||
10541 | |||||||
10542 | // Semantic checking for this function declaration (in isolation). | ||||||
10543 | |||||||
10544 | if (getLangOpts().CPlusPlus) { | ||||||
10545 | // C++-specific checks. | ||||||
10546 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { | ||||||
10547 | CheckConstructor(Constructor); | ||||||
10548 | } else if (CXXDestructorDecl *Destructor = | ||||||
10549 | dyn_cast<CXXDestructorDecl>(NewFD)) { | ||||||
10550 | CXXRecordDecl *Record = Destructor->getParent(); | ||||||
10551 | QualType ClassType = Context.getTypeDeclType(Record); | ||||||
10552 | |||||||
10553 | // FIXME: Shouldn't we be able to perform this check even when the class | ||||||
10554 | // type is dependent? Both gcc and edg can handle that. | ||||||
10555 | if (!ClassType->isDependentType()) { | ||||||
10556 | DeclarationName Name | ||||||
10557 | = Context.DeclarationNames.getCXXDestructorName( | ||||||
10558 | Context.getCanonicalType(ClassType)); | ||||||
10559 | if (NewFD->getDeclName() != Name) { | ||||||
10560 | Diag(NewFD->getLocation(), diag::err_destructor_name); | ||||||
10561 | NewFD->setInvalidDecl(); | ||||||
10562 | return Redeclaration; | ||||||
10563 | } | ||||||
10564 | } | ||||||
10565 | } else if (CXXConversionDecl *Conversion | ||||||
10566 | = dyn_cast<CXXConversionDecl>(NewFD)) { | ||||||
10567 | ActOnConversionDeclarator(Conversion); | ||||||
10568 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { | ||||||
10569 | if (auto *TD = Guide->getDescribedFunctionTemplate()) | ||||||
10570 | CheckDeductionGuideTemplate(TD); | ||||||
10571 | |||||||
10572 | // A deduction guide is not on the list of entities that can be | ||||||
10573 | // explicitly specialized. | ||||||
10574 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) | ||||||
10575 | Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) | ||||||
10576 | << /*explicit specialization*/ 1; | ||||||
10577 | } | ||||||
10578 | |||||||
10579 | // Find any virtual functions that this function overrides. | ||||||
10580 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { | ||||||
10581 | if (!Method->isFunctionTemplateSpecialization() && | ||||||
10582 | !Method->getDescribedFunctionTemplate() && | ||||||
10583 | Method->isCanonicalDecl()) { | ||||||
10584 | if (AddOverriddenMethods(Method->getParent(), Method)) { | ||||||
10585 | // If the function was marked as "static", we have a problem. | ||||||
10586 | if (NewFD->getStorageClass() == SC_Static) { | ||||||
10587 | ReportOverrides(*this, diag::err_static_overrides_virtual, Method); | ||||||
10588 | } | ||||||
10589 | } | ||||||
10590 | } | ||||||
10591 | if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) | ||||||
10592 | // C++2a [class.virtual]p6 | ||||||
10593 | // A virtual method shall not have a requires-clause. | ||||||
10594 | Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), | ||||||
10595 | diag::err_constrained_virtual_method); | ||||||
10596 | |||||||
10597 | if (Method->isStatic()) | ||||||
10598 | checkThisInStaticMemberFunctionType(Method); | ||||||
10599 | } | ||||||
10600 | |||||||
10601 | // Extra checking for C++ overloaded operators (C++ [over.oper]). | ||||||
10602 | if (NewFD->isOverloadedOperator() && | ||||||
10603 | CheckOverloadedOperatorDeclaration(NewFD)) { | ||||||
10604 | NewFD->setInvalidDecl(); | ||||||
10605 | return Redeclaration; | ||||||
10606 | } | ||||||
10607 | |||||||
10608 | // Extra checking for C++0x literal operators (C++0x [over.literal]). | ||||||
10609 | if (NewFD->getLiteralIdentifier() && | ||||||
10610 | CheckLiteralOperatorDeclaration(NewFD)) { | ||||||
10611 | NewFD->setInvalidDecl(); | ||||||
10612 | return Redeclaration; | ||||||
10613 | } | ||||||
10614 | |||||||
10615 | // In C++, check default arguments now that we have merged decls. Unless | ||||||
10616 | // the lexical context is the class, because in this case this is done | ||||||
10617 | // during delayed parsing anyway. | ||||||
10618 | if (!CurContext->isRecord()) | ||||||
10619 | CheckCXXDefaultArguments(NewFD); | ||||||
10620 | |||||||
10621 | // If this function declares a builtin function, check the type of this | ||||||
10622 | // declaration against the expected type for the builtin. | ||||||
10623 | if (unsigned BuiltinID = NewFD->getBuiltinID()) { | ||||||
10624 | ASTContext::GetBuiltinTypeError Error; | ||||||
10625 | LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); | ||||||
10626 | QualType T = Context.GetBuiltinType(BuiltinID, Error); | ||||||
10627 | // If the type of the builtin differs only in its exception | ||||||
10628 | // specification, that's OK. | ||||||
10629 | // FIXME: If the types do differ in this way, it would be better to | ||||||
10630 | // retain the 'noexcept' form of the type. | ||||||
10631 | if (!T.isNull() && | ||||||
10632 | !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, | ||||||
10633 | NewFD->getType())) | ||||||
10634 | // The type of this function differs from the type of the builtin, | ||||||
10635 | // so forget about the builtin entirely. | ||||||
10636 | Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); | ||||||
10637 | } | ||||||
10638 | |||||||
10639 | // If this function is declared as being extern "C", then check to see if | ||||||
10640 | // the function returns a UDT (class, struct, or union type) that is not C | ||||||
10641 | // compatible, and if it does, warn the user. | ||||||
10642 | // But, issue any diagnostic on the first declaration only. | ||||||
10643 | if (Previous.empty() && NewFD->isExternC()) { | ||||||
10644 | QualType R = NewFD->getReturnType(); | ||||||
10645 | if (R->isIncompleteType() && !R->isVoidType()) | ||||||
10646 | Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) | ||||||
10647 | << NewFD << R; | ||||||
10648 | else if (!R.isPODType(Context) && !R->isVoidType() && | ||||||
10649 | !R->isObjCObjectPointerType()) | ||||||
10650 | Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; | ||||||
10651 | } | ||||||
10652 | |||||||
10653 | // C++1z [dcl.fct]p6: | ||||||
10654 | // [...] whether the function has a non-throwing exception-specification | ||||||
10655 | // [is] part of the function type | ||||||
10656 | // | ||||||
10657 | // This results in an ABI break between C++14 and C++17 for functions whose | ||||||
10658 | // declared type includes an exception-specification in a parameter or | ||||||
10659 | // return type. (Exception specifications on the function itself are OK in | ||||||
10660 | // most cases, and exception specifications are not permitted in most other | ||||||
10661 | // contexts where they could make it into a mangling.) | ||||||
10662 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { | ||||||
10663 | auto HasNoexcept = [&](QualType T) -> bool { | ||||||
10664 | // Strip off declarator chunks that could be between us and a function | ||||||
10665 | // type. We don't need to look far, exception specifications are very | ||||||
10666 | // restricted prior to C++17. | ||||||
10667 | if (auto *RT = T->getAs<ReferenceType>()) | ||||||
10668 | T = RT->getPointeeType(); | ||||||
10669 | else if (T->isAnyPointerType()) | ||||||
10670 | T = T->getPointeeType(); | ||||||
10671 | else if (auto *MPT = T->getAs<MemberPointerType>()) | ||||||
10672 | T = MPT->getPointeeType(); | ||||||
10673 | if (auto *FPT = T->getAs<FunctionProtoType>()) | ||||||
10674 | if (FPT->isNothrow()) | ||||||
10675 | return true; | ||||||
10676 | return false; | ||||||
10677 | }; | ||||||
10678 | |||||||
10679 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); | ||||||
10680 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); | ||||||
10681 | for (QualType T : FPT->param_types()) | ||||||
10682 | AnyNoexcept |= HasNoexcept(T); | ||||||
10683 | if (AnyNoexcept) | ||||||
10684 | Diag(NewFD->getLocation(), | ||||||
10685 | diag::warn_cxx17_compat_exception_spec_in_signature) | ||||||
10686 | << NewFD; | ||||||
10687 | } | ||||||
10688 | |||||||
10689 | if (!Redeclaration && LangOpts.CUDA) | ||||||
10690 | checkCUDATargetOverload(NewFD, Previous); | ||||||
10691 | } | ||||||
10692 | return Redeclaration; | ||||||
10693 | } | ||||||
10694 | |||||||
10695 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { | ||||||
10696 | // C++11 [basic.start.main]p3: | ||||||
10697 | // A program that [...] declares main to be inline, static or | ||||||
10698 | // constexpr is ill-formed. | ||||||
10699 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall | ||||||
10700 | // appear in a declaration of main. | ||||||
10701 | // static main is not an error under C99, but we should warn about it. | ||||||
10702 | // We accept _Noreturn main as an extension. | ||||||
10703 | if (FD->getStorageClass() == SC_Static) | ||||||
10704 | Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus | ||||||
10705 | ? diag::err_static_main : diag::warn_static_main) | ||||||
10706 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
10707 | if (FD->isInlineSpecified()) | ||||||
10708 | Diag(DS.getInlineSpecLoc(), diag::err_inline_main) | ||||||
10709 | << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); | ||||||
10710 | if (DS.isNoreturnSpecified()) { | ||||||
10711 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); | ||||||
10712 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); | ||||||
10713 | Diag(NoreturnLoc, diag::ext_noreturn_main); | ||||||
10714 | Diag(NoreturnLoc, diag::note_main_remove_noreturn) | ||||||
10715 | << FixItHint::CreateRemoval(NoreturnRange); | ||||||
10716 | } | ||||||
10717 | if (FD->isConstexpr()) { | ||||||
10718 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) | ||||||
10719 | << FD->isConsteval() | ||||||
10720 | << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); | ||||||
10721 | FD->setConstexprKind(CSK_unspecified); | ||||||
10722 | } | ||||||
10723 | |||||||
10724 | if (getLangOpts().OpenCL) { | ||||||
10725 | Diag(FD->getLocation(), diag::err_opencl_no_main) | ||||||
10726 | << FD->hasAttr<OpenCLKernelAttr>(); | ||||||
10727 | FD->setInvalidDecl(); | ||||||
10728 | return; | ||||||
10729 | } | ||||||
10730 | |||||||
10731 | QualType T = FD->getType(); | ||||||
10732 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10732, __PRETTY_FUNCTION__)); | ||||||
10733 | const FunctionType* FT = T->castAs<FunctionType>(); | ||||||
10734 | |||||||
10735 | // Set default calling convention for main() | ||||||
10736 | if (FT->getCallConv() != CC_C) { | ||||||
10737 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); | ||||||
10738 | FD->setType(QualType(FT, 0)); | ||||||
10739 | T = Context.getCanonicalType(FD->getType()); | ||||||
10740 | } | ||||||
10741 | |||||||
10742 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { | ||||||
10743 | // In C with GNU extensions we allow main() to have non-integer return | ||||||
10744 | // type, but we should warn about the extension, and we disable the | ||||||
10745 | // implicit-return-zero rule. | ||||||
10746 | |||||||
10747 | // GCC in C mode accepts qualified 'int'. | ||||||
10748 | if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) | ||||||
10749 | FD->setHasImplicitReturnZero(true); | ||||||
10750 | else { | ||||||
10751 | Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); | ||||||
10752 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | ||||||
10753 | if (RTRange.isValid()) | ||||||
10754 | Diag(RTRange.getBegin(), diag::note_main_change_return_type) | ||||||
10755 | << FixItHint::CreateReplacement(RTRange, "int"); | ||||||
10756 | } | ||||||
10757 | } else { | ||||||
10758 | // In C and C++, main magically returns 0 if you fall off the end; | ||||||
10759 | // set the flag which tells us that. | ||||||
10760 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. | ||||||
10761 | |||||||
10762 | // All the standards say that main() should return 'int'. | ||||||
10763 | if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) | ||||||
10764 | FD->setHasImplicitReturnZero(true); | ||||||
10765 | else { | ||||||
10766 | // Otherwise, this is just a flat-out error. | ||||||
10767 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | ||||||
10768 | Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) | ||||||
10769 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") | ||||||
10770 | : FixItHint()); | ||||||
10771 | FD->setInvalidDecl(true); | ||||||
10772 | } | ||||||
10773 | } | ||||||
10774 | |||||||
10775 | // Treat protoless main() as nullary. | ||||||
10776 | if (isa<FunctionNoProtoType>(FT)) return; | ||||||
10777 | |||||||
10778 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); | ||||||
10779 | unsigned nparams = FTP->getNumParams(); | ||||||
10780 | assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10780, __PRETTY_FUNCTION__)); | ||||||
10781 | |||||||
10782 | bool HasExtraParameters = (nparams > 3); | ||||||
10783 | |||||||
10784 | if (FTP->isVariadic()) { | ||||||
10785 | Diag(FD->getLocation(), diag::ext_variadic_main); | ||||||
10786 | // FIXME: if we had information about the location of the ellipsis, we | ||||||
10787 | // could add a FixIt hint to remove it as a parameter. | ||||||
10788 | } | ||||||
10789 | |||||||
10790 | // Darwin passes an undocumented fourth argument of type char**. If | ||||||
10791 | // other platforms start sprouting these, the logic below will start | ||||||
10792 | // getting shifty. | ||||||
10793 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) | ||||||
10794 | HasExtraParameters = false; | ||||||
10795 | |||||||
10796 | if (HasExtraParameters) { | ||||||
10797 | Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; | ||||||
10798 | FD->setInvalidDecl(true); | ||||||
10799 | nparams = 3; | ||||||
10800 | } | ||||||
10801 | |||||||
10802 | // FIXME: a lot of the following diagnostics would be improved | ||||||
10803 | // if we had some location information about types. | ||||||
10804 | |||||||
10805 | QualType CharPP = | ||||||
10806 | Context.getPointerType(Context.getPointerType(Context.CharTy)); | ||||||
10807 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; | ||||||
10808 | |||||||
10809 | for (unsigned i = 0; i < nparams; ++i) { | ||||||
10810 | QualType AT = FTP->getParamType(i); | ||||||
10811 | |||||||
10812 | bool mismatch = true; | ||||||
10813 | |||||||
10814 | if (Context.hasSameUnqualifiedType(AT, Expected[i])) | ||||||
10815 | mismatch = false; | ||||||
10816 | else if (Expected[i] == CharPP) { | ||||||
10817 | // As an extension, the following forms are okay: | ||||||
10818 | // char const ** | ||||||
10819 | // char const * const * | ||||||
10820 | // char * const * | ||||||
10821 | |||||||
10822 | QualifierCollector qs; | ||||||
10823 | const PointerType* PT; | ||||||
10824 | if ((PT = qs.strip(AT)->getAs<PointerType>()) && | ||||||
10825 | (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && | ||||||
10826 | Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), | ||||||
10827 | Context.CharTy)) { | ||||||
10828 | qs.removeConst(); | ||||||
10829 | mismatch = !qs.empty(); | ||||||
10830 | } | ||||||
10831 | } | ||||||
10832 | |||||||
10833 | if (mismatch) { | ||||||
10834 | Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; | ||||||
10835 | // TODO: suggest replacing given type with expected type | ||||||
10836 | FD->setInvalidDecl(true); | ||||||
10837 | } | ||||||
10838 | } | ||||||
10839 | |||||||
10840 | if (nparams == 1 && !FD->isInvalidDecl()) { | ||||||
10841 | Diag(FD->getLocation(), diag::warn_main_one_arg); | ||||||
10842 | } | ||||||
10843 | |||||||
10844 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | ||||||
10845 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | ||||||
10846 | FD->setInvalidDecl(); | ||||||
10847 | } | ||||||
10848 | } | ||||||
10849 | |||||||
10850 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { | ||||||
10851 | QualType T = FD->getType(); | ||||||
10852 | assert(T->isFunctionType() && "function decl is not of function type")((T->isFunctionType() && "function decl is not of function type" ) ? static_cast<void> (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 10852, __PRETTY_FUNCTION__)); | ||||||
10853 | const FunctionType *FT = T->castAs<FunctionType>(); | ||||||
10854 | |||||||
10855 | // Set an implicit return of 'zero' if the function can return some integral, | ||||||
10856 | // enumeration, pointer or nullptr type. | ||||||
10857 | if (FT->getReturnType()->isIntegralOrEnumerationType() || | ||||||
10858 | FT->getReturnType()->isAnyPointerType() || | ||||||
10859 | FT->getReturnType()->isNullPtrType()) | ||||||
10860 | // DllMain is exempt because a return value of zero means it failed. | ||||||
10861 | if (FD->getName() != "DllMain") | ||||||
10862 | FD->setHasImplicitReturnZero(true); | ||||||
10863 | |||||||
10864 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | ||||||
10865 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | ||||||
10866 | FD->setInvalidDecl(); | ||||||
10867 | } | ||||||
10868 | } | ||||||
10869 | |||||||
10870 | bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { | ||||||
10871 | // FIXME: Need strict checking. In C89, we need to check for | ||||||
10872 | // any assignment, increment, decrement, function-calls, or | ||||||
10873 | // commas outside of a sizeof. In C99, it's the same list, | ||||||
10874 | // except that the aforementioned are allowed in unevaluated | ||||||
10875 | // expressions. Everything else falls under the | ||||||
10876 | // "may accept other forms of constant expressions" exception. | ||||||
10877 | // (We never end up here for C++, so the constant expression | ||||||
10878 | // rules there don't matter.) | ||||||
10879 | const Expr *Culprit; | ||||||
10880 | if (Init->isConstantInitializer(Context, false, &Culprit)) | ||||||
10881 | return false; | ||||||
10882 | Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) | ||||||
10883 | << Culprit->getSourceRange(); | ||||||
10884 | return true; | ||||||
10885 | } | ||||||
10886 | |||||||
10887 | namespace { | ||||||
10888 | // Visits an initialization expression to see if OrigDecl is evaluated in | ||||||
10889 | // its own initialization and throws a warning if it does. | ||||||
10890 | class SelfReferenceChecker | ||||||
10891 | : public EvaluatedExprVisitor<SelfReferenceChecker> { | ||||||
10892 | Sema &S; | ||||||
10893 | Decl *OrigDecl; | ||||||
10894 | bool isRecordType; | ||||||
10895 | bool isPODType; | ||||||
10896 | bool isReferenceType; | ||||||
10897 | |||||||
10898 | bool isInitList; | ||||||
10899 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | ||||||
10900 | |||||||
10901 | public: | ||||||
10902 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; | ||||||
10903 | |||||||
10904 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), | ||||||
10905 | S(S), OrigDecl(OrigDecl) { | ||||||
10906 | isPODType = false; | ||||||
10907 | isRecordType = false; | ||||||
10908 | isReferenceType = false; | ||||||
10909 | isInitList = false; | ||||||
10910 | if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { | ||||||
10911 | isPODType = VD->getType().isPODType(S.Context); | ||||||
10912 | isRecordType = VD->getType()->isRecordType(); | ||||||
10913 | isReferenceType = VD->getType()->isReferenceType(); | ||||||
10914 | } | ||||||
10915 | } | ||||||
10916 | |||||||
10917 | // For most expressions, just call the visitor. For initializer lists, | ||||||
10918 | // track the index of the field being initialized since fields are | ||||||
10919 | // initialized in order allowing use of previously initialized fields. | ||||||
10920 | void CheckExpr(Expr *E) { | ||||||
10921 | InitListExpr *InitList = dyn_cast<InitListExpr>(E); | ||||||
10922 | if (!InitList) { | ||||||
10923 | Visit(E); | ||||||
10924 | return; | ||||||
10925 | } | ||||||
10926 | |||||||
10927 | // Track and increment the index here. | ||||||
10928 | isInitList = true; | ||||||
10929 | InitFieldIndex.push_back(0); | ||||||
10930 | for (auto Child : InitList->children()) { | ||||||
10931 | CheckExpr(cast<Expr>(Child)); | ||||||
10932 | ++InitFieldIndex.back(); | ||||||
10933 | } | ||||||
10934 | InitFieldIndex.pop_back(); | ||||||
10935 | } | ||||||
10936 | |||||||
10937 | // Returns true if MemberExpr is checked and no further checking is needed. | ||||||
10938 | // Returns false if additional checking is required. | ||||||
10939 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { | ||||||
10940 | llvm::SmallVector<FieldDecl*, 4> Fields; | ||||||
10941 | Expr *Base = E; | ||||||
10942 | bool ReferenceField = false; | ||||||
10943 | |||||||
10944 | // Get the field members used. | ||||||
10945 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
10946 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | ||||||
10947 | if (!FD) | ||||||
10948 | return false; | ||||||
10949 | Fields.push_back(FD); | ||||||
10950 | if (FD->getType()->isReferenceType()) | ||||||
10951 | ReferenceField = true; | ||||||
10952 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
10953 | } | ||||||
10954 | |||||||
10955 | // Keep checking only if the base Decl is the same. | ||||||
10956 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); | ||||||
10957 | if (!DRE || DRE->getDecl() != OrigDecl) | ||||||
10958 | return false; | ||||||
10959 | |||||||
10960 | // A reference field can be bound to an unininitialized field. | ||||||
10961 | if (CheckReference && !ReferenceField) | ||||||
10962 | return true; | ||||||
10963 | |||||||
10964 | // Convert FieldDecls to their index number. | ||||||
10965 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | ||||||
10966 | for (const FieldDecl *I : llvm::reverse(Fields)) | ||||||
10967 | UsedFieldIndex.push_back(I->getFieldIndex()); | ||||||
10968 | |||||||
10969 | // See if a warning is needed by checking the first difference in index | ||||||
10970 | // numbers. If field being used has index less than the field being | ||||||
10971 | // initialized, then the use is safe. | ||||||
10972 | for (auto UsedIter = UsedFieldIndex.begin(), | ||||||
10973 | UsedEnd = UsedFieldIndex.end(), | ||||||
10974 | OrigIter = InitFieldIndex.begin(), | ||||||
10975 | OrigEnd = InitFieldIndex.end(); | ||||||
10976 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | ||||||
10977 | if (*UsedIter < *OrigIter) | ||||||
10978 | return true; | ||||||
10979 | if (*UsedIter > *OrigIter) | ||||||
10980 | break; | ||||||
10981 | } | ||||||
10982 | |||||||
10983 | // TODO: Add a different warning which will print the field names. | ||||||
10984 | HandleDeclRefExpr(DRE); | ||||||
10985 | return true; | ||||||
10986 | } | ||||||
10987 | |||||||
10988 | // For most expressions, the cast is directly above the DeclRefExpr. | ||||||
10989 | // For conditional operators, the cast can be outside the conditional | ||||||
10990 | // operator if both expressions are DeclRefExpr's. | ||||||
10991 | void HandleValue(Expr *E) { | ||||||
10992 | E = E->IgnoreParens(); | ||||||
10993 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { | ||||||
10994 | HandleDeclRefExpr(DRE); | ||||||
10995 | return; | ||||||
10996 | } | ||||||
10997 | |||||||
10998 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | ||||||
10999 | Visit(CO->getCond()); | ||||||
11000 | HandleValue(CO->getTrueExpr()); | ||||||
11001 | HandleValue(CO->getFalseExpr()); | ||||||
11002 | return; | ||||||
11003 | } | ||||||
11004 | |||||||
11005 | if (BinaryConditionalOperator *BCO = | ||||||
11006 | dyn_cast<BinaryConditionalOperator>(E)) { | ||||||
11007 | Visit(BCO->getCond()); | ||||||
11008 | HandleValue(BCO->getFalseExpr()); | ||||||
11009 | return; | ||||||
11010 | } | ||||||
11011 | |||||||
11012 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | ||||||
11013 | HandleValue(OVE->getSourceExpr()); | ||||||
11014 | return; | ||||||
11015 | } | ||||||
11016 | |||||||
11017 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | ||||||
11018 | if (BO->getOpcode() == BO_Comma) { | ||||||
11019 | Visit(BO->getLHS()); | ||||||
11020 | HandleValue(BO->getRHS()); | ||||||
11021 | return; | ||||||
11022 | } | ||||||
11023 | } | ||||||
11024 | |||||||
11025 | if (isa<MemberExpr>(E)) { | ||||||
11026 | if (isInitList) { | ||||||
11027 | if (CheckInitListMemberExpr(cast<MemberExpr>(E), | ||||||
11028 | false /*CheckReference*/)) | ||||||
11029 | return; | ||||||
11030 | } | ||||||
11031 | |||||||
11032 | Expr *Base = E->IgnoreParenImpCasts(); | ||||||
11033 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
11034 | // Check for static member variables and don't warn on them. | ||||||
11035 | if (!isa<FieldDecl>(ME->getMemberDecl())) | ||||||
11036 | return; | ||||||
11037 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
11038 | } | ||||||
11039 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) | ||||||
11040 | HandleDeclRefExpr(DRE); | ||||||
11041 | return; | ||||||
11042 | } | ||||||
11043 | |||||||
11044 | Visit(E); | ||||||
11045 | } | ||||||
11046 | |||||||
11047 | // Reference types not handled in HandleValue are handled here since all | ||||||
11048 | // uses of references are bad, not just r-value uses. | ||||||
11049 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||||
11050 | if (isReferenceType) | ||||||
11051 | HandleDeclRefExpr(E); | ||||||
11052 | } | ||||||
11053 | |||||||
11054 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||||
11055 | if (E->getCastKind() == CK_LValueToRValue) { | ||||||
11056 | HandleValue(E->getSubExpr()); | ||||||
11057 | return; | ||||||
11058 | } | ||||||
11059 | |||||||
11060 | Inherited::VisitImplicitCastExpr(E); | ||||||
11061 | } | ||||||
11062 | |||||||
11063 | void VisitMemberExpr(MemberExpr *E) { | ||||||
11064 | if (isInitList) { | ||||||
11065 | if (CheckInitListMemberExpr(E, true /*CheckReference*/)) | ||||||
11066 | return; | ||||||
11067 | } | ||||||
11068 | |||||||
11069 | // Don't warn on arrays since they can be treated as pointers. | ||||||
11070 | if (E->getType()->canDecayToPointerType()) return; | ||||||
11071 | |||||||
11072 | // Warn when a non-static method call is followed by non-static member | ||||||
11073 | // field accesses, which is followed by a DeclRefExpr. | ||||||
11074 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); | ||||||
11075 | bool Warn = (MD && !MD->isStatic()); | ||||||
11076 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); | ||||||
11077 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
11078 | if (!isa<FieldDecl>(ME->getMemberDecl())) | ||||||
11079 | Warn = false; | ||||||
11080 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
11081 | } | ||||||
11082 | |||||||
11083 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { | ||||||
11084 | if (Warn) | ||||||
11085 | HandleDeclRefExpr(DRE); | ||||||
11086 | return; | ||||||
11087 | } | ||||||
11088 | |||||||
11089 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. | ||||||
11090 | // Visit that expression. | ||||||
11091 | Visit(Base); | ||||||
11092 | } | ||||||
11093 | |||||||
11094 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||||
11095 | Expr *Callee = E->getCallee(); | ||||||
11096 | |||||||
11097 | if (isa<UnresolvedLookupExpr>(Callee)) | ||||||
11098 | return Inherited::VisitCXXOperatorCallExpr(E); | ||||||
11099 | |||||||
11100 | Visit(Callee); | ||||||
11101 | for (auto Arg: E->arguments()) | ||||||
11102 | HandleValue(Arg->IgnoreParenImpCasts()); | ||||||
11103 | } | ||||||
11104 | |||||||
11105 | void VisitUnaryOperator(UnaryOperator *E) { | ||||||
11106 | // For POD record types, addresses of its own members are well-defined. | ||||||
11107 | if (E->getOpcode() == UO_AddrOf && isRecordType && | ||||||
11108 | isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { | ||||||
11109 | if (!isPODType) | ||||||
11110 | HandleValue(E->getSubExpr()); | ||||||
11111 | return; | ||||||
11112 | } | ||||||
11113 | |||||||
11114 | if (E->isIncrementDecrementOp()) { | ||||||
11115 | HandleValue(E->getSubExpr()); | ||||||
11116 | return; | ||||||
11117 | } | ||||||
11118 | |||||||
11119 | Inherited::VisitUnaryOperator(E); | ||||||
11120 | } | ||||||
11121 | |||||||
11122 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} | ||||||
11123 | |||||||
11124 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | ||||||
11125 | if (E->getConstructor()->isCopyConstructor()) { | ||||||
11126 | Expr *ArgExpr = E->getArg(0); | ||||||
11127 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | ||||||
11128 | if (ILE->getNumInits() == 1) | ||||||
11129 | ArgExpr = ILE->getInit(0); | ||||||
11130 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | ||||||
11131 | if (ICE->getCastKind() == CK_NoOp) | ||||||
11132 | ArgExpr = ICE->getSubExpr(); | ||||||
11133 | HandleValue(ArgExpr); | ||||||
11134 | return; | ||||||
11135 | } | ||||||
11136 | Inherited::VisitCXXConstructExpr(E); | ||||||
11137 | } | ||||||
11138 | |||||||
11139 | void VisitCallExpr(CallExpr *E) { | ||||||
11140 | // Treat std::move as a use. | ||||||
11141 | if (E->isCallToStdMove()) { | ||||||
11142 | HandleValue(E->getArg(0)); | ||||||
11143 | return; | ||||||
11144 | } | ||||||
11145 | |||||||
11146 | Inherited::VisitCallExpr(E); | ||||||
11147 | } | ||||||
11148 | |||||||
11149 | void VisitBinaryOperator(BinaryOperator *E) { | ||||||
11150 | if (E->isCompoundAssignmentOp()) { | ||||||
11151 | HandleValue(E->getLHS()); | ||||||
11152 | Visit(E->getRHS()); | ||||||
11153 | return; | ||||||
11154 | } | ||||||
11155 | |||||||
11156 | Inherited::VisitBinaryOperator(E); | ||||||
11157 | } | ||||||
11158 | |||||||
11159 | // A custom visitor for BinaryConditionalOperator is needed because the | ||||||
11160 | // regular visitor would check the condition and true expression separately | ||||||
11161 | // but both point to the same place giving duplicate diagnostics. | ||||||
11162 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { | ||||||
11163 | Visit(E->getCond()); | ||||||
11164 | Visit(E->getFalseExpr()); | ||||||
11165 | } | ||||||
11166 | |||||||
11167 | void HandleDeclRefExpr(DeclRefExpr *DRE) { | ||||||
11168 | Decl* ReferenceDecl = DRE->getDecl(); | ||||||
11169 | if (OrigDecl != ReferenceDecl) return; | ||||||
11170 | unsigned diag; | ||||||
11171 | if (isReferenceType) { | ||||||
11172 | diag = diag::warn_uninit_self_reference_in_reference_init; | ||||||
11173 | } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { | ||||||
11174 | diag = diag::warn_static_self_reference_in_init; | ||||||
11175 | } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || | ||||||
11176 | isa<NamespaceDecl>(OrigDecl->getDeclContext()) || | ||||||
11177 | DRE->getDecl()->getType()->isRecordType()) { | ||||||
11178 | diag = diag::warn_uninit_self_reference_in_init; | ||||||
11179 | } else { | ||||||
11180 | // Local variables will be handled by the CFG analysis. | ||||||
11181 | return; | ||||||
11182 | } | ||||||
11183 | |||||||
11184 | S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, | ||||||
11185 | S.PDiag(diag) | ||||||
11186 | << DRE->getDecl() << OrigDecl->getLocation() | ||||||
11187 | << DRE->getSourceRange()); | ||||||
11188 | } | ||||||
11189 | }; | ||||||
11190 | |||||||
11191 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. | ||||||
11192 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, | ||||||
11193 | bool DirectInit) { | ||||||
11194 | // Parameters arguments are occassionially constructed with itself, | ||||||
11195 | // for instance, in recursive functions. Skip them. | ||||||
11196 | if (isa<ParmVarDecl>(OrigDecl)) | ||||||
11197 | return; | ||||||
11198 | |||||||
11199 | E = E->IgnoreParens(); | ||||||
11200 | |||||||
11201 | // Skip checking T a = a where T is not a record or reference type. | ||||||
11202 | // Doing so is a way to silence uninitialized warnings. | ||||||
11203 | if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) | ||||||
11204 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||||
11205 | if (ICE->getCastKind() == CK_LValueToRValue) | ||||||
11206 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) | ||||||
11207 | if (DRE->getDecl() == OrigDecl) | ||||||
11208 | return; | ||||||
11209 | |||||||
11210 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); | ||||||
11211 | } | ||||||
11212 | } // end anonymous namespace | ||||||
11213 | |||||||
11214 | namespace { | ||||||
11215 | // Simple wrapper to add the name of a variable or (if no variable is | ||||||
11216 | // available) a DeclarationName into a diagnostic. | ||||||
11217 | struct VarDeclOrName { | ||||||
11218 | VarDecl *VDecl; | ||||||
11219 | DeclarationName Name; | ||||||
11220 | |||||||
11221 | friend const Sema::SemaDiagnosticBuilder & | ||||||
11222 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { | ||||||
11223 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; | ||||||
11224 | } | ||||||
11225 | }; | ||||||
11226 | } // end anonymous namespace | ||||||
11227 | |||||||
11228 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, | ||||||
11229 | DeclarationName Name, QualType Type, | ||||||
11230 | TypeSourceInfo *TSI, | ||||||
11231 | SourceRange Range, bool DirectInit, | ||||||
11232 | Expr *Init) { | ||||||
11233 | bool IsInitCapture = !VDecl; | ||||||
11234 | assert((!VDecl || !VDecl->isInitCapture()) &&(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11235, __PRETTY_FUNCTION__)) | ||||||
11235 | "init captures are expected to be deduced prior to initialization")(((!VDecl || !VDecl->isInitCapture()) && "init captures are expected to be deduced prior to initialization" ) ? static_cast<void> (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11235, __PRETTY_FUNCTION__)); | ||||||
11236 | |||||||
11237 | VarDeclOrName VN{VDecl, Name}; | ||||||
11238 | |||||||
11239 | DeducedType *Deduced = Type->getContainedDeducedType(); | ||||||
11240 | assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((Deduced && "deduceVarTypeFromInitializer for non-deduced type" ) ? static_cast<void> (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11240, __PRETTY_FUNCTION__)); | ||||||
11241 | |||||||
11242 | // C++11 [dcl.spec.auto]p3 | ||||||
11243 | if (!Init) { | ||||||
11244 | assert(VDecl && "no init for init capture deduction?")((VDecl && "no init for init capture deduction?") ? static_cast <void> (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11244, __PRETTY_FUNCTION__)); | ||||||
11245 | |||||||
11246 | // Except for class argument deduction, and then for an initializing | ||||||
11247 | // declaration only, i.e. no static at class scope or extern. | ||||||
11248 | if (!isa<DeducedTemplateSpecializationType>(Deduced) || | ||||||
11249 | VDecl->hasExternalStorage() || | ||||||
11250 | VDecl->isStaticDataMember()) { | ||||||
11251 | Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) | ||||||
11252 | << VDecl->getDeclName() << Type; | ||||||
11253 | return QualType(); | ||||||
11254 | } | ||||||
11255 | } | ||||||
11256 | |||||||
11257 | ArrayRef<Expr*> DeduceInits; | ||||||
11258 | if (Init) | ||||||
11259 | DeduceInits = Init; | ||||||
11260 | |||||||
11261 | if (DirectInit) { | ||||||
11262 | if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) | ||||||
11263 | DeduceInits = PL->exprs(); | ||||||
11264 | } | ||||||
11265 | |||||||
11266 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | ||||||
11267 | assert(VDecl && "non-auto type for init capture deduction?")((VDecl && "non-auto type for init capture deduction?" ) ? static_cast<void> (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11267, __PRETTY_FUNCTION__)); | ||||||
11268 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | ||||||
11269 | InitializationKind Kind = InitializationKind::CreateForInit( | ||||||
11270 | VDecl->getLocation(), DirectInit, Init); | ||||||
11271 | // FIXME: Initialization should not be taking a mutable list of inits. | ||||||
11272 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); | ||||||
11273 | return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, | ||||||
11274 | InitsCopy); | ||||||
11275 | } | ||||||
11276 | |||||||
11277 | if (DirectInit) { | ||||||
11278 | if (auto *IL = dyn_cast<InitListExpr>(Init)) | ||||||
11279 | DeduceInits = IL->inits(); | ||||||
11280 | } | ||||||
11281 | |||||||
11282 | // Deduction only works if we have exactly one source expression. | ||||||
11283 | if (DeduceInits.empty()) { | ||||||
11284 | // It isn't possible to write this directly, but it is possible to | ||||||
11285 | // end up in this situation with "auto x(some_pack...);" | ||||||
11286 | Diag(Init->getBeginLoc(), IsInitCapture | ||||||
11287 | ? diag::err_init_capture_no_expression | ||||||
11288 | : diag::err_auto_var_init_no_expression) | ||||||
11289 | << VN << Type << Range; | ||||||
11290 | return QualType(); | ||||||
11291 | } | ||||||
11292 | |||||||
11293 | if (DeduceInits.size() > 1) { | ||||||
11294 | Diag(DeduceInits[1]->getBeginLoc(), | ||||||
11295 | IsInitCapture ? diag::err_init_capture_multiple_expressions | ||||||
11296 | : diag::err_auto_var_init_multiple_expressions) | ||||||
11297 | << VN << Type << Range; | ||||||
11298 | return QualType(); | ||||||
11299 | } | ||||||
11300 | |||||||
11301 | Expr *DeduceInit = DeduceInits[0]; | ||||||
11302 | if (DirectInit && isa<InitListExpr>(DeduceInit)) { | ||||||
11303 | Diag(Init->getBeginLoc(), IsInitCapture | ||||||
11304 | ? diag::err_init_capture_paren_braces | ||||||
11305 | : diag::err_auto_var_init_paren_braces) | ||||||
11306 | << isa<InitListExpr>(Init) << VN << Type << Range; | ||||||
11307 | return QualType(); | ||||||
11308 | } | ||||||
11309 | |||||||
11310 | // Expressions default to 'id' when we're in a debugger. | ||||||
11311 | bool DefaultedAnyToId = false; | ||||||
11312 | if (getLangOpts().DebuggerCastResultToId && | ||||||
11313 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { | ||||||
11314 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | ||||||
11315 | if (Result.isInvalid()) { | ||||||
11316 | return QualType(); | ||||||
11317 | } | ||||||
11318 | Init = Result.get(); | ||||||
11319 | DefaultedAnyToId = true; | ||||||
11320 | } | ||||||
11321 | |||||||
11322 | // C++ [dcl.decomp]p1: | ||||||
11323 | // If the assignment-expression [...] has array type A and no ref-qualifier | ||||||
11324 | // is present, e has type cv A | ||||||
11325 | if (VDecl && isa<DecompositionDecl>(VDecl) && | ||||||
11326 | Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && | ||||||
11327 | DeduceInit->getType()->isConstantArrayType()) | ||||||
11328 | return Context.getQualifiedType(DeduceInit->getType(), | ||||||
11329 | Type.getQualifiers()); | ||||||
11330 | |||||||
11331 | QualType DeducedType; | ||||||
11332 | if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { | ||||||
11333 | if (!IsInitCapture) | ||||||
11334 | DiagnoseAutoDeductionFailure(VDecl, DeduceInit); | ||||||
11335 | else if (isa<InitListExpr>(Init)) | ||||||
11336 | Diag(Range.getBegin(), | ||||||
11337 | diag::err_init_capture_deduction_failure_from_init_list) | ||||||
11338 | << VN | ||||||
11339 | << (DeduceInit->getType().isNull() ? TSI->getType() | ||||||
11340 | : DeduceInit->getType()) | ||||||
11341 | << DeduceInit->getSourceRange(); | ||||||
11342 | else | ||||||
11343 | Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) | ||||||
11344 | << VN << TSI->getType() | ||||||
11345 | << (DeduceInit->getType().isNull() ? TSI->getType() | ||||||
11346 | : DeduceInit->getType()) | ||||||
11347 | << DeduceInit->getSourceRange(); | ||||||
11348 | } | ||||||
11349 | |||||||
11350 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using | ||||||
11351 | // 'id' instead of a specific object type prevents most of our usual | ||||||
11352 | // checks. | ||||||
11353 | // We only want to warn outside of template instantiations, though: | ||||||
11354 | // inside a template, the 'id' could have come from a parameter. | ||||||
11355 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && | ||||||
11356 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { | ||||||
11357 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); | ||||||
11358 | Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; | ||||||
11359 | } | ||||||
11360 | |||||||
11361 | return DeducedType; | ||||||
11362 | } | ||||||
11363 | |||||||
11364 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, | ||||||
11365 | Expr *Init) { | ||||||
11366 | QualType DeducedType = deduceVarTypeFromInitializer( | ||||||
11367 | VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), | ||||||
11368 | VDecl->getSourceRange(), DirectInit, Init); | ||||||
11369 | if (DeducedType.isNull()) { | ||||||
11370 | VDecl->setInvalidDecl(); | ||||||
11371 | return true; | ||||||
11372 | } | ||||||
11373 | |||||||
11374 | VDecl->setType(DeducedType); | ||||||
11375 | assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11375, __PRETTY_FUNCTION__)); | ||||||
11376 | |||||||
11377 | // In ARC, infer lifetime. | ||||||
11378 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) | ||||||
11379 | VDecl->setInvalidDecl(); | ||||||
11380 | |||||||
11381 | if (getLangOpts().OpenCL) | ||||||
11382 | deduceOpenCLAddressSpace(VDecl); | ||||||
11383 | |||||||
11384 | // If this is a redeclaration, check that the type we just deduced matches | ||||||
11385 | // the previously declared type. | ||||||
11386 | if (VarDecl *Old = VDecl->getPreviousDecl()) { | ||||||
11387 | // We never need to merge the type, because we cannot form an incomplete | ||||||
11388 | // array of auto, nor deduce such a type. | ||||||
11389 | MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); | ||||||
11390 | } | ||||||
11391 | |||||||
11392 | // Check the deduced type is valid for a variable declaration. | ||||||
11393 | CheckVariableDeclarationType(VDecl); | ||||||
11394 | return VDecl->isInvalidDecl(); | ||||||
11395 | } | ||||||
11396 | |||||||
11397 | void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, | ||||||
11398 | SourceLocation Loc) { | ||||||
11399 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||||
11400 | Init = CE->getSubExpr(); | ||||||
11401 | |||||||
11402 | QualType InitType = Init->getType(); | ||||||
11403 | assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11405, __PRETTY_FUNCTION__)) | ||||||
11404 | InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11405, __PRETTY_FUNCTION__)) | ||||||
11405 | "shouldn't be called if type doesn't have a non-trivial C struct")(((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && "shouldn't be called if type doesn't have a non-trivial C struct" ) ? static_cast<void> (0) : __assert_fail ("(InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || InitType.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C struct\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11405, __PRETTY_FUNCTION__)); | ||||||
11406 | if (auto *ILE = dyn_cast<InitListExpr>(Init)) { | ||||||
11407 | for (auto I : ILE->inits()) { | ||||||
11408 | if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && | ||||||
11409 | !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11410 | continue; | ||||||
11411 | SourceLocation SL = I->getExprLoc(); | ||||||
11412 | checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); | ||||||
11413 | } | ||||||
11414 | return; | ||||||
11415 | } | ||||||
11416 | |||||||
11417 | if (isa<ImplicitValueInitExpr>(Init)) { | ||||||
11418 | if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
11419 | checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, | ||||||
11420 | NTCUK_Init); | ||||||
11421 | } else { | ||||||
11422 | // Assume all other explicit initializers involving copying some existing | ||||||
11423 | // object. | ||||||
11424 | // TODO: ignore any explicit initializers where we can guarantee | ||||||
11425 | // copy-elision. | ||||||
11426 | if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11427 | checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); | ||||||
11428 | } | ||||||
11429 | } | ||||||
11430 | |||||||
11431 | namespace { | ||||||
11432 | |||||||
11433 | bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { | ||||||
11434 | // Ignore unavailable fields. A field can be marked as unavailable explicitly | ||||||
11435 | // in the source code or implicitly by the compiler if it is in a union | ||||||
11436 | // defined in a system header and has non-trivial ObjC ownership | ||||||
11437 | // qualifications. We don't want those fields to participate in determining | ||||||
11438 | // whether the containing union is non-trivial. | ||||||
11439 | return FD->hasAttr<UnavailableAttr>(); | ||||||
11440 | } | ||||||
11441 | |||||||
11442 | struct DiagNonTrivalCUnionDefaultInitializeVisitor | ||||||
11443 | : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | ||||||
11444 | void> { | ||||||
11445 | using Super = | ||||||
11446 | DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | ||||||
11447 | void>; | ||||||
11448 | |||||||
11449 | DiagNonTrivalCUnionDefaultInitializeVisitor( | ||||||
11450 | QualType OrigTy, SourceLocation OrigLoc, | ||||||
11451 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | ||||||
11452 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11453 | |||||||
11454 | void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, | ||||||
11455 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11456 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11457 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11458 | InNonTrivialUnion); | ||||||
11459 | return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); | ||||||
11460 | } | ||||||
11461 | |||||||
11462 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11463 | bool InNonTrivialUnion) { | ||||||
11464 | if (InNonTrivialUnion) | ||||||
11465 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11466 | << 1 << 0 << QT << FD->getName(); | ||||||
11467 | } | ||||||
11468 | |||||||
11469 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11470 | if (InNonTrivialUnion) | ||||||
11471 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11472 | << 1 << 0 << QT << FD->getName(); | ||||||
11473 | } | ||||||
11474 | |||||||
11475 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11476 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11477 | if (RD->isUnion()) { | ||||||
11478 | if (OrigLoc.isValid()) { | ||||||
11479 | bool IsUnion = false; | ||||||
11480 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11481 | IsUnion = OrigRD->isUnion(); | ||||||
11482 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11483 | << 0 << OrigTy << IsUnion << UseContext; | ||||||
11484 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11485 | OrigLoc = SourceLocation(); | ||||||
11486 | } | ||||||
11487 | InNonTrivialUnion = true; | ||||||
11488 | } | ||||||
11489 | |||||||
11490 | if (InNonTrivialUnion) | ||||||
11491 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11492 | << 0 << 0 << QT.getUnqualifiedType() << ""; | ||||||
11493 | |||||||
11494 | for (const FieldDecl *FD : RD->fields()) | ||||||
11495 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11496 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11497 | } | ||||||
11498 | |||||||
11499 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11500 | |||||||
11501 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11502 | // non-trivial C union. | ||||||
11503 | QualType OrigTy; | ||||||
11504 | SourceLocation OrigLoc; | ||||||
11505 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11506 | Sema &S; | ||||||
11507 | }; | ||||||
11508 | |||||||
11509 | struct DiagNonTrivalCUnionDestructedTypeVisitor | ||||||
11510 | : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { | ||||||
11511 | using Super = | ||||||
11512 | DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; | ||||||
11513 | |||||||
11514 | DiagNonTrivalCUnionDestructedTypeVisitor( | ||||||
11515 | QualType OrigTy, SourceLocation OrigLoc, | ||||||
11516 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | ||||||
11517 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11518 | |||||||
11519 | void visitWithKind(QualType::DestructionKind DK, QualType QT, | ||||||
11520 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11521 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11522 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11523 | InNonTrivialUnion); | ||||||
11524 | return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); | ||||||
11525 | } | ||||||
11526 | |||||||
11527 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11528 | bool InNonTrivialUnion) { | ||||||
11529 | if (InNonTrivialUnion) | ||||||
11530 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11531 | << 1 << 1 << QT << FD->getName(); | ||||||
11532 | } | ||||||
11533 | |||||||
11534 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11535 | if (InNonTrivialUnion) | ||||||
11536 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11537 | << 1 << 1 << QT << FD->getName(); | ||||||
11538 | } | ||||||
11539 | |||||||
11540 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11541 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11542 | if (RD->isUnion()) { | ||||||
11543 | if (OrigLoc.isValid()) { | ||||||
11544 | bool IsUnion = false; | ||||||
11545 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11546 | IsUnion = OrigRD->isUnion(); | ||||||
11547 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11548 | << 1 << OrigTy << IsUnion << UseContext; | ||||||
11549 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11550 | OrigLoc = SourceLocation(); | ||||||
11551 | } | ||||||
11552 | InNonTrivialUnion = true; | ||||||
11553 | } | ||||||
11554 | |||||||
11555 | if (InNonTrivialUnion) | ||||||
11556 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11557 | << 0 << 1 << QT.getUnqualifiedType() << ""; | ||||||
11558 | |||||||
11559 | for (const FieldDecl *FD : RD->fields()) | ||||||
11560 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11561 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11562 | } | ||||||
11563 | |||||||
11564 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11565 | void visitCXXDestructor(QualType QT, const FieldDecl *FD, | ||||||
11566 | bool InNonTrivialUnion) {} | ||||||
11567 | |||||||
11568 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11569 | // non-trivial C union. | ||||||
11570 | QualType OrigTy; | ||||||
11571 | SourceLocation OrigLoc; | ||||||
11572 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11573 | Sema &S; | ||||||
11574 | }; | ||||||
11575 | |||||||
11576 | struct DiagNonTrivalCUnionCopyVisitor | ||||||
11577 | : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { | ||||||
11578 | using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; | ||||||
11579 | |||||||
11580 | DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, | ||||||
11581 | Sema::NonTrivialCUnionContext UseContext, | ||||||
11582 | Sema &S) | ||||||
11583 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11584 | |||||||
11585 | void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, | ||||||
11586 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11587 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11588 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11589 | InNonTrivialUnion); | ||||||
11590 | return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); | ||||||
11591 | } | ||||||
11592 | |||||||
11593 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11594 | bool InNonTrivialUnion) { | ||||||
11595 | if (InNonTrivialUnion) | ||||||
11596 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11597 | << 1 << 2 << QT << FD->getName(); | ||||||
11598 | } | ||||||
11599 | |||||||
11600 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11601 | if (InNonTrivialUnion) | ||||||
11602 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11603 | << 1 << 2 << QT << FD->getName(); | ||||||
11604 | } | ||||||
11605 | |||||||
11606 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11607 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11608 | if (RD->isUnion()) { | ||||||
11609 | if (OrigLoc.isValid()) { | ||||||
11610 | bool IsUnion = false; | ||||||
11611 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11612 | IsUnion = OrigRD->isUnion(); | ||||||
11613 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11614 | << 2 << OrigTy << IsUnion << UseContext; | ||||||
11615 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11616 | OrigLoc = SourceLocation(); | ||||||
11617 | } | ||||||
11618 | InNonTrivialUnion = true; | ||||||
11619 | } | ||||||
11620 | |||||||
11621 | if (InNonTrivialUnion) | ||||||
11622 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11623 | << 0 << 2 << QT.getUnqualifiedType() << ""; | ||||||
11624 | |||||||
11625 | for (const FieldDecl *FD : RD->fields()) | ||||||
11626 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11627 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11628 | } | ||||||
11629 | |||||||
11630 | void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, | ||||||
11631 | const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11632 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11633 | void visitVolatileTrivial(QualType QT, const FieldDecl *FD, | ||||||
11634 | bool InNonTrivialUnion) {} | ||||||
11635 | |||||||
11636 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11637 | // non-trivial C union. | ||||||
11638 | QualType OrigTy; | ||||||
11639 | SourceLocation OrigLoc; | ||||||
11640 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11641 | Sema &S; | ||||||
11642 | }; | ||||||
11643 | |||||||
11644 | } // namespace | ||||||
11645 | |||||||
11646 | void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, | ||||||
11647 | NonTrivialCUnionContext UseContext, | ||||||
11648 | unsigned NonTrivialKind) { | ||||||
11649 | assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11652, __PRETTY_FUNCTION__)) | ||||||
11650 | QT.hasNonTrivialToPrimitiveDestructCUnion() ||(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11652, __PRETTY_FUNCTION__)) | ||||||
11651 | QT.hasNonTrivialToPrimitiveCopyCUnion()) &&(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11652, __PRETTY_FUNCTION__)) | ||||||
11652 | "shouldn't be called if type doesn't have a non-trivial C union")(((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT .hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion ()) && "shouldn't be called if type doesn't have a non-trivial C union" ) ? static_cast<void> (0) : __assert_fail ("(QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || QT.hasNonTrivialToPrimitiveDestructCUnion() || QT.hasNonTrivialToPrimitiveCopyCUnion()) && \"shouldn't be called if type doesn't have a non-trivial C union\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11652, __PRETTY_FUNCTION__)); | ||||||
11653 | |||||||
11654 | if ((NonTrivialKind & NTCUK_Init) && | ||||||
11655 | QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
11656 | DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) | ||||||
11657 | .visit(QT, nullptr, false); | ||||||
11658 | if ((NonTrivialKind & NTCUK_Destruct) && | ||||||
11659 | QT.hasNonTrivialToPrimitiveDestructCUnion()) | ||||||
11660 | DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) | ||||||
11661 | .visit(QT, nullptr, false); | ||||||
11662 | if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11663 | DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) | ||||||
11664 | .visit(QT, nullptr, false); | ||||||
11665 | } | ||||||
11666 | |||||||
11667 | /// AddInitializerToDecl - Adds the initializer Init to the | ||||||
11668 | /// declaration dcl. If DirectInit is true, this is C++ direct | ||||||
11669 | /// initialization rather than copy initialization. | ||||||
11670 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { | ||||||
11671 | // If there is no declaration, there was an error parsing it. Just ignore | ||||||
11672 | // the initializer. | ||||||
11673 | if (!RealDecl || RealDecl->isInvalidDecl()) { | ||||||
11674 | CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); | ||||||
11675 | return; | ||||||
11676 | } | ||||||
11677 | |||||||
11678 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { | ||||||
11679 | // Pure-specifiers are handled in ActOnPureSpecifier. | ||||||
11680 | Diag(Method->getLocation(), diag::err_member_function_initialization) | ||||||
11681 | << Method->getDeclName() << Init->getSourceRange(); | ||||||
11682 | Method->setInvalidDecl(); | ||||||
11683 | return; | ||||||
11684 | } | ||||||
11685 | |||||||
11686 | VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); | ||||||
11687 | if (!VDecl) { | ||||||
11688 | assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((!isa<FieldDecl>(RealDecl) && "field init shouldn't get here" ) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 11688, __PRETTY_FUNCTION__)); | ||||||
11689 | Diag(RealDecl->getLocation(), diag::err_illegal_initializer); | ||||||
11690 | RealDecl->setInvalidDecl(); | ||||||
11691 | return; | ||||||
11692 | } | ||||||
11693 | |||||||
11694 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. | ||||||
11695 | if (VDecl->getType()->isUndeducedType()) { | ||||||
11696 | // Attempt typo correction early so that the type of the init expression can | ||||||
11697 | // be deduced based on the chosen correction if the original init contains a | ||||||
11698 | // TypoExpr. | ||||||
11699 | ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); | ||||||
11700 | if (!Res.isUsable()) { | ||||||
11701 | RealDecl->setInvalidDecl(); | ||||||
11702 | return; | ||||||
11703 | } | ||||||
11704 | Init = Res.get(); | ||||||
11705 | |||||||
11706 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) | ||||||
11707 | return; | ||||||
11708 | } | ||||||
11709 | |||||||
11710 | // dllimport cannot be used on variable definitions. | ||||||
11711 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { | ||||||
11712 | Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); | ||||||
11713 | VDecl->setInvalidDecl(); | ||||||
11714 | return; | ||||||
11715 | } | ||||||
11716 | |||||||
11717 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { | ||||||
11718 | // C99 6.7.8p5. C++ has no such restriction, but that is a defect. | ||||||
11719 | Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); | ||||||
11720 | VDecl->setInvalidDecl(); | ||||||
11721 | return; | ||||||
11722 | } | ||||||
11723 | |||||||
11724 | if (!VDecl->getType()->isDependentType()) { | ||||||
11725 | // A definition must end up with a complete type, which means it must be | ||||||
11726 | // complete with the restriction that an array type might be completed by | ||||||
11727 | // the initializer; note that later code assumes this restriction. | ||||||
11728 | QualType BaseDeclType = VDecl->getType(); | ||||||
11729 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) | ||||||
11730 | BaseDeclType = Array->getElementType(); | ||||||
11731 | if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, | ||||||
11732 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
11733 | RealDecl->setInvalidDecl(); | ||||||
11734 | return; | ||||||
11735 | } | ||||||
11736 | |||||||
11737 | // The variable can not have an abstract class type. | ||||||
11738 | if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), | ||||||
11739 | diag::err_abstract_type_in_decl, | ||||||
11740 | AbstractVariableType)) | ||||||
11741 | VDecl->setInvalidDecl(); | ||||||
11742 | } | ||||||
11743 | |||||||
11744 | // If adding the initializer will turn this declaration into a definition, | ||||||
11745 | // and we already have a definition for this variable, diagnose or otherwise | ||||||
11746 | // handle the situation. | ||||||
11747 | VarDecl *Def; | ||||||
11748 | if ((Def = VDecl->getDefinition()) && Def != VDecl && | ||||||
11749 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && | ||||||
11750 | !VDecl->isThisDeclarationADemotedDefinition() && | ||||||
11751 | checkVarDeclRedefinition(Def, VDecl)) | ||||||
11752 | return; | ||||||
11753 | |||||||
11754 | if (getLangOpts().CPlusPlus) { | ||||||
11755 | // C++ [class.static.data]p4 | ||||||
11756 | // If a static data member is of const integral or const | ||||||
11757 | // enumeration type, its declaration in the class definition can | ||||||
11758 | // specify a constant-initializer which shall be an integral | ||||||
11759 | // constant expression (5.19). In that case, the member can appear | ||||||
11760 | // in integral constant expressions. The member shall still be | ||||||
11761 | // defined in a namespace scope if it is used in the program and the | ||||||
11762 | // namespace scope definition shall not contain an initializer. | ||||||
11763 | // | ||||||
11764 | // We already performed a redefinition check above, but for static | ||||||
11765 | // data members we also need to check whether there was an in-class | ||||||
11766 | // declaration with an initializer. | ||||||
11767 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { | ||||||
11768 | Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) | ||||||
11769 | << VDecl->getDeclName(); | ||||||
11770 | Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), | ||||||
11771 | diag::note_previous_initializer) | ||||||
11772 | << 0; | ||||||
11773 | return; | ||||||
11774 | } | ||||||
11775 | |||||||
11776 | if (VDecl->hasLocalStorage()) | ||||||
11777 | setFunctionHasBranchProtectedScope(); | ||||||
11778 | |||||||
11779 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { | ||||||
11780 | VDecl->setInvalidDecl(); | ||||||
11781 | return; | ||||||
11782 | } | ||||||
11783 | } | ||||||
11784 | |||||||
11785 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside | ||||||
11786 | // a kernel function cannot be initialized." | ||||||
11787 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { | ||||||
11788 | Diag(VDecl->getLocation(), diag::err_local_cant_init); | ||||||
11789 | VDecl->setInvalidDecl(); | ||||||
11790 | return; | ||||||
11791 | } | ||||||
11792 | |||||||
11793 | // Get the decls type and save a reference for later, since | ||||||
11794 | // CheckInitializerTypes may change it. | ||||||
11795 | QualType DclT = VDecl->getType(), SavT = DclT; | ||||||
11796 | |||||||
11797 | // Expressions default to 'id' when we're in a debugger | ||||||
11798 | // and we are assigning it to a variable of Objective-C pointer type. | ||||||
11799 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && | ||||||
11800 | Init->getType() == Context.UnknownAnyTy) { | ||||||
11801 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | ||||||
11802 | if (Result.isInvalid()) { | ||||||
11803 | VDecl->setInvalidDecl(); | ||||||
11804 | return; | ||||||
11805 | } | ||||||
11806 | Init = Result.get(); | ||||||
11807 | } | ||||||
11808 | |||||||
11809 | // Perform the initialization. | ||||||
11810 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); | ||||||
11811 | if (!VDecl->isInvalidDecl()) { | ||||||
11812 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | ||||||
11813 | InitializationKind Kind = InitializationKind::CreateForInit( | ||||||
11814 | VDecl->getLocation(), DirectInit, Init); | ||||||
11815 | |||||||
11816 | MultiExprArg Args = Init; | ||||||
11817 | if (CXXDirectInit) | ||||||
11818 | Args = MultiExprArg(CXXDirectInit->getExprs(), | ||||||
11819 | CXXDirectInit->getNumExprs()); | ||||||
11820 | |||||||
11821 | // Try to correct any TypoExprs in the initialization arguments. | ||||||
11822 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { | ||||||
11823 | ExprResult Res = CorrectDelayedTyposInExpr( | ||||||
11824 | Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { | ||||||
11825 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); | ||||||
11826 | return Init.Failed() ? ExprError() : E; | ||||||
11827 | }); | ||||||
11828 | if (Res.isInvalid()) { | ||||||
11829 | VDecl->setInvalidDecl(); | ||||||
11830 | } else if (Res.get() != Args[Idx]) { | ||||||
11831 | Args[Idx] = Res.get(); | ||||||
11832 | } | ||||||
11833 | } | ||||||
11834 | if (VDecl->isInvalidDecl()) | ||||||
11835 | return; | ||||||
11836 | |||||||
11837 | InitializationSequence InitSeq(*this, Entity, Kind, Args, | ||||||
11838 | /*TopLevelOfInitList=*/false, | ||||||
11839 | /*TreatUnavailableAsInvalid=*/false); | ||||||
11840 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); | ||||||
11841 | if (Result.isInvalid()) { | ||||||
11842 | VDecl->setInvalidDecl(); | ||||||
11843 | return; | ||||||
11844 | } | ||||||
11845 | |||||||
11846 | Init = Result.getAs<Expr>(); | ||||||
11847 | } | ||||||
11848 | |||||||
11849 | // Check for self-references within variable initializers. | ||||||
11850 | // Variables declared within a function/method body (except for references) | ||||||
11851 | // are handled by a dataflow analysis. | ||||||
11852 | // This is undefined behavior in C++, but valid in C. | ||||||
11853 | if (getLangOpts().CPlusPlus) { | ||||||
11854 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || | ||||||
11855 | VDecl->getType()->isReferenceType()) { | ||||||
11856 | CheckSelfReference(*this, RealDecl, Init, DirectInit); | ||||||
11857 | } | ||||||
11858 | } | ||||||
11859 | |||||||
11860 | // If the type changed, it means we had an incomplete type that was | ||||||
11861 | // completed by the initializer. For example: | ||||||
11862 | // int ary[] = { 1, 3, 5 }; | ||||||
11863 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. | ||||||
11864 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) | ||||||
11865 | VDecl->setType(DclT); | ||||||
11866 | |||||||
11867 | if (!VDecl->isInvalidDecl()) { | ||||||
11868 | checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); | ||||||
11869 | |||||||
11870 | if (VDecl->hasAttr<BlocksAttr>()) | ||||||
11871 | checkRetainCycles(VDecl, Init); | ||||||
11872 | |||||||
11873 | // It is safe to assign a weak reference into a strong variable. | ||||||
11874 | // Although this code can still have problems: | ||||||
11875 | // id x = self.weakProp; | ||||||
11876 | // id y = self.weakProp; | ||||||
11877 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||||
11878 | // paths through the function. This should be revisited if | ||||||
11879 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||||
11880 | if (FunctionScopeInfo *FSI = getCurFunction()) | ||||||
11881 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || | ||||||
11882 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && | ||||||
11883 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||||
11884 | Init->getBeginLoc())) | ||||||
11885 | FSI->markSafeWeakUse(Init); | ||||||
11886 | } | ||||||
11887 | |||||||
11888 | // The initialization is usually a full-expression. | ||||||
11889 | // | ||||||
11890 | // FIXME: If this is a braced initialization of an aggregate, it is not | ||||||
11891 | // an expression, and each individual field initializer is a separate | ||||||
11892 | // full-expression. For instance, in: | ||||||
11893 | // | ||||||
11894 | // struct Temp { ~Temp(); }; | ||||||
11895 | // struct S { S(Temp); }; | ||||||
11896 | // struct T { S a, b; } t = { Temp(), Temp() } | ||||||
11897 | // | ||||||
11898 | // we should destroy the first Temp before constructing the second. | ||||||
11899 | ExprResult Result = | ||||||
11900 | ActOnFinishFullExpr(Init, VDecl->getLocation(), | ||||||
11901 | /*DiscardedValue*/ false, VDecl->isConstexpr()); | ||||||
11902 | if (Result.isInvalid()) { | ||||||
11903 | VDecl->setInvalidDecl(); | ||||||
11904 | return; | ||||||
11905 | } | ||||||
11906 | Init = Result.get(); | ||||||
11907 | |||||||
11908 | // Attach the initializer to the decl. | ||||||
11909 | VDecl->setInit(Init); | ||||||
11910 | |||||||
11911 | if (VDecl->isLocalVarDecl()) { | ||||||
11912 | // Don't check the initializer if the declaration is malformed. | ||||||
11913 | if (VDecl->isInvalidDecl()) { | ||||||
11914 | // do nothing | ||||||
11915 | |||||||
11916 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. | ||||||
11917 | // This is true even in C++ for OpenCL. | ||||||
11918 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { | ||||||
11919 | CheckForConstantInitializer(Init, DclT); | ||||||
11920 | |||||||
11921 | // Otherwise, C++ does not restrict the initializer. | ||||||
11922 | } else if (getLangOpts().CPlusPlus) { | ||||||
11923 | // do nothing | ||||||
11924 | |||||||
11925 | // C99 6.7.8p4: All the expressions in an initializer for an object that has | ||||||
11926 | // static storage duration shall be constant expressions or string literals. | ||||||
11927 | } else if (VDecl->getStorageClass() == SC_Static) { | ||||||
11928 | CheckForConstantInitializer(Init, DclT); | ||||||
11929 | |||||||
11930 | // C89 is stricter than C99 for aggregate initializers. | ||||||
11931 | // C89 6.5.7p3: All the expressions [...] in an initializer list | ||||||
11932 | // for an object that has aggregate or union type shall be | ||||||
11933 | // constant expressions. | ||||||
11934 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && | ||||||
11935 | isa<InitListExpr>(Init)) { | ||||||
11936 | const Expr *Culprit; | ||||||
11937 | if (!Init->isConstantInitializer(Context, false, &Culprit)) { | ||||||
11938 | Diag(Culprit->getExprLoc(), | ||||||
11939 | diag::ext_aggregate_init_not_constant) | ||||||
11940 | << Culprit->getSourceRange(); | ||||||
11941 | } | ||||||
11942 | } | ||||||
11943 | |||||||
11944 | if (auto *E = dyn_cast<ExprWithCleanups>(Init)) | ||||||
11945 | if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) | ||||||
11946 | if (VDecl->hasLocalStorage()) | ||||||
11947 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||||
11948 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && | ||||||
11949 | VDecl->getLexicalDeclContext()->isRecord()) { | ||||||
11950 | // This is an in-class initialization for a static data member, e.g., | ||||||
11951 | // | ||||||
11952 | // struct S { | ||||||
11953 | // static const int value = 17; | ||||||
11954 | // }; | ||||||
11955 | |||||||
11956 | // C++ [class.mem]p4: | ||||||
11957 | // A member-declarator can contain a constant-initializer only | ||||||
11958 | // if it declares a static member (9.4) of const integral or | ||||||
11959 | // const enumeration type, see 9.4.2. | ||||||
11960 | // | ||||||
11961 | // C++11 [class.static.data]p3: | ||||||
11962 | // If a non-volatile non-inline const static data member is of integral | ||||||
11963 | // or enumeration type, its declaration in the class definition can | ||||||
11964 | // specify a brace-or-equal-initializer in which every initializer-clause | ||||||
11965 | // that is an assignment-expression is a constant expression. A static | ||||||
11966 | // data member of literal type can be declared in the class definition | ||||||
11967 | // with the constexpr specifier; if so, its declaration shall specify a | ||||||
11968 | // brace-or-equal-initializer in which every initializer-clause that is | ||||||
11969 | // an assignment-expression is a constant expression. | ||||||
11970 | |||||||
11971 | // Do nothing on dependent types. | ||||||
11972 | if (DclT->isDependentType()) { | ||||||
11973 | |||||||
11974 | // Allow any 'static constexpr' members, whether or not they are of literal | ||||||
11975 | // type. We separately check that every constexpr variable is of literal | ||||||
11976 | // type. | ||||||
11977 | } else if (VDecl->isConstexpr()) { | ||||||
11978 | |||||||
11979 | // Require constness. | ||||||
11980 | } else if (!DclT.isConstQualified()) { | ||||||
11981 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) | ||||||
11982 | << Init->getSourceRange(); | ||||||
11983 | VDecl->setInvalidDecl(); | ||||||
11984 | |||||||
11985 | // We allow integer constant expressions in all cases. | ||||||
11986 | } else if (DclT->isIntegralOrEnumerationType()) { | ||||||
11987 | // Check whether the expression is a constant expression. | ||||||
11988 | SourceLocation Loc; | ||||||
11989 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) | ||||||
11990 | // In C++11, a non-constexpr const static data member with an | ||||||
11991 | // in-class initializer cannot be volatile. | ||||||
11992 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); | ||||||
11993 | else if (Init->isValueDependent()) | ||||||
11994 | ; // Nothing to check. | ||||||
11995 | else if (Init->isIntegerConstantExpr(Context, &Loc)) | ||||||
11996 | ; // Ok, it's an ICE! | ||||||
11997 | else if (Init->getType()->isScopedEnumeralType() && | ||||||
11998 | Init->isCXX11ConstantExpr(Context)) | ||||||
11999 | ; // Ok, it is a scoped-enum constant expression. | ||||||
12000 | else if (Init->isEvaluatable(Context)) { | ||||||
12001 | // If we can constant fold the initializer through heroics, accept it, | ||||||
12002 | // but report this as a use of an extension for -pedantic. | ||||||
12003 | Diag(Loc, diag::ext_in_class_initializer_non_constant) | ||||||
12004 | << Init->getSourceRange(); | ||||||
12005 | } else { | ||||||
12006 | // Otherwise, this is some crazy unknown case. Report the issue at the | ||||||
12007 | // location provided by the isIntegerConstantExpr failed check. | ||||||
12008 | Diag(Loc, diag::err_in_class_initializer_non_constant) | ||||||
12009 | << Init->getSourceRange(); | ||||||
12010 | VDecl->setInvalidDecl(); | ||||||
12011 | } | ||||||
12012 | |||||||
12013 | // We allow foldable floating-point constants as an extension. | ||||||
12014 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok | ||||||
12015 | // In C++98, this is a GNU extension. In C++11, it is not, but we support | ||||||
12016 | // it anyway and provide a fixit to add the 'constexpr'. | ||||||
12017 | if (getLangOpts().CPlusPlus11) { | ||||||
12018 | Diag(VDecl->getLocation(), | ||||||
12019 | diag::ext_in_class_initializer_float_type_cxx11) | ||||||
12020 | << DclT << Init->getSourceRange(); | ||||||
12021 | Diag(VDecl->getBeginLoc(), | ||||||
12022 | diag::note_in_class_initializer_float_type_cxx11) | ||||||
12023 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | ||||||
12024 | } else { | ||||||
12025 | Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) | ||||||
12026 | << DclT << Init->getSourceRange(); | ||||||
12027 | |||||||
12028 | if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { | ||||||
12029 | Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) | ||||||
12030 | << Init->getSourceRange(); | ||||||
12031 | VDecl->setInvalidDecl(); | ||||||
12032 | } | ||||||
12033 | } | ||||||
12034 | |||||||
12035 | // Suggest adding 'constexpr' in C++11 for literal types. | ||||||
12036 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { | ||||||
12037 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) | ||||||
12038 | << DclT << Init->getSourceRange() | ||||||
12039 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | ||||||
12040 | VDecl->setConstexpr(true); | ||||||
12041 | |||||||
12042 | } else { | ||||||
12043 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) | ||||||
12044 | << DclT << Init->getSourceRange(); | ||||||
12045 | VDecl->setInvalidDecl(); | ||||||
12046 | } | ||||||
12047 | } else if (VDecl->isFileVarDecl()) { | ||||||
12048 | // In C, extern is typically used to avoid tentative definitions when | ||||||
12049 | // declaring variables in headers, but adding an intializer makes it a | ||||||
12050 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. | ||||||
12051 | // In C++, extern is often used to give implictly static const variables | ||||||
12052 | // external linkage, so don't warn in that case. If selectany is present, | ||||||
12053 | // this might be header code intended for C and C++ inclusion, so apply the | ||||||
12054 | // C++ rules. | ||||||
12055 | if (VDecl->getStorageClass() == SC_Extern && | ||||||
12056 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || | ||||||
12057 | !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && | ||||||
12058 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && | ||||||
12059 | !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) | ||||||
12060 | Diag(VDecl->getLocation(), diag::warn_extern_init); | ||||||
12061 | |||||||
12062 | // In Microsoft C++ mode, a const variable defined in namespace scope has | ||||||
12063 | // external linkage by default if the variable is declared with | ||||||
12064 | // __declspec(dllexport). | ||||||
12065 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | ||||||
12066 | getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && | ||||||
12067 | VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) | ||||||
12068 | VDecl->setStorageClass(SC_Extern); | ||||||
12069 | |||||||
12070 | // C99 6.7.8p4. All file scoped initializers need to be constant. | ||||||
12071 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) | ||||||
12072 | CheckForConstantInitializer(Init, DclT); | ||||||
12073 | } | ||||||
12074 | |||||||
12075 | QualType InitType = Init->getType(); | ||||||
12076 | if (!InitType.isNull() && | ||||||
12077 | (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||||
12078 | InitType.hasNonTrivialToPrimitiveCopyCUnion())) | ||||||
12079 | checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); | ||||||
12080 | |||||||
12081 | // We will represent direct-initialization similarly to copy-initialization: | ||||||
12082 | // int x(1); -as-> int x = 1; | ||||||
12083 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); | ||||||
12084 | // | ||||||
12085 | // Clients that want to distinguish between the two forms, can check for | ||||||
12086 | // direct initializer using VarDecl::getInitStyle(). | ||||||
12087 | // A major benefit is that clients that don't particularly care about which | ||||||
12088 | // exactly form was it (like the CodeGen) can handle both cases without | ||||||
12089 | // special case code. | ||||||
12090 | |||||||
12091 | // C++ 8.5p11: | ||||||
12092 | // The form of initialization (using parentheses or '=') is generally | ||||||
12093 | // insignificant, but does matter when the entity being initialized has a | ||||||
12094 | // class type. | ||||||
12095 | if (CXXDirectInit) { | ||||||
12096 | assert(DirectInit && "Call-style initializer must be direct init.")((DirectInit && "Call-style initializer must be direct init." ) ? static_cast<void> (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 12096, __PRETTY_FUNCTION__)); | ||||||
12097 | VDecl->setInitStyle(VarDecl::CallInit); | ||||||
12098 | } else if (DirectInit) { | ||||||
12099 | // This must be list-initialization. No other way is direct-initialization. | ||||||
12100 | VDecl->setInitStyle(VarDecl::ListInit); | ||||||
12101 | } | ||||||
12102 | |||||||
12103 | CheckCompleteVariableDeclaration(VDecl); | ||||||
12104 | } | ||||||
12105 | |||||||
12106 | /// ActOnInitializerError - Given that there was an error parsing an | ||||||
12107 | /// initializer for the given declaration, try to return to some form | ||||||
12108 | /// of sanity. | ||||||
12109 | void Sema::ActOnInitializerError(Decl *D) { | ||||||
12110 | // Our main concern here is re-establishing invariants like "a | ||||||
12111 | // variable's type is either dependent or complete". | ||||||
12112 | if (!D || D->isInvalidDecl()) return; | ||||||
12113 | |||||||
12114 | VarDecl *VD = dyn_cast<VarDecl>(D); | ||||||
12115 | if (!VD) return; | ||||||
12116 | |||||||
12117 | // Bindings are not usable if we can't make sense of the initializer. | ||||||
12118 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) | ||||||
12119 | for (auto *BD : DD->bindings()) | ||||||
12120 | BD->setInvalidDecl(); | ||||||
12121 | |||||||
12122 | // Auto types are meaningless if we can't make sense of the initializer. | ||||||
12123 | if (ParsingInitForAutoVars.count(D)) { | ||||||
12124 | D->setInvalidDecl(); | ||||||
12125 | return; | ||||||
12126 | } | ||||||
12127 | |||||||
12128 | QualType Ty = VD->getType(); | ||||||
12129 | if (Ty->isDependentType()) return; | ||||||
12130 | |||||||
12131 | // Require a complete type. | ||||||
12132 | if (RequireCompleteType(VD->getLocation(), | ||||||
12133 | Context.getBaseElementType(Ty), | ||||||
12134 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
12135 | VD->setInvalidDecl(); | ||||||
12136 | return; | ||||||
12137 | } | ||||||
12138 | |||||||
12139 | // Require a non-abstract type. | ||||||
12140 | if (RequireNonAbstractType(VD->getLocation(), Ty, | ||||||
12141 | diag::err_abstract_type_in_decl, | ||||||
12142 | AbstractVariableType)) { | ||||||
12143 | VD->setInvalidDecl(); | ||||||
12144 | return; | ||||||
12145 | } | ||||||
12146 | |||||||
12147 | // Don't bother complaining about constructors or destructors, | ||||||
12148 | // though. | ||||||
12149 | } | ||||||
12150 | |||||||
12151 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { | ||||||
12152 | // If there is no declaration, there was an error parsing it. Just ignore it. | ||||||
12153 | if (!RealDecl) | ||||||
12154 | return; | ||||||
12155 | |||||||
12156 | if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { | ||||||
12157 | QualType Type = Var->getType(); | ||||||
12158 | |||||||
12159 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. | ||||||
12160 | if (isa<DecompositionDecl>(RealDecl)) { | ||||||
12161 | Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; | ||||||
12162 | Var->setInvalidDecl(); | ||||||
12163 | return; | ||||||
12164 | } | ||||||
12165 | |||||||
12166 | if (Type->isUndeducedType() && | ||||||
12167 | DeduceVariableDeclarationType(Var, false, nullptr)) | ||||||
12168 | return; | ||||||
12169 | |||||||
12170 | // C++11 [class.static.data]p3: A static data member can be declared with | ||||||
12171 | // the constexpr specifier; if so, its declaration shall specify | ||||||
12172 | // a brace-or-equal-initializer. | ||||||
12173 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to | ||||||
12174 | // the definition of a variable [...] or the declaration of a static data | ||||||
12175 | // member. | ||||||
12176 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && | ||||||
12177 | !Var->isThisDeclarationADemotedDefinition()) { | ||||||
12178 | if (Var->isStaticDataMember()) { | ||||||
12179 | // C++1z removes the relevant rule; the in-class declaration is always | ||||||
12180 | // a definition there. | ||||||
12181 | if (!getLangOpts().CPlusPlus17 && | ||||||
12182 | !Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||||
12183 | Diag(Var->getLocation(), | ||||||
12184 | diag::err_constexpr_static_mem_var_requires_init) | ||||||
12185 | << Var->getDeclName(); | ||||||
12186 | Var->setInvalidDecl(); | ||||||
12187 | return; | ||||||
12188 | } | ||||||
12189 | } else { | ||||||
12190 | Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); | ||||||
12191 | Var->setInvalidDecl(); | ||||||
12192 | return; | ||||||
12193 | } | ||||||
12194 | } | ||||||
12195 | |||||||
12196 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must | ||||||
12197 | // be initialized. | ||||||
12198 | if (!Var->isInvalidDecl() && | ||||||
12199 | Var->getType().getAddressSpace() == LangAS::opencl_constant && | ||||||
12200 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { | ||||||
12201 | Diag(Var->getLocation(), diag::err_opencl_constant_no_init); | ||||||
12202 | Var->setInvalidDecl(); | ||||||
12203 | return; | ||||||
12204 | } | ||||||
12205 | |||||||
12206 | VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); | ||||||
12207 | if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && | ||||||
12208 | Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
12209 | checkNonTrivialCUnion(Var->getType(), Var->getLocation(), | ||||||
12210 | NTCUC_DefaultInitializedObject, NTCUK_Init); | ||||||
12211 | |||||||
12212 | |||||||
12213 | switch (DefKind) { | ||||||
12214 | case VarDecl::Definition: | ||||||
12215 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) | ||||||
12216 | break; | ||||||
12217 | |||||||
12218 | // We have an out-of-line definition of a static data member | ||||||
12219 | // that has an in-class initializer, so we type-check this like | ||||||
12220 | // a declaration. | ||||||
12221 | // | ||||||
12222 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
12223 | |||||||
12224 | case VarDecl::DeclarationOnly: | ||||||
12225 | // It's only a declaration. | ||||||
12226 | |||||||
12227 | // Block scope. C99 6.7p7: If an identifier for an object is | ||||||
12228 | // declared with no linkage (C99 6.2.2p6), the type for the | ||||||
12229 | // object shall be complete. | ||||||
12230 | if (!Type->isDependentType() && Var->isLocalVarDecl() && | ||||||
12231 | !Var->hasLinkage() && !Var->isInvalidDecl() && | ||||||
12232 | RequireCompleteType(Var->getLocation(), Type, | ||||||
12233 | diag::err_typecheck_decl_incomplete_type)) | ||||||
12234 | Var->setInvalidDecl(); | ||||||
12235 | |||||||
12236 | // Make sure that the type is not abstract. | ||||||
12237 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | ||||||
12238 | RequireNonAbstractType(Var->getLocation(), Type, | ||||||
12239 | diag::err_abstract_type_in_decl, | ||||||
12240 | AbstractVariableType)) | ||||||
12241 | Var->setInvalidDecl(); | ||||||
12242 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | ||||||
12243 | Var->getStorageClass() == SC_PrivateExtern) { | ||||||
12244 | Diag(Var->getLocation(), diag::warn_private_extern); | ||||||
12245 | Diag(Var->getLocation(), diag::note_private_extern); | ||||||
12246 | } | ||||||
12247 | |||||||
12248 | if (Context.getTargetInfo().allowDebugInfoForExternalVar() && | ||||||
12249 | !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) | ||||||
12250 | ExternalDeclarations.push_back(Var); | ||||||
12251 | |||||||
12252 | return; | ||||||
12253 | |||||||
12254 | case VarDecl::TentativeDefinition: | ||||||
12255 | // File scope. C99 6.9.2p2: A declaration of an identifier for an | ||||||
12256 | // object that has file scope without an initializer, and without a | ||||||
12257 | // storage-class specifier or with the storage-class specifier "static", | ||||||
12258 | // constitutes a tentative definition. Note: A tentative definition with | ||||||
12259 | // external linkage is valid (C99 6.2.2p5). | ||||||
12260 | if (!Var->isInvalidDecl()) { | ||||||
12261 | if (const IncompleteArrayType *ArrayT | ||||||
12262 | = Context.getAsIncompleteArrayType(Type)) { | ||||||
12263 | if (RequireCompleteType(Var->getLocation(), | ||||||
12264 | ArrayT->getElementType(), | ||||||
12265 | diag::err_illegal_decl_array_incomplete_type)) | ||||||
12266 | Var->setInvalidDecl(); | ||||||
12267 | } else if (Var->getStorageClass() == SC_Static) { | ||||||
12268 | // C99 6.9.2p3: If the declaration of an identifier for an object is | ||||||
12269 | // a tentative definition and has internal linkage (C99 6.2.2p3), the | ||||||
12270 | // declared type shall not be an incomplete type. | ||||||
12271 | // NOTE: code such as the following | ||||||
12272 | // static struct s; | ||||||
12273 | // struct s { int a; }; | ||||||
12274 | // is accepted by gcc. Hence here we issue a warning instead of | ||||||
12275 | // an error and we do not invalidate the static declaration. | ||||||
12276 | // NOTE: to avoid multiple warnings, only check the first declaration. | ||||||
12277 | if (Var->isFirstDecl()) | ||||||
12278 | RequireCompleteType(Var->getLocation(), Type, | ||||||
12279 | diag::ext_typecheck_decl_incomplete_type); | ||||||
12280 | } | ||||||
12281 | } | ||||||
12282 | |||||||
12283 | // Record the tentative definition; we're done. | ||||||
12284 | if (!Var->isInvalidDecl()) | ||||||
12285 | TentativeDefinitions.push_back(Var); | ||||||
12286 | return; | ||||||
12287 | } | ||||||
12288 | |||||||
12289 | // Provide a specific diagnostic for uninitialized variable | ||||||
12290 | // definitions with incomplete array type. | ||||||
12291 | if (Type->isIncompleteArrayType()) { | ||||||
12292 | Diag(Var->getLocation(), | ||||||
12293 | diag::err_typecheck_incomplete_array_needs_initializer); | ||||||
12294 | Var->setInvalidDecl(); | ||||||
12295 | return; | ||||||
12296 | } | ||||||
12297 | |||||||
12298 | // Provide a specific diagnostic for uninitialized variable | ||||||
12299 | // definitions with reference type. | ||||||
12300 | if (Type->isReferenceType()) { | ||||||
12301 | Diag(Var->getLocation(), diag::err_reference_var_requires_init) | ||||||
12302 | << Var->getDeclName() | ||||||
12303 | << SourceRange(Var->getLocation(), Var->getLocation()); | ||||||
12304 | Var->setInvalidDecl(); | ||||||
12305 | return; | ||||||
12306 | } | ||||||
12307 | |||||||
12308 | // Do not attempt to type-check the default initializer for a | ||||||
12309 | // variable with dependent type. | ||||||
12310 | if (Type->isDependentType()) | ||||||
12311 | return; | ||||||
12312 | |||||||
12313 | if (Var->isInvalidDecl()) | ||||||
12314 | return; | ||||||
12315 | |||||||
12316 | if (!Var->hasAttr<AliasAttr>()) { | ||||||
12317 | if (RequireCompleteType(Var->getLocation(), | ||||||
12318 | Context.getBaseElementType(Type), | ||||||
12319 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
12320 | Var->setInvalidDecl(); | ||||||
12321 | return; | ||||||
12322 | } | ||||||
12323 | } else { | ||||||
12324 | return; | ||||||
12325 | } | ||||||
12326 | |||||||
12327 | // The variable can not have an abstract class type. | ||||||
12328 | if (RequireNonAbstractType(Var->getLocation(), Type, | ||||||
12329 | diag::err_abstract_type_in_decl, | ||||||
12330 | AbstractVariableType)) { | ||||||
12331 | Var->setInvalidDecl(); | ||||||
12332 | return; | ||||||
12333 | } | ||||||
12334 | |||||||
12335 | // Check for jumps past the implicit initializer. C++0x | ||||||
12336 | // clarifies that this applies to a "variable with automatic | ||||||
12337 | // storage duration", not a "local variable". | ||||||
12338 | // C++11 [stmt.dcl]p3 | ||||||
12339 | // A program that jumps from a point where a variable with automatic | ||||||
12340 | // storage duration is not in scope to a point where it is in scope is | ||||||
12341 | // ill-formed unless the variable has scalar type, class type with a | ||||||
12342 | // trivial default constructor and a trivial destructor, a cv-qualified | ||||||
12343 | // version of one of these types, or an array of one of the preceding | ||||||
12344 | // types and is declared without an initializer. | ||||||
12345 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { | ||||||
12346 | if (const RecordType *Record | ||||||
12347 | = Context.getBaseElementType(Type)->getAs<RecordType>()) { | ||||||
12348 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); | ||||||
12349 | // Mark the function (if we're in one) for further checking even if the | ||||||
12350 | // looser rules of C++11 do not require such checks, so that we can | ||||||
12351 | // diagnose incompatibilities with C++98. | ||||||
12352 | if (!CXXRecord->isPOD()) | ||||||
12353 | setFunctionHasBranchProtectedScope(); | ||||||
12354 | } | ||||||
12355 | } | ||||||
12356 | // In OpenCL, we can't initialize objects in the __local address space, | ||||||
12357 | // even implicitly, so don't synthesize an implicit initializer. | ||||||
12358 | if (getLangOpts().OpenCL && | ||||||
12359 | Var->getType().getAddressSpace() == LangAS::opencl_local) | ||||||
12360 | return; | ||||||
12361 | // C++03 [dcl.init]p9: | ||||||
12362 | // If no initializer is specified for an object, and the | ||||||
12363 | // object is of (possibly cv-qualified) non-POD class type (or | ||||||
12364 | // array thereof), the object shall be default-initialized; if | ||||||
12365 | // the object is of const-qualified type, the underlying class | ||||||
12366 | // type shall have a user-declared default | ||||||
12367 | // constructor. Otherwise, if no initializer is specified for | ||||||
12368 | // a non- static object, the object and its subobjects, if | ||||||
12369 | // any, have an indeterminate initial value); if the object | ||||||
12370 | // or any of its subobjects are of const-qualified type, the | ||||||
12371 | // program is ill-formed. | ||||||
12372 | // C++0x [dcl.init]p11: | ||||||
12373 | // If no initializer is specified for an object, the object is | ||||||
12374 | // default-initialized; [...]. | ||||||
12375 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); | ||||||
12376 | InitializationKind Kind | ||||||
12377 | = InitializationKind::CreateDefault(Var->getLocation()); | ||||||
12378 | |||||||
12379 | InitializationSequence InitSeq(*this, Entity, Kind, None); | ||||||
12380 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); | ||||||
12381 | if (Init.isInvalid()) | ||||||
12382 | Var->setInvalidDecl(); | ||||||
12383 | else if (Init.get()) { | ||||||
12384 | Var->setInit(MaybeCreateExprWithCleanups(Init.get())); | ||||||
12385 | // This is important for template substitution. | ||||||
12386 | Var->setInitStyle(VarDecl::CallInit); | ||||||
12387 | } | ||||||
12388 | |||||||
12389 | CheckCompleteVariableDeclaration(Var); | ||||||
12390 | } | ||||||
12391 | } | ||||||
12392 | |||||||
12393 | void Sema::ActOnCXXForRangeDecl(Decl *D) { | ||||||
12394 | // If there is no declaration, there was an error parsing it. Ignore it. | ||||||
12395 | if (!D) | ||||||
12396 | return; | ||||||
12397 | |||||||
12398 | VarDecl *VD = dyn_cast<VarDecl>(D); | ||||||
12399 | if (!VD) { | ||||||
12400 | Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); | ||||||
12401 | D->setInvalidDecl(); | ||||||
12402 | return; | ||||||
12403 | } | ||||||
12404 | |||||||
12405 | VD->setCXXForRangeDecl(true); | ||||||
12406 | |||||||
12407 | // for-range-declaration cannot be given a storage class specifier. | ||||||
12408 | int Error = -1; | ||||||
12409 | switch (VD->getStorageClass()) { | ||||||
12410 | case SC_None: | ||||||
12411 | break; | ||||||
12412 | case SC_Extern: | ||||||
12413 | Error = 0; | ||||||
12414 | break; | ||||||
12415 | case SC_Static: | ||||||
12416 | Error = 1; | ||||||
12417 | break; | ||||||
12418 | case SC_PrivateExtern: | ||||||
12419 | Error = 2; | ||||||
12420 | break; | ||||||
12421 | case SC_Auto: | ||||||
12422 | Error = 3; | ||||||
12423 | break; | ||||||
12424 | case SC_Register: | ||||||
12425 | Error = 4; | ||||||
12426 | break; | ||||||
12427 | } | ||||||
12428 | if (Error != -1) { | ||||||
12429 | Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) | ||||||
12430 | << VD->getDeclName() << Error; | ||||||
12431 | D->setInvalidDecl(); | ||||||
12432 | } | ||||||
12433 | } | ||||||
12434 | |||||||
12435 | StmtResult | ||||||
12436 | Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, | ||||||
12437 | IdentifierInfo *Ident, | ||||||
12438 | ParsedAttributes &Attrs, | ||||||
12439 | SourceLocation AttrEnd) { | ||||||
12440 | // C++1y [stmt.iter]p1: | ||||||
12441 | // A range-based for statement of the form | ||||||
12442 | // for ( for-range-identifier : for-range-initializer ) statement | ||||||
12443 | // is equivalent to | ||||||
12444 | // for ( auto&& for-range-identifier : for-range-initializer ) statement | ||||||
12445 | DeclSpec DS(Attrs.getPool().getFactory()); | ||||||
12446 | |||||||
12447 | const char *PrevSpec; | ||||||
12448 | unsigned DiagID; | ||||||
12449 | DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, | ||||||
12450 | getPrintingPolicy()); | ||||||
12451 | |||||||
12452 | Declarator D(DS, DeclaratorContext::ForContext); | ||||||
12453 | D.SetIdentifier(Ident, IdentLoc); | ||||||
12454 | D.takeAttributes(Attrs, AttrEnd); | ||||||
12455 | |||||||
12456 | D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), | ||||||
12457 | IdentLoc); | ||||||
12458 | Decl *Var = ActOnDeclarator(S, D); | ||||||
12459 | cast<VarDecl>(Var)->setCXXForRangeDecl(true); | ||||||
12460 | FinalizeDeclaration(Var); | ||||||
12461 | return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, | ||||||
12462 | AttrEnd.isValid() ? AttrEnd : IdentLoc); | ||||||
12463 | } | ||||||
12464 | |||||||
12465 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { | ||||||
12466 | if (var->isInvalidDecl()) return; | ||||||
12467 | |||||||
12468 | if (getLangOpts().OpenCL) { | ||||||
12469 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an | ||||||
12470 | // initialiser | ||||||
12471 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && | ||||||
12472 | !var->hasInit()) { | ||||||
12473 | Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||||
12474 | << 1 /*Init*/; | ||||||
12475 | var->setInvalidDecl(); | ||||||
12476 | return; | ||||||
12477 | } | ||||||
12478 | } | ||||||
12479 | |||||||
12480 | // In Objective-C, don't allow jumps past the implicit initialization of a | ||||||
12481 | // local retaining variable. | ||||||
12482 | if (getLangOpts().ObjC && | ||||||
12483 | var->hasLocalStorage()) { | ||||||
12484 | switch (var->getType().getObjCLifetime()) { | ||||||
12485 | case Qualifiers::OCL_None: | ||||||
12486 | case Qualifiers::OCL_ExplicitNone: | ||||||
12487 | case Qualifiers::OCL_Autoreleasing: | ||||||
12488 | break; | ||||||
12489 | |||||||
12490 | case Qualifiers::OCL_Weak: | ||||||
12491 | case Qualifiers::OCL_Strong: | ||||||
12492 | setFunctionHasBranchProtectedScope(); | ||||||
12493 | break; | ||||||
12494 | } | ||||||
12495 | } | ||||||
12496 | |||||||
12497 | if (var->hasLocalStorage() && | ||||||
12498 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||
12499 | setFunctionHasBranchProtectedScope(); | ||||||
12500 | |||||||
12501 | // Warn about externally-visible variables being defined without a | ||||||
12502 | // prior declaration. We only want to do this for global | ||||||
12503 | // declarations, but we also specifically need to avoid doing it for | ||||||
12504 | // class members because the linkage of an anonymous class can | ||||||
12505 | // change if it's later given a typedef name. | ||||||
12506 | if (var->isThisDeclarationADefinition() && | ||||||
12507 | var->getDeclContext()->getRedeclContext()->isFileContext() && | ||||||
12508 | var->isExternallyVisible() && var->hasLinkage() && | ||||||
12509 | !var->isInline() && !var->getDescribedVarTemplate() && | ||||||
12510 | !isTemplateInstantiation(var->getTemplateSpecializationKind()) && | ||||||
12511 | !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, | ||||||
12512 | var->getLocation())) { | ||||||
12513 | // Find a previous declaration that's not a definition. | ||||||
12514 | VarDecl *prev = var->getPreviousDecl(); | ||||||
12515 | while (prev && prev->isThisDeclarationADefinition()) | ||||||
12516 | prev = prev->getPreviousDecl(); | ||||||
12517 | |||||||
12518 | if (!prev) { | ||||||
12519 | Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; | ||||||
12520 | Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | ||||||
12521 | << /* variable */ 0; | ||||||
12522 | } | ||||||
12523 | } | ||||||
12524 | |||||||
12525 | // Cache the result of checking for constant initialization. | ||||||
12526 | Optional<bool> CacheHasConstInit; | ||||||
12527 | const Expr *CacheCulprit = nullptr; | ||||||
12528 | auto checkConstInit = [&]() mutable { | ||||||
12529 | if (!CacheHasConstInit) | ||||||
12530 | CacheHasConstInit = var->getInit()->isConstantInitializer( | ||||||
12531 | Context, var->getType()->isReferenceType(), &CacheCulprit); | ||||||
12532 | return *CacheHasConstInit; | ||||||
12533 | }; | ||||||
12534 | |||||||
12535 | if (var->getTLSKind() == VarDecl::TLS_Static) { | ||||||
12536 | if (var->getType().isDestructedType()) { | ||||||
12537 | // GNU C++98 edits for __thread, [basic.start.term]p3: | ||||||
12538 | // The type of an object with thread storage duration shall not | ||||||
12539 | // have a non-trivial destructor. | ||||||
12540 | Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); | ||||||
12541 | if (getLangOpts().CPlusPlus11) | ||||||
12542 | Diag(var->getLocation(), diag::note_use_thread_local); | ||||||
12543 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { | ||||||
12544 | if (!checkConstInit()) { | ||||||
12545 | // GNU C++98 edits for __thread, [basic.start.init]p4: | ||||||
12546 | // An object of thread storage duration shall not require dynamic | ||||||
12547 | // initialization. | ||||||
12548 | // FIXME: Need strict checking here. | ||||||
12549 | Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) | ||||||
12550 | << CacheCulprit->getSourceRange(); | ||||||
12551 | if (getLangOpts().CPlusPlus11) | ||||||
12552 | Diag(var->getLocation(), diag::note_use_thread_local); | ||||||
12553 | } | ||||||
12554 | } | ||||||
12555 | } | ||||||
12556 | |||||||
12557 | // Apply section attributes and pragmas to global variables. | ||||||
12558 | bool GlobalStorage = var->hasGlobalStorage(); | ||||||
12559 | if (GlobalStorage && var->isThisDeclarationADefinition() && | ||||||
12560 | !inTemplateInstantiation()) { | ||||||
12561 | PragmaStack<StringLiteral *> *Stack = nullptr; | ||||||
12562 | int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; | ||||||
12563 | if (var->getType().isConstQualified()) | ||||||
12564 | Stack = &ConstSegStack; | ||||||
12565 | else if (!var->getInit()) { | ||||||
12566 | Stack = &BSSSegStack; | ||||||
12567 | SectionFlags |= ASTContext::PSF_Write; | ||||||
12568 | } else { | ||||||
12569 | Stack = &DataSegStack; | ||||||
12570 | SectionFlags |= ASTContext::PSF_Write; | ||||||
12571 | } | ||||||
12572 | if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) | ||||||
12573 | var->addAttr(SectionAttr::CreateImplicit( | ||||||
12574 | Context, Stack->CurrentValue->getString(), | ||||||
12575 | Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||||
12576 | SectionAttr::Declspec_allocate)); | ||||||
12577 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) | ||||||
12578 | if (UnifySection(SA->getName(), SectionFlags, var)) | ||||||
12579 | var->dropAttr<SectionAttr>(); | ||||||
12580 | |||||||
12581 | // Apply the init_seg attribute if this has an initializer. If the | ||||||
12582 | // initializer turns out to not be dynamic, we'll end up ignoring this | ||||||
12583 | // attribute. | ||||||
12584 | if (CurInitSeg && var->getInit()) | ||||||
12585 | var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), | ||||||
12586 | CurInitSegLoc, | ||||||
12587 | AttributeCommonInfo::AS_Pragma)); | ||||||
12588 | } | ||||||
12589 | |||||||
12590 | // All the following checks are C++ only. | ||||||
12591 | if (!getLangOpts().CPlusPlus) { | ||||||
12592 | // If this variable must be emitted, add it as an initializer for the | ||||||
12593 | // current module. | ||||||
12594 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | ||||||
12595 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | ||||||
12596 | return; | ||||||
12597 | } | ||||||
12598 | |||||||
12599 | if (auto *DD = dyn_cast<DecompositionDecl>(var)) | ||||||
12600 | CheckCompleteDecompositionDeclaration(DD); | ||||||
12601 | |||||||
12602 | QualType type = var->getType(); | ||||||
12603 | if (type->isDependentType()) return; | ||||||
12604 | |||||||
12605 | if (var->hasAttr<BlocksAttr>()) | ||||||
12606 | getCurFunction()->addByrefBlockVar(var); | ||||||
12607 | |||||||
12608 | Expr *Init = var->getInit(); | ||||||
12609 | bool IsGlobal = GlobalStorage && !var->isStaticLocal(); | ||||||
12610 | QualType baseType = Context.getBaseElementType(type); | ||||||
12611 | |||||||
12612 | if (Init && !Init->isValueDependent()) { | ||||||
12613 | if (var->isConstexpr()) { | ||||||
12614 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||
12615 | if (!var->evaluateValue(Notes) || !var->isInitICE()) { | ||||||
12616 | SourceLocation DiagLoc = var->getLocation(); | ||||||
12617 | // If the note doesn't add any useful information other than a source | ||||||
12618 | // location, fold it into the primary diagnostic. | ||||||
12619 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||||
12620 | diag::note_invalid_subexpr_in_const_expr) { | ||||||
12621 | DiagLoc = Notes[0].first; | ||||||
12622 | Notes.clear(); | ||||||
12623 | } | ||||||
12624 | Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) | ||||||
12625 | << var << Init->getSourceRange(); | ||||||
12626 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) | ||||||
12627 | Diag(Notes[I].first, Notes[I].second); | ||||||
12628 | } | ||||||
12629 | } else if (var->mightBeUsableInConstantExpressions(Context)) { | ||||||
12630 | // Check whether the initializer of a const variable of integral or | ||||||
12631 | // enumeration type is an ICE now, since we can't tell whether it was | ||||||
12632 | // initialized by a constant expression if we check later. | ||||||
12633 | var->checkInitIsICE(); | ||||||
12634 | } | ||||||
12635 | |||||||
12636 | // Don't emit further diagnostics about constexpr globals since they | ||||||
12637 | // were just diagnosed. | ||||||
12638 | if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { | ||||||
12639 | // FIXME: Need strict checking in C++03 here. | ||||||
12640 | bool DiagErr = getLangOpts().CPlusPlus11 | ||||||
12641 | ? !var->checkInitIsICE() : !checkConstInit(); | ||||||
12642 | if (DiagErr) { | ||||||
12643 | auto *Attr = var->getAttr<ConstInitAttr>(); | ||||||
12644 | Diag(var->getLocation(), diag::err_require_constant_init_failed) | ||||||
12645 | << Init->getSourceRange(); | ||||||
12646 | Diag(Attr->getLocation(), | ||||||
12647 | diag::note_declared_required_constant_init_here) | ||||||
12648 | << Attr->getRange() << Attr->isConstinit(); | ||||||
12649 | if (getLangOpts().CPlusPlus11) { | ||||||
12650 | APValue Value; | ||||||
12651 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||
12652 | Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); | ||||||
12653 | for (auto &it : Notes) | ||||||
12654 | Diag(it.first, it.second); | ||||||
12655 | } else { | ||||||
12656 | Diag(CacheCulprit->getExprLoc(), | ||||||
12657 | diag::note_invalid_subexpr_in_const_expr) | ||||||
12658 | << CacheCulprit->getSourceRange(); | ||||||
12659 | } | ||||||
12660 | } | ||||||
12661 | } | ||||||
12662 | else if (!var->isConstexpr() && IsGlobal && | ||||||
12663 | !getDiagnostics().isIgnored(diag::warn_global_constructor, | ||||||
12664 | var->getLocation())) { | ||||||
12665 | // Warn about globals which don't have a constant initializer. Don't | ||||||
12666 | // warn about globals with a non-trivial destructor because we already | ||||||
12667 | // warned about them. | ||||||
12668 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); | ||||||
12669 | if (!(RD && !RD->hasTrivialDestructor())) { | ||||||
12670 | if (!checkConstInit()) | ||||||
12671 | Diag(var->getLocation(), diag::warn_global_constructor) | ||||||
12672 | << Init->getSourceRange(); | ||||||
12673 | } | ||||||
12674 | } | ||||||
12675 | } | ||||||
12676 | |||||||
12677 | // Require the destructor. | ||||||
12678 | if (const RecordType *recordType = baseType->getAs<RecordType>()) | ||||||
12679 | FinalizeVarWithDestructor(var, recordType); | ||||||
12680 | |||||||
12681 | // If this variable must be emitted, add it as an initializer for the current | ||||||
12682 | // module. | ||||||
12683 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | ||||||
12684 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | ||||||
12685 | } | ||||||
12686 | |||||||
12687 | /// Determines if a variable's alignment is dependent. | ||||||
12688 | static bool hasDependentAlignment(VarDecl *VD) { | ||||||
12689 | if (VD->getType()->isDependentType()) | ||||||
12690 | return true; | ||||||
12691 | for (auto *I : VD->specific_attrs<AlignedAttr>()) | ||||||
12692 | if (I->isAlignmentDependent()) | ||||||
12693 | return true; | ||||||
12694 | return false; | ||||||
12695 | } | ||||||
12696 | |||||||
12697 | /// Check if VD needs to be dllexport/dllimport due to being in a | ||||||
12698 | /// dllexport/import function. | ||||||
12699 | void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { | ||||||
12700 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 12700, __PRETTY_FUNCTION__)); | ||||||
12701 | |||||||
12702 | auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | ||||||
12703 | |||||||
12704 | // Find outermost function when VD is in lambda function. | ||||||
12705 | while (FD && !getDLLAttr(FD) && | ||||||
12706 | !FD->hasAttr<DLLExportStaticLocalAttr>() && | ||||||
12707 | !FD->hasAttr<DLLImportStaticLocalAttr>()) { | ||||||
12708 | FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); | ||||||
12709 | } | ||||||
12710 | |||||||
12711 | if (!FD) | ||||||
12712 | return; | ||||||
12713 | |||||||
12714 | // Static locals inherit dll attributes from their function. | ||||||
12715 | if (Attr *A = getDLLAttr(FD)) { | ||||||
12716 | auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); | ||||||
12717 | NewAttr->setInherited(true); | ||||||
12718 | VD->addAttr(NewAttr); | ||||||
12719 | } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { | ||||||
12720 | auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); | ||||||
12721 | NewAttr->setInherited(true); | ||||||
12722 | VD->addAttr(NewAttr); | ||||||
12723 | |||||||
12724 | // Export this function to enforce exporting this static variable even | ||||||
12725 | // if it is not used in this compilation unit. | ||||||
12726 | if (!FD->hasAttr<DLLExportAttr>()) | ||||||
12727 | FD->addAttr(NewAttr); | ||||||
12728 | |||||||
12729 | } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { | ||||||
12730 | auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); | ||||||
12731 | NewAttr->setInherited(true); | ||||||
12732 | VD->addAttr(NewAttr); | ||||||
12733 | } | ||||||
12734 | } | ||||||
12735 | |||||||
12736 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform | ||||||
12737 | /// any semantic actions necessary after any initializer has been attached. | ||||||
12738 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { | ||||||
12739 | // Note that we are no longer parsing the initializer for this declaration. | ||||||
12740 | ParsingInitForAutoVars.erase(ThisDecl); | ||||||
12741 | |||||||
12742 | VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); | ||||||
12743 | if (!VD) | ||||||
12744 | return; | ||||||
12745 | |||||||
12746 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active | ||||||
12747 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && | ||||||
12748 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { | ||||||
12749 | if (PragmaClangBSSSection.Valid) | ||||||
12750 | VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( | ||||||
12751 | Context, PragmaClangBSSSection.SectionName, | ||||||
12752 | PragmaClangBSSSection.PragmaLocation, | ||||||
12753 | AttributeCommonInfo::AS_Pragma)); | ||||||
12754 | if (PragmaClangDataSection.Valid) | ||||||
12755 | VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( | ||||||
12756 | Context, PragmaClangDataSection.SectionName, | ||||||
12757 | PragmaClangDataSection.PragmaLocation, | ||||||
12758 | AttributeCommonInfo::AS_Pragma)); | ||||||
12759 | if (PragmaClangRodataSection.Valid) | ||||||
12760 | VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( | ||||||
12761 | Context, PragmaClangRodataSection.SectionName, | ||||||
12762 | PragmaClangRodataSection.PragmaLocation, | ||||||
12763 | AttributeCommonInfo::AS_Pragma)); | ||||||
12764 | if (PragmaClangRelroSection.Valid) | ||||||
12765 | VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( | ||||||
12766 | Context, PragmaClangRelroSection.SectionName, | ||||||
12767 | PragmaClangRelroSection.PragmaLocation, | ||||||
12768 | AttributeCommonInfo::AS_Pragma)); | ||||||
12769 | } | ||||||
12770 | |||||||
12771 | if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { | ||||||
12772 | for (auto *BD : DD->bindings()) { | ||||||
12773 | FinalizeDeclaration(BD); | ||||||
12774 | } | ||||||
12775 | } | ||||||
12776 | |||||||
12777 | checkAttributesAfterMerging(*this, *VD); | ||||||
12778 | |||||||
12779 | // Perform TLS alignment check here after attributes attached to the variable | ||||||
12780 | // which may affect the alignment have been processed. Only perform the check | ||||||
12781 | // if the target has a maximum TLS alignment (zero means no constraints). | ||||||
12782 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { | ||||||
12783 | // Protect the check so that it's not performed on dependent types and | ||||||
12784 | // dependent alignments (we can't determine the alignment in that case). | ||||||
12785 | if (VD->getTLSKind() && !hasDependentAlignment(VD) && | ||||||
12786 | !VD->isInvalidDecl()) { | ||||||
12787 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); | ||||||
12788 | if (Context.getDeclAlign(VD) > MaxAlignChars) { | ||||||
12789 | Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) | ||||||
12790 | << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD | ||||||
12791 | << (unsigned)MaxAlignChars.getQuantity(); | ||||||
12792 | } | ||||||
12793 | } | ||||||
12794 | } | ||||||
12795 | |||||||
12796 | if (VD->isStaticLocal()) { | ||||||
12797 | CheckStaticLocalForDllExport(VD); | ||||||
12798 | |||||||
12799 | if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { | ||||||
12800 | // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ | ||||||
12801 | // function, only __shared__ variables or variables without any device | ||||||
12802 | // memory qualifiers may be declared with static storage class. | ||||||
12803 | // Note: It is unclear how a function-scope non-const static variable | ||||||
12804 | // without device memory qualifier is implemented, therefore only static | ||||||
12805 | // const variable without device memory qualifier is allowed. | ||||||
12806 | [&]() { | ||||||
12807 | if (!getLangOpts().CUDA) | ||||||
12808 | return; | ||||||
12809 | if (VD->hasAttr<CUDASharedAttr>()) | ||||||
12810 | return; | ||||||
12811 | if (VD->getType().isConstQualified() && | ||||||
12812 | !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) | ||||||
12813 | return; | ||||||
12814 | if (CUDADiagIfDeviceCode(VD->getLocation(), | ||||||
12815 | diag::err_device_static_local_var) | ||||||
12816 | << CurrentCUDATarget()) | ||||||
12817 | VD->setInvalidDecl(); | ||||||
12818 | }(); | ||||||
12819 | } | ||||||
12820 | } | ||||||
12821 | |||||||
12822 | // Perform check for initializers of device-side global variables. | ||||||
12823 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA | ||||||
12824 | // 7.5). We must also apply the same checks to all __shared__ | ||||||
12825 | // variables whether they are local or not. CUDA also allows | ||||||
12826 | // constant initializers for __constant__ and __device__ variables. | ||||||
12827 | if (getLangOpts().CUDA) | ||||||
12828 | checkAllowedCUDAInitializer(VD); | ||||||
12829 | |||||||
12830 | // Grab the dllimport or dllexport attribute off of the VarDecl. | ||||||
12831 | const InheritableAttr *DLLAttr = getDLLAttr(VD); | ||||||
12832 | |||||||
12833 | // Imported static data members cannot be defined out-of-line. | ||||||
12834 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { | ||||||
12835 | if (VD->isStaticDataMember() && VD->isOutOfLine() && | ||||||
12836 | VD->isThisDeclarationADefinition()) { | ||||||
12837 | // We allow definitions of dllimport class template static data members | ||||||
12838 | // with a warning. | ||||||
12839 | CXXRecordDecl *Context = | ||||||
12840 | cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); | ||||||
12841 | bool IsClassTemplateMember = | ||||||
12842 | isa<ClassTemplatePartialSpecializationDecl>(Context) || | ||||||
12843 | Context->getDescribedClassTemplate(); | ||||||
12844 | |||||||
12845 | Diag(VD->getLocation(), | ||||||
12846 | IsClassTemplateMember | ||||||
12847 | ? diag::warn_attribute_dllimport_static_field_definition | ||||||
12848 | : diag::err_attribute_dllimport_static_field_definition); | ||||||
12849 | Diag(IA->getLocation(), diag::note_attribute); | ||||||
12850 | if (!IsClassTemplateMember) | ||||||
12851 | VD->setInvalidDecl(); | ||||||
12852 | } | ||||||
12853 | } | ||||||
12854 | |||||||
12855 | // dllimport/dllexport variables cannot be thread local, their TLS index | ||||||
12856 | // isn't exported with the variable. | ||||||
12857 | if (DLLAttr && VD->getTLSKind()) { | ||||||
12858 | auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | ||||||
12859 | if (F && getDLLAttr(F)) { | ||||||
12860 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 12860, __PRETTY_FUNCTION__)); | ||||||
12861 | // But if this is a static local in a dlimport/dllexport function, the | ||||||
12862 | // function will never be inlined, which means the var would never be | ||||||
12863 | // imported, so having it marked import/export is safe. | ||||||
12864 | } else { | ||||||
12865 | Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD | ||||||
12866 | << DLLAttr; | ||||||
12867 | VD->setInvalidDecl(); | ||||||
12868 | } | ||||||
12869 | } | ||||||
12870 | |||||||
12871 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { | ||||||
12872 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { | ||||||
12873 | Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; | ||||||
12874 | VD->dropAttr<UsedAttr>(); | ||||||
12875 | } | ||||||
12876 | } | ||||||
12877 | |||||||
12878 | const DeclContext *DC = VD->getDeclContext(); | ||||||
12879 | // If there's a #pragma GCC visibility in scope, and this isn't a class | ||||||
12880 | // member, set the visibility of this variable. | ||||||
12881 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) | ||||||
12882 | AddPushedVisibilityAttribute(VD); | ||||||
12883 | |||||||
12884 | // FIXME: Warn on unused var template partial specializations. | ||||||
12885 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) | ||||||
12886 | MarkUnusedFileScopedDecl(VD); | ||||||
12887 | |||||||
12888 | // Now we have parsed the initializer and can update the table of magic | ||||||
12889 | // tag values. | ||||||
12890 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || | ||||||
12891 | !VD->getType()->isIntegralOrEnumerationType()) | ||||||
12892 | return; | ||||||
12893 | |||||||
12894 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { | ||||||
12895 | const Expr *MagicValueExpr = VD->getInit(); | ||||||
12896 | if (!MagicValueExpr) { | ||||||
12897 | continue; | ||||||
12898 | } | ||||||
12899 | llvm::APSInt MagicValueInt; | ||||||
12900 | if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { | ||||||
12901 | Diag(I->getRange().getBegin(), | ||||||
12902 | diag::err_type_tag_for_datatype_not_ice) | ||||||
12903 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | ||||||
12904 | continue; | ||||||
12905 | } | ||||||
12906 | if (MagicValueInt.getActiveBits() > 64) { | ||||||
12907 | Diag(I->getRange().getBegin(), | ||||||
12908 | diag::err_type_tag_for_datatype_too_large) | ||||||
12909 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | ||||||
12910 | continue; | ||||||
12911 | } | ||||||
12912 | uint64_t MagicValue = MagicValueInt.getZExtValue(); | ||||||
12913 | RegisterTypeTagForDatatype(I->getArgumentKind(), | ||||||
12914 | MagicValue, | ||||||
12915 | I->getMatchingCType(), | ||||||
12916 | I->getLayoutCompatible(), | ||||||
12917 | I->getMustBeNull()); | ||||||
12918 | } | ||||||
12919 | } | ||||||
12920 | |||||||
12921 | static bool hasDeducedAuto(DeclaratorDecl *DD) { | ||||||
12922 | auto *VD = dyn_cast<VarDecl>(DD); | ||||||
12923 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); | ||||||
12924 | } | ||||||
12925 | |||||||
12926 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, | ||||||
12927 | ArrayRef<Decl *> Group) { | ||||||
12928 | SmallVector<Decl*, 8> Decls; | ||||||
12929 | |||||||
12930 | if (DS.isTypeSpecOwned()) | ||||||
12931 | Decls.push_back(DS.getRepAsDecl()); | ||||||
12932 | |||||||
12933 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; | ||||||
12934 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; | ||||||
12935 | bool DiagnosedMultipleDecomps = false; | ||||||
12936 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; | ||||||
12937 | bool DiagnosedNonDeducedAuto = false; | ||||||
12938 | |||||||
12939 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | ||||||
12940 | if (Decl *D = Group[i]) { | ||||||
12941 | // For declarators, there are some additional syntactic-ish checks we need | ||||||
12942 | // to perform. | ||||||
12943 | if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { | ||||||
12944 | if (!FirstDeclaratorInGroup) | ||||||
12945 | FirstDeclaratorInGroup = DD; | ||||||
12946 | if (!FirstDecompDeclaratorInGroup) | ||||||
12947 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); | ||||||
12948 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && | ||||||
12949 | !hasDeducedAuto(DD)) | ||||||
12950 | FirstNonDeducedAutoInGroup = DD; | ||||||
12951 | |||||||
12952 | if (FirstDeclaratorInGroup != DD) { | ||||||
12953 | // A decomposition declaration cannot be combined with any other | ||||||
12954 | // declaration in the same group. | ||||||
12955 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { | ||||||
12956 | Diag(FirstDecompDeclaratorInGroup->getLocation(), | ||||||
12957 | diag::err_decomp_decl_not_alone) | ||||||
12958 | << FirstDeclaratorInGroup->getSourceRange() | ||||||
12959 | << DD->getSourceRange(); | ||||||
12960 | DiagnosedMultipleDecomps = true; | ||||||
12961 | } | ||||||
12962 | |||||||
12963 | // A declarator that uses 'auto' in any way other than to declare a | ||||||
12964 | // variable with a deduced type cannot be combined with any other | ||||||
12965 | // declarator in the same group. | ||||||
12966 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { | ||||||
12967 | Diag(FirstNonDeducedAutoInGroup->getLocation(), | ||||||
12968 | diag::err_auto_non_deduced_not_alone) | ||||||
12969 | << FirstNonDeducedAutoInGroup->getType() | ||||||
12970 | ->hasAutoForTrailingReturnType() | ||||||
12971 | << FirstDeclaratorInGroup->getSourceRange() | ||||||
12972 | << DD->getSourceRange(); | ||||||
12973 | DiagnosedNonDeducedAuto = true; | ||||||
12974 | } | ||||||
12975 | } | ||||||
12976 | } | ||||||
12977 | |||||||
12978 | Decls.push_back(D); | ||||||
12979 | } | ||||||
12980 | } | ||||||
12981 | |||||||
12982 | if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { | ||||||
12983 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { | ||||||
12984 | handleTagNumbering(Tag, S); | ||||||
12985 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && | ||||||
12986 | getLangOpts().CPlusPlus) | ||||||
12987 | Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); | ||||||
12988 | } | ||||||
12989 | } | ||||||
12990 | |||||||
12991 | return BuildDeclaratorGroup(Decls); | ||||||
12992 | } | ||||||
12993 | |||||||
12994 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration | ||||||
12995 | /// group, performing any necessary semantic checking. | ||||||
12996 | Sema::DeclGroupPtrTy | ||||||
12997 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { | ||||||
12998 | // C++14 [dcl.spec.auto]p7: (DR1347) | ||||||
12999 | // If the type that replaces the placeholder type is not the same in each | ||||||
13000 | // deduction, the program is ill-formed. | ||||||
13001 | if (Group.size() > 1) { | ||||||
13002 | QualType Deduced; | ||||||
13003 | VarDecl *DeducedDecl = nullptr; | ||||||
13004 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | ||||||
13005 | VarDecl *D = dyn_cast<VarDecl>(Group[i]); | ||||||
13006 | if (!D || D->isInvalidDecl()) | ||||||
13007 | break; | ||||||
13008 | DeducedType *DT = D->getType()->getContainedDeducedType(); | ||||||
13009 | if (!DT || DT->getDeducedType().isNull()) | ||||||
13010 | continue; | ||||||
13011 | if (Deduced.isNull()) { | ||||||
13012 | Deduced = DT->getDeducedType(); | ||||||
13013 | DeducedDecl = D; | ||||||
13014 | } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { | ||||||
13015 | auto *AT = dyn_cast<AutoType>(DT); | ||||||
13016 | Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), | ||||||
13017 | diag::err_auto_different_deductions) | ||||||
13018 | << (AT ? (unsigned)AT->getKeyword() : 3) | ||||||
13019 | << Deduced << DeducedDecl->getDeclName() | ||||||
13020 | << DT->getDeducedType() << D->getDeclName() | ||||||
13021 | << DeducedDecl->getInit()->getSourceRange() | ||||||
13022 | << D->getInit()->getSourceRange(); | ||||||
13023 | D->setInvalidDecl(); | ||||||
13024 | break; | ||||||
13025 | } | ||||||
13026 | } | ||||||
13027 | } | ||||||
13028 | |||||||
13029 | ActOnDocumentableDecls(Group); | ||||||
13030 | |||||||
13031 | return DeclGroupPtrTy::make( | ||||||
13032 | DeclGroupRef::Create(Context, Group.data(), Group.size())); | ||||||
13033 | } | ||||||
13034 | |||||||
13035 | void Sema::ActOnDocumentableDecl(Decl *D) { | ||||||
13036 | ActOnDocumentableDecls(D); | ||||||
13037 | } | ||||||
13038 | |||||||
13039 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { | ||||||
13040 | // Don't parse the comment if Doxygen diagnostics are ignored. | ||||||
13041 | if (Group.empty() || !Group[0]) | ||||||
13042 | return; | ||||||
13043 | |||||||
13044 | if (Diags.isIgnored(diag::warn_doc_param_not_found, | ||||||
13045 | Group[0]->getLocation()) && | ||||||
13046 | Diags.isIgnored(diag::warn_unknown_comment_command_name, | ||||||
13047 | Group[0]->getLocation())) | ||||||
13048 | return; | ||||||
13049 | |||||||
13050 | if (Group.size() >= 2) { | ||||||
13051 | // This is a decl group. Normally it will contain only declarations | ||||||
13052 | // produced from declarator list. But in case we have any definitions or | ||||||
13053 | // additional declaration references: | ||||||
13054 | // 'typedef struct S {} S;' | ||||||
13055 | // 'typedef struct S *S;' | ||||||
13056 | // 'struct S *pS;' | ||||||
13057 | // FinalizeDeclaratorGroup adds these as separate declarations. | ||||||
13058 | Decl *MaybeTagDecl = Group[0]; | ||||||
13059 | if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { | ||||||
13060 | Group = Group.slice(1); | ||||||
13061 | } | ||||||
13062 | } | ||||||
13063 | |||||||
13064 | // FIMXE: We assume every Decl in the group is in the same file. | ||||||
13065 | // This is false when preprocessor constructs the group from decls in | ||||||
13066 | // different files (e. g. macros or #include). | ||||||
13067 | Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); | ||||||
13068 | } | ||||||
13069 | |||||||
13070 | /// Common checks for a parameter-declaration that should apply to both function | ||||||
13071 | /// parameters and non-type template parameters. | ||||||
13072 | void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { | ||||||
13073 | // Check that there are no default arguments inside the type of this | ||||||
13074 | // parameter. | ||||||
13075 | if (getLangOpts().CPlusPlus) | ||||||
13076 | CheckExtraCXXDefaultArguments(D); | ||||||
13077 | |||||||
13078 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||||
13079 | if (D.getCXXScopeSpec().isSet()) { | ||||||
13080 | Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) | ||||||
13081 | << D.getCXXScopeSpec().getRange(); | ||||||
13082 | } | ||||||
13083 | |||||||
13084 | // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a | ||||||
13085 | // simple identifier except [...irrelevant cases...]. | ||||||
13086 | switch (D.getName().getKind()) { | ||||||
13087 | case UnqualifiedIdKind::IK_Identifier: | ||||||
13088 | break; | ||||||
13089 | |||||||
13090 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||||
13091 | case UnqualifiedIdKind::IK_ConversionFunctionId: | ||||||
13092 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||||
13093 | case UnqualifiedIdKind::IK_ConstructorName: | ||||||
13094 | case UnqualifiedIdKind::IK_DestructorName: | ||||||
13095 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||||
13096 | case UnqualifiedIdKind::IK_DeductionGuideName: | ||||||
13097 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) | ||||||
13098 | << GetNameForDeclarator(D).getName(); | ||||||
13099 | break; | ||||||
13100 | |||||||
13101 | case UnqualifiedIdKind::IK_TemplateId: | ||||||
13102 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | ||||||
13103 | // GetNameForDeclarator would not produce a useful name in this case. | ||||||
13104 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); | ||||||
13105 | break; | ||||||
13106 | } | ||||||
13107 | } | ||||||
13108 | |||||||
13109 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() | ||||||
13110 | /// to introduce parameters into function prototype scope. | ||||||
13111 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { | ||||||
13112 | const DeclSpec &DS = D.getDeclSpec(); | ||||||
13113 | |||||||
13114 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. | ||||||
13115 | |||||||
13116 | // C++03 [dcl.stc]p2 also permits 'auto'. | ||||||
13117 | StorageClass SC = SC_None; | ||||||
13118 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { | ||||||
13119 | SC = SC_Register; | ||||||
13120 | // In C++11, the 'register' storage class specifier is deprecated. | ||||||
13121 | // In C++17, it is not allowed, but we tolerate it as an extension. | ||||||
13122 | if (getLangOpts().CPlusPlus11) { | ||||||
13123 | Diag(DS.getStorageClassSpecLoc(), | ||||||
13124 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||||
13125 | : diag::warn_deprecated_register) | ||||||
13126 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
13127 | } | ||||||
13128 | } else if (getLangOpts().CPlusPlus && | ||||||
13129 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { | ||||||
13130 | SC = SC_Auto; | ||||||
13131 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { | ||||||
13132 | Diag(DS.getStorageClassSpecLoc(), | ||||||
13133 | diag::err_invalid_storage_class_in_func_decl); | ||||||
13134 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||||
13135 | } | ||||||
13136 | |||||||
13137 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||||
13138 | Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) | ||||||
13139 | << DeclSpec::getSpecifierName(TSCS); | ||||||
13140 | if (DS.isInlineSpecified()) | ||||||
13141 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
13142 | << getLangOpts().CPlusPlus17; | ||||||
13143 | if (DS.hasConstexprSpecifier()) | ||||||
13144 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||||
13145 | << 0 << D.getDeclSpec().getConstexprSpecifier(); | ||||||
13146 | |||||||
13147 | DiagnoseFunctionSpecifiers(DS); | ||||||
13148 | |||||||
13149 | CheckFunctionOrTemplateParamDeclarator(S, D); | ||||||
13150 | |||||||
13151 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
13152 | QualType parmDeclType = TInfo->getType(); | ||||||
13153 | |||||||
13154 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); | ||||||
13155 | IdentifierInfo *II = D.getIdentifier(); | ||||||
13156 | if (II) { | ||||||
13157 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, | ||||||
13158 | ForVisibleRedeclaration); | ||||||
13159 | LookupName(R, S); | ||||||
13160 | if (R.isSingleResult()) { | ||||||
13161 | NamedDecl *PrevDecl = R.getFoundDecl(); | ||||||
13162 | if (PrevDecl->isTemplateParameter()) { | ||||||
13163 | // Maybe we will complain about the shadowed template parameter. | ||||||
13164 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||||
13165 | // Just pretend that we didn't see the previous declaration. | ||||||
13166 | PrevDecl = nullptr; | ||||||
13167 | } else if (S->isDeclScope(PrevDecl)) { | ||||||
13168 | Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; | ||||||
13169 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
13170 | |||||||
13171 | // Recover by removing the name | ||||||
13172 | II = nullptr; | ||||||
13173 | D.SetIdentifier(nullptr, D.getIdentifierLoc()); | ||||||
13174 | D.setInvalidType(true); | ||||||
13175 | } | ||||||
13176 | } | ||||||
13177 | } | ||||||
13178 | |||||||
13179 | // Temporarily put parameter variables in the translation unit, not | ||||||
13180 | // the enclosing context. This prevents them from accidentally | ||||||
13181 | // looking like class members in C++. | ||||||
13182 | ParmVarDecl *New = | ||||||
13183 | CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), | ||||||
13184 | D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); | ||||||
13185 | |||||||
13186 | if (D.isInvalidType()) | ||||||
13187 | New->setInvalidDecl(); | ||||||
13188 | |||||||
13189 | assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void> (0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13189, __PRETTY_FUNCTION__)); | ||||||
13190 | assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast< void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13190, __PRETTY_FUNCTION__)); | ||||||
13191 | New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, | ||||||
13192 | S->getNextFunctionPrototypeIndex()); | ||||||
13193 | |||||||
13194 | // Add the parameter declaration into this scope. | ||||||
13195 | S->AddDecl(New); | ||||||
13196 | if (II) | ||||||
13197 | IdResolver.AddDecl(New); | ||||||
13198 | |||||||
13199 | ProcessDeclAttributes(S, New, D); | ||||||
13200 | |||||||
13201 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
13202 | Diag(New->getLocation(), diag::err_module_private_local) | ||||||
13203 | << 1 << New->getDeclName() | ||||||
13204 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
13205 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
13206 | |||||||
13207 | if (New->hasAttr<BlocksAttr>()) { | ||||||
13208 | Diag(New->getLocation(), diag::err_block_on_nonlocal); | ||||||
13209 | } | ||||||
13210 | |||||||
13211 | if (getLangOpts().OpenCL) | ||||||
13212 | deduceOpenCLAddressSpace(New); | ||||||
13213 | |||||||
13214 | return New; | ||||||
13215 | } | ||||||
13216 | |||||||
13217 | /// Synthesizes a variable for a parameter arising from a | ||||||
13218 | /// typedef. | ||||||
13219 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, | ||||||
13220 | SourceLocation Loc, | ||||||
13221 | QualType T) { | ||||||
13222 | /* FIXME: setting StartLoc == Loc. | ||||||
13223 | Would it be worth to modify callers so as to provide proper source | ||||||
13224 | location for the unnamed parameters, embedding the parameter's type? */ | ||||||
13225 | ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, | ||||||
13226 | T, Context.getTrivialTypeSourceInfo(T, Loc), | ||||||
13227 | SC_None, nullptr); | ||||||
13228 | Param->setImplicit(); | ||||||
13229 | return Param; | ||||||
13230 | } | ||||||
13231 | |||||||
13232 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { | ||||||
13233 | // Don't diagnose unused-parameter errors in template instantiations; we | ||||||
13234 | // will already have done so in the template itself. | ||||||
13235 | if (inTemplateInstantiation()) | ||||||
13236 | return; | ||||||
13237 | |||||||
13238 | for (const ParmVarDecl *Parameter : Parameters) { | ||||||
13239 | if (!Parameter->isReferenced() && Parameter->getDeclName() && | ||||||
13240 | !Parameter->hasAttr<UnusedAttr>()) { | ||||||
13241 | Diag(Parameter->getLocation(), diag::warn_unused_parameter) | ||||||
13242 | << Parameter->getDeclName(); | ||||||
13243 | } | ||||||
13244 | } | ||||||
13245 | } | ||||||
13246 | |||||||
13247 | void Sema::DiagnoseSizeOfParametersAndReturnValue( | ||||||
13248 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { | ||||||
13249 | if (LangOpts.NumLargeByValueCopy == 0) // No check. | ||||||
13250 | return; | ||||||
13251 | |||||||
13252 | // Warn if the return value is pass-by-value and larger than the specified | ||||||
13253 | // threshold. | ||||||
13254 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { | ||||||
13255 | unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); | ||||||
13256 | if (Size > LangOpts.NumLargeByValueCopy) | ||||||
13257 | Diag(D->getLocation(), diag::warn_return_value_size) | ||||||
13258 | << D->getDeclName() << Size; | ||||||
13259 | } | ||||||
13260 | |||||||
13261 | // Warn if any parameter is pass-by-value and larger than the specified | ||||||
13262 | // threshold. | ||||||
13263 | for (const ParmVarDecl *Parameter : Parameters) { | ||||||
13264 | QualType T = Parameter->getType(); | ||||||
13265 | if (T->isDependentType() || !T.isPODType(Context)) | ||||||
13266 | continue; | ||||||
13267 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); | ||||||
13268 | if (Size > LangOpts.NumLargeByValueCopy) | ||||||
13269 | Diag(Parameter->getLocation(), diag::warn_parameter_size) | ||||||
13270 | << Parameter->getDeclName() << Size; | ||||||
13271 | } | ||||||
13272 | } | ||||||
13273 | |||||||
13274 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, | ||||||
13275 | SourceLocation NameLoc, IdentifierInfo *Name, | ||||||
13276 | QualType T, TypeSourceInfo *TSInfo, | ||||||
13277 | StorageClass SC) { | ||||||
13278 | // In ARC, infer a lifetime qualifier for appropriate parameter types. | ||||||
13279 | if (getLangOpts().ObjCAutoRefCount && | ||||||
13280 | T.getObjCLifetime() == Qualifiers::OCL_None && | ||||||
13281 | T->isObjCLifetimeType()) { | ||||||
13282 | |||||||
13283 | Qualifiers::ObjCLifetime lifetime; | ||||||
13284 | |||||||
13285 | // Special cases for arrays: | ||||||
13286 | // - if it's const, use __unsafe_unretained | ||||||
13287 | // - otherwise, it's an error | ||||||
13288 | if (T->isArrayType()) { | ||||||
13289 | if (!T.isConstQualified()) { | ||||||
13290 | if (DelayedDiagnostics.shouldDelayDiagnostics()) | ||||||
13291 | DelayedDiagnostics.add( | ||||||
13292 | sema::DelayedDiagnostic::makeForbiddenType( | ||||||
13293 | NameLoc, diag::err_arc_array_param_no_ownership, T, false)); | ||||||
13294 | else | ||||||
13295 | Diag(NameLoc, diag::err_arc_array_param_no_ownership) | ||||||
13296 | << TSInfo->getTypeLoc().getSourceRange(); | ||||||
13297 | } | ||||||
13298 | lifetime = Qualifiers::OCL_ExplicitNone; | ||||||
13299 | } else { | ||||||
13300 | lifetime = T->getObjCARCImplicitLifetime(); | ||||||
13301 | } | ||||||
13302 | T = Context.getLifetimeQualifiedType(T, lifetime); | ||||||
13303 | } | ||||||
13304 | |||||||
13305 | ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, | ||||||
13306 | Context.getAdjustedParameterType(T), | ||||||
13307 | TSInfo, SC, nullptr); | ||||||
13308 | |||||||
13309 | // Make a note if we created a new pack in the scope of a lambda, so that | ||||||
13310 | // we know that references to that pack must also be expanded within the | ||||||
13311 | // lambda scope. | ||||||
13312 | if (New->isParameterPack()) | ||||||
13313 | if (auto *LSI = getEnclosingLambda()) | ||||||
13314 | LSI->LocalPacks.push_back(New); | ||||||
13315 | |||||||
13316 | if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||||
13317 | New->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
13318 | checkNonTrivialCUnion(New->getType(), New->getLocation(), | ||||||
13319 | NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); | ||||||
13320 | |||||||
13321 | // Parameters can not be abstract class types. | ||||||
13322 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||||
13323 | // the class has been completely parsed. | ||||||
13324 | if (!CurContext->isRecord() && | ||||||
13325 | RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, | ||||||
13326 | AbstractParamType)) | ||||||
13327 | New->setInvalidDecl(); | ||||||
13328 | |||||||
13329 | // Parameter declarators cannot be interface types. All ObjC objects are | ||||||
13330 | // passed by reference. | ||||||
13331 | if (T->isObjCObjectType()) { | ||||||
13332 | SourceLocation TypeEndLoc = | ||||||
13333 | getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); | ||||||
13334 | Diag(NameLoc, | ||||||
13335 | diag::err_object_cannot_be_passed_returned_by_value) << 1 << T | ||||||
13336 | << FixItHint::CreateInsertion(TypeEndLoc, "*"); | ||||||
13337 | T = Context.getObjCObjectPointerType(T); | ||||||
13338 | New->setType(T); | ||||||
13339 | } | ||||||
13340 | |||||||
13341 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage | ||||||
13342 | // duration shall not be qualified by an address-space qualifier." | ||||||
13343 | // Since all parameters have automatic store duration, they can not have | ||||||
13344 | // an address space. | ||||||
13345 | if (T.getAddressSpace() != LangAS::Default && | ||||||
13346 | // OpenCL allows function arguments declared to be an array of a type | ||||||
13347 | // to be qualified with an address space. | ||||||
13348 | !(getLangOpts().OpenCL && | ||||||
13349 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { | ||||||
13350 | Diag(NameLoc, diag::err_arg_with_address_space); | ||||||
13351 | New->setInvalidDecl(); | ||||||
13352 | } | ||||||
13353 | |||||||
13354 | return New; | ||||||
13355 | } | ||||||
13356 | |||||||
13357 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, | ||||||
13358 | SourceLocation LocAfterDecls) { | ||||||
13359 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | ||||||
13360 | |||||||
13361 | // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' | ||||||
13362 | // for a K&R function. | ||||||
13363 | if (!FTI.hasPrototype) { | ||||||
13364 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { | ||||||
13365 | --i; | ||||||
13366 | if (FTI.Params[i].Param == nullptr) { | ||||||
13367 | SmallString<256> Code; | ||||||
13368 | llvm::raw_svector_ostream(Code) | ||||||
13369 | << " int " << FTI.Params[i].Ident->getName() << ";\n"; | ||||||
13370 | Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) | ||||||
13371 | << FTI.Params[i].Ident | ||||||
13372 | << FixItHint::CreateInsertion(LocAfterDecls, Code); | ||||||
13373 | |||||||
13374 | // Implicitly declare the argument as type 'int' for lack of a better | ||||||
13375 | // type. | ||||||
13376 | AttributeFactory attrs; | ||||||
13377 | DeclSpec DS(attrs); | ||||||
13378 | const char* PrevSpec; // unused | ||||||
13379 | unsigned DiagID; // unused | ||||||
13380 | DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, | ||||||
13381 | DiagID, Context.getPrintingPolicy()); | ||||||
13382 | // Use the identifier location for the type source range. | ||||||
13383 | DS.SetRangeStart(FTI.Params[i].IdentLoc); | ||||||
13384 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); | ||||||
13385 | Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); | ||||||
13386 | ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); | ||||||
13387 | FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); | ||||||
13388 | } | ||||||
13389 | } | ||||||
13390 | } | ||||||
13391 | } | ||||||
13392 | |||||||
13393 | Decl * | ||||||
13394 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, | ||||||
13395 | MultiTemplateParamsArg TemplateParameterLists, | ||||||
13396 | SkipBodyInfo *SkipBody) { | ||||||
13397 | assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((getCurFunctionDecl() == nullptr && "Function parsing confused" ) ? static_cast<void> (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13397, __PRETTY_FUNCTION__)); | ||||||
13398 | assert(D.isFunctionDeclarator() && "Not a function declarator!")((D.isFunctionDeclarator() && "Not a function declarator!" ) ? static_cast<void> (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13398, __PRETTY_FUNCTION__)); | ||||||
13399 | Scope *ParentScope = FnBodyScope->getParent(); | ||||||
13400 | |||||||
13401 | D.setFunctionDefinitionKind(FDK_Definition); | ||||||
13402 | Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); | ||||||
13403 | return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); | ||||||
13404 | } | ||||||
13405 | |||||||
13406 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { | ||||||
13407 | Consumer.HandleInlineFunctionDefinition(D); | ||||||
13408 | } | ||||||
13409 | |||||||
13410 | static bool | ||||||
13411 | ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, | ||||||
13412 | const FunctionDecl *&PossiblePrototype) { | ||||||
13413 | // Don't warn about invalid declarations. | ||||||
13414 | if (FD->isInvalidDecl()) | ||||||
13415 | return false; | ||||||
13416 | |||||||
13417 | // Or declarations that aren't global. | ||||||
13418 | if (!FD->isGlobal()) | ||||||
13419 | return false; | ||||||
13420 | |||||||
13421 | // Don't warn about C++ member functions. | ||||||
13422 | if (isa<CXXMethodDecl>(FD)) | ||||||
13423 | return false; | ||||||
13424 | |||||||
13425 | // Don't warn about 'main'. | ||||||
13426 | if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) | ||||||
13427 | if (IdentifierInfo *II = FD->getIdentifier()) | ||||||
13428 | if (II->isStr("main")) | ||||||
13429 | return false; | ||||||
13430 | |||||||
13431 | // Don't warn about inline functions. | ||||||
13432 | if (FD->isInlined()) | ||||||
13433 | return false; | ||||||
13434 | |||||||
13435 | // Don't warn about function templates. | ||||||
13436 | if (FD->getDescribedFunctionTemplate()) | ||||||
13437 | return false; | ||||||
13438 | |||||||
13439 | // Don't warn about function template specializations. | ||||||
13440 | if (FD->isFunctionTemplateSpecialization()) | ||||||
13441 | return false; | ||||||
13442 | |||||||
13443 | // Don't warn for OpenCL kernels. | ||||||
13444 | if (FD->hasAttr<OpenCLKernelAttr>()) | ||||||
13445 | return false; | ||||||
13446 | |||||||
13447 | // Don't warn on explicitly deleted functions. | ||||||
13448 | if (FD->isDeleted()) | ||||||
13449 | return false; | ||||||
13450 | |||||||
13451 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); | ||||||
13452 | Prev; Prev = Prev->getPreviousDecl()) { | ||||||
13453 | // Ignore any declarations that occur in function or method | ||||||
13454 | // scope, because they aren't visible from the header. | ||||||
13455 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||
13456 | continue; | ||||||
13457 | |||||||
13458 | PossiblePrototype = Prev; | ||||||
13459 | return Prev->getType()->isFunctionNoProtoType(); | ||||||
13460 | } | ||||||
13461 | |||||||
13462 | return true; | ||||||
13463 | } | ||||||
13464 | |||||||
13465 | void | ||||||
13466 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, | ||||||
13467 | const FunctionDecl *EffectiveDefinition, | ||||||
13468 | SkipBodyInfo *SkipBody) { | ||||||
13469 | const FunctionDecl *Definition = EffectiveDefinition; | ||||||
13470 | if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { | ||||||
13471 | // If this is a friend function defined in a class template, it does not | ||||||
13472 | // have a body until it is used, nevertheless it is a definition, see | ||||||
13473 | // [temp.inst]p2: | ||||||
13474 | // | ||||||
13475 | // ... for the purpose of determining whether an instantiated redeclaration | ||||||
13476 | // is valid according to [basic.def.odr] and [class.mem], a declaration that | ||||||
13477 | // corresponds to a definition in the template is considered to be a | ||||||
13478 | // definition. | ||||||
13479 | // | ||||||
13480 | // The following code must produce redefinition error: | ||||||
13481 | // | ||||||
13482 | // template<typename T> struct C20 { friend void func_20() {} }; | ||||||
13483 | // C20<int> c20i; | ||||||
13484 | // void func_20() {} | ||||||
13485 | // | ||||||
13486 | for (auto I : FD->redecls()) { | ||||||
13487 | if (I != FD && !I->isInvalidDecl() && | ||||||
13488 | I->getFriendObjectKind() != Decl::FOK_None) { | ||||||
13489 | if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { | ||||||
13490 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { | ||||||
13491 | // A merged copy of the same function, instantiated as a member of | ||||||
13492 | // the same class, is OK. | ||||||
13493 | if (declaresSameEntity(OrigFD, Original) && | ||||||
13494 | declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), | ||||||
13495 | cast<Decl>(FD->getLexicalDeclContext()))) | ||||||
13496 | continue; | ||||||
13497 | } | ||||||
13498 | |||||||
13499 | if (Original->isThisDeclarationADefinition()) { | ||||||
13500 | Definition = I; | ||||||
13501 | break; | ||||||
13502 | } | ||||||
13503 | } | ||||||
13504 | } | ||||||
13505 | } | ||||||
13506 | } | ||||||
13507 | |||||||
13508 | if (!Definition) | ||||||
13509 | // Similar to friend functions a friend function template may be a | ||||||
13510 | // definition and do not have a body if it is instantiated in a class | ||||||
13511 | // template. | ||||||
13512 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { | ||||||
13513 | for (auto I : FTD->redecls()) { | ||||||
13514 | auto D = cast<FunctionTemplateDecl>(I); | ||||||
13515 | if (D != FTD) { | ||||||
13516 | assert(!D->isThisDeclarationADefinition() &&((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13517, __PRETTY_FUNCTION__)) | ||||||
13517 | "More than one definition in redeclaration chain")((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13517, __PRETTY_FUNCTION__)); | ||||||
13518 | if (D->getFriendObjectKind() != Decl::FOK_None) | ||||||
13519 | if (FunctionTemplateDecl *FT = | ||||||
13520 | D->getInstantiatedFromMemberTemplate()) { | ||||||
13521 | if (FT->isThisDeclarationADefinition()) { | ||||||
13522 | Definition = D->getTemplatedDecl(); | ||||||
13523 | break; | ||||||
13524 | } | ||||||
13525 | } | ||||||
13526 | } | ||||||
13527 | } | ||||||
13528 | } | ||||||
13529 | |||||||
13530 | if (!Definition) | ||||||
13531 | return; | ||||||
13532 | |||||||
13533 | if (canRedefineFunction(Definition, getLangOpts())) | ||||||
13534 | return; | ||||||
13535 | |||||||
13536 | // Don't emit an error when this is redefinition of a typo-corrected | ||||||
13537 | // definition. | ||||||
13538 | if (TypoCorrectedFunctionDefinitions.count(Definition)) | ||||||
13539 | return; | ||||||
13540 | |||||||
13541 | // If we don't have a visible definition of the function, and it's inline or | ||||||
13542 | // a template, skip the new definition. | ||||||
13543 | if (SkipBody && !hasVisibleDefinition(Definition) && | ||||||
13544 | (Definition->getFormalLinkage() == InternalLinkage || | ||||||
13545 | Definition->isInlined() || | ||||||
13546 | Definition->getDescribedFunctionTemplate() || | ||||||
13547 | Definition->getNumTemplateParameterLists())) { | ||||||
13548 | SkipBody->ShouldSkip = true; | ||||||
13549 | SkipBody->Previous = const_cast<FunctionDecl*>(Definition); | ||||||
13550 | if (auto *TD = Definition->getDescribedFunctionTemplate()) | ||||||
13551 | makeMergedDefinitionVisible(TD); | ||||||
13552 | makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); | ||||||
13553 | return; | ||||||
13554 | } | ||||||
13555 | |||||||
13556 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && | ||||||
13557 | Definition->getStorageClass() == SC_Extern) | ||||||
13558 | Diag(FD->getLocation(), diag::err_redefinition_extern_inline) | ||||||
13559 | << FD->getDeclName() << getLangOpts().CPlusPlus; | ||||||
13560 | else | ||||||
13561 | Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); | ||||||
13562 | |||||||
13563 | Diag(Definition->getLocation(), diag::note_previous_definition); | ||||||
13564 | FD->setInvalidDecl(); | ||||||
13565 | } | ||||||
13566 | |||||||
13567 | static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, | ||||||
13568 | Sema &S) { | ||||||
13569 | CXXRecordDecl *const LambdaClass = CallOperator->getParent(); | ||||||
13570 | |||||||
13571 | LambdaScopeInfo *LSI = S.PushLambdaScope(); | ||||||
13572 | LSI->CallOperator = CallOperator; | ||||||
13573 | LSI->Lambda = LambdaClass; | ||||||
13574 | LSI->ReturnType = CallOperator->getReturnType(); | ||||||
13575 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); | ||||||
13576 | |||||||
13577 | if (LCD == LCD_None) | ||||||
13578 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; | ||||||
13579 | else if (LCD == LCD_ByCopy) | ||||||
13580 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; | ||||||
13581 | else if (LCD == LCD_ByRef) | ||||||
13582 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; | ||||||
13583 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); | ||||||
13584 | |||||||
13585 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); | ||||||
13586 | LSI->Mutable = !CallOperator->isConst(); | ||||||
13587 | |||||||
13588 | // Add the captures to the LSI so they can be noted as already | ||||||
13589 | // captured within tryCaptureVar. | ||||||
13590 | auto I = LambdaClass->field_begin(); | ||||||
13591 | for (const auto &C : LambdaClass->captures()) { | ||||||
13592 | if (C.capturesVariable()) { | ||||||
13593 | VarDecl *VD = C.getCapturedVar(); | ||||||
13594 | if (VD->isInitCapture()) | ||||||
13595 | S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); | ||||||
13596 | QualType CaptureType = VD->getType(); | ||||||
13597 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; | ||||||
13598 | LSI->addCapture(VD, /*IsBlock*/false, ByRef, | ||||||
13599 | /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), | ||||||
13600 | /*EllipsisLoc*/C.isPackExpansion() | ||||||
13601 | ? C.getEllipsisLoc() : SourceLocation(), | ||||||
13602 | CaptureType, /*Invalid*/false); | ||||||
13603 | |||||||
13604 | } else if (C.capturesThis()) { | ||||||
13605 | LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), | ||||||
13606 | C.getCaptureKind() == LCK_StarThis); | ||||||
13607 | } else { | ||||||
13608 | LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), | ||||||
13609 | I->getType()); | ||||||
13610 | } | ||||||
13611 | ++I; | ||||||
13612 | } | ||||||
13613 | } | ||||||
13614 | |||||||
13615 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, | ||||||
13616 | SkipBodyInfo *SkipBody) { | ||||||
13617 | if (!D) { | ||||||
13618 | // Parsing the function declaration failed in some way. Push on a fake scope | ||||||
13619 | // anyway so we can try to parse the function body. | ||||||
13620 | PushFunctionScope(); | ||||||
13621 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||||
13622 | return D; | ||||||
13623 | } | ||||||
13624 | |||||||
13625 | FunctionDecl *FD = nullptr; | ||||||
13626 | |||||||
13627 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) | ||||||
13628 | FD = FunTmpl->getTemplatedDecl(); | ||||||
13629 | else | ||||||
13630 | FD = cast<FunctionDecl>(D); | ||||||
13631 | |||||||
13632 | // Do not push if it is a lambda because one is already pushed when building | ||||||
13633 | // the lambda in ActOnStartOfLambdaDefinition(). | ||||||
13634 | if (!isLambdaCallOperator(FD)) | ||||||
13635 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||||
13636 | |||||||
13637 | // Check for defining attributes before the check for redefinition. | ||||||
13638 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { | ||||||
13639 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; | ||||||
13640 | FD->dropAttr<AliasAttr>(); | ||||||
13641 | FD->setInvalidDecl(); | ||||||
13642 | } | ||||||
13643 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { | ||||||
13644 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; | ||||||
13645 | FD->dropAttr<IFuncAttr>(); | ||||||
13646 | FD->setInvalidDecl(); | ||||||
13647 | } | ||||||
13648 | |||||||
13649 | // See if this is a redefinition. If 'will have body' is already set, then | ||||||
13650 | // these checks were already performed when it was set. | ||||||
13651 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { | ||||||
13652 | CheckForFunctionRedefinition(FD, nullptr, SkipBody); | ||||||
13653 | |||||||
13654 | // If we're skipping the body, we're done. Don't enter the scope. | ||||||
13655 | if (SkipBody && SkipBody->ShouldSkip) | ||||||
13656 | return D; | ||||||
13657 | } | ||||||
13658 | |||||||
13659 | // Mark this function as "will have a body eventually". This lets users to | ||||||
13660 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing | ||||||
13661 | // this function. | ||||||
13662 | FD->setWillHaveBody(); | ||||||
13663 | |||||||
13664 | // If we are instantiating a generic lambda call operator, push | ||||||
13665 | // a LambdaScopeInfo onto the function stack. But use the information | ||||||
13666 | // that's already been calculated (ActOnLambdaExpr) to prime the current | ||||||
13667 | // LambdaScopeInfo. | ||||||
13668 | // When the template operator is being specialized, the LambdaScopeInfo, | ||||||
13669 | // has to be properly restored so that tryCaptureVariable doesn't try | ||||||
13670 | // and capture any new variables. In addition when calculating potential | ||||||
13671 | // captures during transformation of nested lambdas, it is necessary to | ||||||
13672 | // have the LSI properly restored. | ||||||
13673 | if (isGenericLambdaCallOperatorSpecialization(FD)) { | ||||||
13674 | assert(inTemplateInstantiation() &&((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13676, __PRETTY_FUNCTION__)) | ||||||
13675 | "There should be an active template instantiation on the stack "((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13676, __PRETTY_FUNCTION__)) | ||||||
13676 | "when instantiating a generic lambda!")((inTemplateInstantiation() && "There should be an active template instantiation on the stack " "when instantiating a generic lambda!") ? static_cast<void > (0) : __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13676, __PRETTY_FUNCTION__)); | ||||||
13677 | RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); | ||||||
13678 | } else { | ||||||
13679 | // Enter a new function scope | ||||||
13680 | PushFunctionScope(); | ||||||
13681 | } | ||||||
13682 | |||||||
13683 | // Builtin functions cannot be defined. | ||||||
13684 | if (unsigned BuiltinID = FD->getBuiltinID()) { | ||||||
13685 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && | ||||||
13686 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { | ||||||
13687 | Diag(FD->getLocation(), diag::err_builtin_definition) << FD; | ||||||
13688 | FD->setInvalidDecl(); | ||||||
13689 | } | ||||||
13690 | } | ||||||
13691 | |||||||
13692 | // The return type of a function definition must be complete | ||||||
13693 | // (C99 6.9.1p3, C++ [dcl.fct]p6). | ||||||
13694 | QualType ResultType = FD->getReturnType(); | ||||||
13695 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && | ||||||
13696 | !FD->isInvalidDecl() && | ||||||
13697 | RequireCompleteType(FD->getLocation(), ResultType, | ||||||
13698 | diag::err_func_def_incomplete_result)) | ||||||
13699 | FD->setInvalidDecl(); | ||||||
13700 | |||||||
13701 | if (FnBodyScope) | ||||||
13702 | PushDeclContext(FnBodyScope, FD); | ||||||
13703 | |||||||
13704 | // Check the validity of our function parameters | ||||||
13705 | CheckParmsForFunctionDef(FD->parameters(), | ||||||
13706 | /*CheckParameterNames=*/true); | ||||||
13707 | |||||||
13708 | // Add non-parameter declarations already in the function to the current | ||||||
13709 | // scope. | ||||||
13710 | if (FnBodyScope) { | ||||||
13711 | for (Decl *NPD : FD->decls()) { | ||||||
13712 | auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); | ||||||
13713 | if (!NonParmDecl) | ||||||
13714 | continue; | ||||||
13715 | assert(!isa<ParmVarDecl>(NonParmDecl) &&((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13716, __PRETTY_FUNCTION__)) | ||||||
13716 | "parameters should not be in newly created FD yet")((!isa<ParmVarDecl>(NonParmDecl) && "parameters should not be in newly created FD yet" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13716, __PRETTY_FUNCTION__)); | ||||||
13717 | |||||||
13718 | // If the decl has a name, make it accessible in the current scope. | ||||||
13719 | if (NonParmDecl->getDeclName()) | ||||||
13720 | PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); | ||||||
13721 | |||||||
13722 | // Similarly, dive into enums and fish their constants out, making them | ||||||
13723 | // accessible in this scope. | ||||||
13724 | if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { | ||||||
13725 | for (auto *EI : ED->enumerators()) | ||||||
13726 | PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); | ||||||
13727 | } | ||||||
13728 | } | ||||||
13729 | } | ||||||
13730 | |||||||
13731 | // Introduce our parameters into the function scope | ||||||
13732 | for (auto Param : FD->parameters()) { | ||||||
13733 | Param->setOwningFunction(FD); | ||||||
13734 | |||||||
13735 | // If this has an identifier, add it to the scope stack. | ||||||
13736 | if (Param->getIdentifier() && FnBodyScope) { | ||||||
13737 | CheckShadow(FnBodyScope, Param); | ||||||
13738 | |||||||
13739 | PushOnScopeChains(Param, FnBodyScope); | ||||||
13740 | } | ||||||
13741 | } | ||||||
13742 | |||||||
13743 | // Ensure that the function's exception specification is instantiated. | ||||||
13744 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) | ||||||
13745 | ResolveExceptionSpec(D->getLocation(), FPT); | ||||||
13746 | |||||||
13747 | // dllimport cannot be applied to non-inline function definitions. | ||||||
13748 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && | ||||||
13749 | !FD->isTemplateInstantiation()) { | ||||||
13750 | assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void > (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 13750, __PRETTY_FUNCTION__)); | ||||||
13751 | Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); | ||||||
13752 | FD->setInvalidDecl(); | ||||||
13753 | return D; | ||||||
13754 | } | ||||||
13755 | // We want to attach documentation to original Decl (which might be | ||||||
13756 | // a function template). | ||||||
13757 | ActOnDocumentableDecl(D); | ||||||
13758 | if (getCurLexicalContext()->isObjCContainer() && | ||||||
13759 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && | ||||||
13760 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) | ||||||
13761 | Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); | ||||||
13762 | |||||||
13763 | return D; | ||||||
13764 | } | ||||||
13765 | |||||||
13766 | /// Given the set of return statements within a function body, | ||||||
13767 | /// compute the variables that are subject to the named return value | ||||||
13768 | /// optimization. | ||||||
13769 | /// | ||||||
13770 | /// Each of the variables that is subject to the named return value | ||||||
13771 | /// optimization will be marked as NRVO variables in the AST, and any | ||||||
13772 | /// return statement that has a marked NRVO variable as its NRVO candidate can | ||||||
13773 | /// use the named return value optimization. | ||||||
13774 | /// | ||||||
13775 | /// This function applies a very simplistic algorithm for NRVO: if every return | ||||||
13776 | /// statement in the scope of a variable has the same NRVO candidate, that | ||||||
13777 | /// candidate is an NRVO variable. | ||||||
13778 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { | ||||||
13779 | ReturnStmt **Returns = Scope->Returns.data(); | ||||||
13780 | |||||||
13781 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { | ||||||
13782 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { | ||||||
13783 | if (!NRVOCandidate->isNRVOVariable()) | ||||||
13784 | Returns[I]->setNRVOCandidate(nullptr); | ||||||
13785 | } | ||||||
13786 | } | ||||||
13787 | } | ||||||
13788 | |||||||
13789 | bool Sema::canDelayFunctionBody(const Declarator &D) { | ||||||
13790 | // We can't delay parsing the body of a constexpr function template (yet). | ||||||
13791 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||||
13792 | return false; | ||||||
13793 | |||||||
13794 | // We can't delay parsing the body of a function template with a deduced | ||||||
13795 | // return type (yet). | ||||||
13796 | if (D.getDeclSpec().hasAutoTypeSpec()) { | ||||||
13797 | // If the placeholder introduces a non-deduced trailing return type, | ||||||
13798 | // we can still delay parsing it. | ||||||
13799 | if (D.getNumTypeObjects()) { | ||||||
13800 | const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); | ||||||
13801 | if (Outer.Kind == DeclaratorChunk::Function && | ||||||
13802 | Outer.Fun.hasTrailingReturnType()) { | ||||||
13803 | QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); | ||||||
13804 | return Ty.isNull() || !Ty->isUndeducedType(); | ||||||
13805 | } | ||||||
13806 | } | ||||||
13807 | return false; | ||||||
13808 | } | ||||||
13809 | |||||||
13810 | return true; | ||||||
13811 | } | ||||||
13812 | |||||||
13813 | bool Sema::canSkipFunctionBody(Decl *D) { | ||||||
13814 | // We cannot skip the body of a function (or function template) which is | ||||||
13815 | // constexpr, since we may need to evaluate its body in order to parse the | ||||||
13816 | // rest of the file. | ||||||
13817 | // We cannot skip the body of a function with an undeduced return type, | ||||||
13818 | // because any callers of that function need to know the type. | ||||||
13819 | if (const FunctionDecl *FD = D->getAsFunction()) { | ||||||
13820 | if (FD->isConstexpr()) | ||||||
13821 | return false; | ||||||
13822 | // We can't simply call Type::isUndeducedType here, because inside template | ||||||
13823 | // auto can be deduced to a dependent type, which is not considered | ||||||
13824 | // "undeduced". | ||||||
13825 | if (FD->getReturnType()->getContainedDeducedType()) | ||||||
13826 | return false; | ||||||
13827 | } | ||||||
13828 | return Consumer.shouldSkipFunctionBody(D); | ||||||
13829 | } | ||||||
13830 | |||||||
13831 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { | ||||||
13832 | if (!Decl) | ||||||
13833 | return nullptr; | ||||||
13834 | if (FunctionDecl *FD = Decl->getAsFunction()) | ||||||
13835 | FD->setHasSkippedBody(); | ||||||
13836 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) | ||||||
13837 | MD->setHasSkippedBody(); | ||||||
13838 | return Decl; | ||||||
13839 | } | ||||||
13840 | |||||||
13841 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { | ||||||
13842 | return ActOnFinishFunctionBody(D, BodyArg, false); | ||||||
13843 | } | ||||||
13844 | |||||||
13845 | /// RAII object that pops an ExpressionEvaluationContext when exiting a function | ||||||
13846 | /// body. | ||||||
13847 | class ExitFunctionBodyRAII { | ||||||
13848 | public: | ||||||
13849 | ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} | ||||||
13850 | ~ExitFunctionBodyRAII() { | ||||||
13851 | if (!IsLambda) | ||||||
13852 | S.PopExpressionEvaluationContext(); | ||||||
13853 | } | ||||||
13854 | |||||||
13855 | private: | ||||||
13856 | Sema &S; | ||||||
13857 | bool IsLambda = false; | ||||||
13858 | }; | ||||||
13859 | |||||||
13860 | static void diagnoseImplicitlyRetainedSelf(Sema &S) { | ||||||
13861 | llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; | ||||||
13862 | |||||||
13863 | auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { | ||||||
13864 | if (EscapeInfo.count(BD)) | ||||||
13865 | return EscapeInfo[BD]; | ||||||
13866 | |||||||
13867 | bool R = false; | ||||||
13868 | const BlockDecl *CurBD = BD; | ||||||
13869 | |||||||
13870 | do { | ||||||
13871 | R = !CurBD->doesNotEscape(); | ||||||
13872 | if (R) | ||||||
13873 | break; | ||||||
13874 | CurBD = CurBD->getParent()->getInnermostBlockDecl(); | ||||||
13875 | } while (CurBD); | ||||||
13876 | |||||||
13877 | return EscapeInfo[BD] = R; | ||||||
13878 | }; | ||||||
13879 | |||||||
13880 | // If the location where 'self' is implicitly retained is inside a escaping | ||||||
13881 | // block, emit a diagnostic. | ||||||
13882 | for (const std::pair<SourceLocation, const BlockDecl *> &P : | ||||||
13883 | S.ImplicitlyRetainedSelfLocs) | ||||||
13884 | if (IsOrNestedInEscapingBlock(P.second)) | ||||||
13885 | S.Diag(P.first, diag::warn_implicitly_retains_self) | ||||||
13886 | << FixItHint::CreateInsertion(P.first, "self->"); | ||||||
13887 | } | ||||||
13888 | |||||||
13889 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, | ||||||
13890 | bool IsInstantiation) { | ||||||
13891 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; | ||||||
| |||||||
13892 | |||||||
13893 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||||
13894 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; | ||||||
13895 | |||||||
13896 | if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) | ||||||
13897 | CheckCompletedCoroutineBody(FD, Body); | ||||||
13898 | |||||||
13899 | // Do not call PopExpressionEvaluationContext() if it is a lambda because one | ||||||
13900 | // is already popped when finishing the lambda in BuildLambdaExpr(). This is | ||||||
13901 | // meant to pop the context added in ActOnStartOfFunctionDef(). | ||||||
13902 | ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); | ||||||
13903 | |||||||
13904 | if (FD
| ||||||
13905 | FD->setBody(Body); | ||||||
13906 | FD->setWillHaveBody(false); | ||||||
13907 | |||||||
13908 | if (getLangOpts().CPlusPlus14) { | ||||||
13909 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && | ||||||
13910 | FD->getReturnType()->isUndeducedType()) { | ||||||
13911 | // If the function has a deduced result type but contains no 'return' | ||||||
13912 | // statements, the result type as written must be exactly 'auto', and | ||||||
13913 | // the deduced result type is 'void'. | ||||||
13914 | if (!FD->getReturnType()->getAs<AutoType>()) { | ||||||
13915 | Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) | ||||||
13916 | << FD->getReturnType(); | ||||||
13917 | FD->setInvalidDecl(); | ||||||
13918 | } else { | ||||||
13919 | // Substitute 'void' for the 'auto' in the type. | ||||||
13920 | TypeLoc ResultType = getReturnTypeLoc(FD); | ||||||
13921 | Context.adjustDeducedFunctionResultType( | ||||||
13922 | FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); | ||||||
13923 | } | ||||||
13924 | } | ||||||
13925 | } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { | ||||||
13926 | // In C++11, we don't use 'auto' deduction rules for lambda call | ||||||
13927 | // operators because we don't support return type deduction. | ||||||
13928 | auto *LSI = getCurLambda(); | ||||||
13929 | if (LSI->HasImplicitReturnType) { | ||||||
13930 | deduceClosureReturnType(*LSI); | ||||||
13931 | |||||||
13932 | // C++11 [expr.prim.lambda]p4: | ||||||
13933 | // [...] if there are no return statements in the compound-statement | ||||||
13934 | // [the deduced type is] the type void | ||||||
13935 | QualType RetType = | ||||||
13936 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; | ||||||
13937 | |||||||
13938 | // Update the return type to the deduced type. | ||||||
13939 | const FunctionProtoType *Proto = | ||||||
13940 | FD->getType()->getAs<FunctionProtoType>(); | ||||||
13941 | FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), | ||||||
| |||||||
13942 | Proto->getExtProtoInfo())); | ||||||
13943 | } | ||||||
13944 | } | ||||||
13945 | |||||||
13946 | // If the function implicitly returns zero (like 'main') or is naked, | ||||||
13947 | // don't complain about missing return statements. | ||||||
13948 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) | ||||||
13949 | WP.disableCheckFallThrough(); | ||||||
13950 | |||||||
13951 | // MSVC permits the use of pure specifier (=0) on function definition, | ||||||
13952 | // defined at class scope, warn about this non-standard construct. | ||||||
13953 | if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) | ||||||
13954 | Diag(FD->getLocation(), diag::ext_pure_function_definition); | ||||||
13955 | |||||||
13956 | if (!FD->isInvalidDecl()) { | ||||||
13957 | // Don't diagnose unused parameters of defaulted or deleted functions. | ||||||
13958 | if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) | ||||||
13959 | DiagnoseUnusedParameters(FD->parameters()); | ||||||
13960 | DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), | ||||||
13961 | FD->getReturnType(), FD); | ||||||
13962 | |||||||
13963 | // If this is a structor, we need a vtable. | ||||||
13964 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) | ||||||
13965 | MarkVTableUsed(FD->getLocation(), Constructor->getParent()); | ||||||
13966 | else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) | ||||||
13967 | MarkVTableUsed(FD->getLocation(), Destructor->getParent()); | ||||||
13968 | |||||||
13969 | // Try to apply the named return value optimization. We have to check | ||||||
13970 | // if we can do this here because lambdas keep return statements around | ||||||
13971 | // to deduce an implicit return type. | ||||||
13972 | if (FD->getReturnType()->isRecordType() && | ||||||
13973 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) | ||||||
13974 | computeNRVO(Body, getCurFunction()); | ||||||
13975 | } | ||||||
13976 | |||||||
13977 | // GNU warning -Wmissing-prototypes: | ||||||
13978 | // Warn if a global function is defined without a previous | ||||||
13979 | // prototype declaration. This warning is issued even if the | ||||||
13980 | // definition itself provides a prototype. The aim is to detect | ||||||
13981 | // global functions that fail to be declared in header files. | ||||||
13982 | const FunctionDecl *PossiblePrototype = nullptr; | ||||||
13983 | if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { | ||||||
13984 | Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; | ||||||
13985 | |||||||
13986 | if (PossiblePrototype) { | ||||||
13987 | // We found a declaration that is not a prototype, | ||||||
13988 | // but that could be a zero-parameter prototype | ||||||
13989 | if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { | ||||||
13990 | TypeLoc TL = TI->getTypeLoc(); | ||||||
13991 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) | ||||||
13992 | Diag(PossiblePrototype->getLocation(), | ||||||
13993 | diag::note_declaration_not_a_prototype) | ||||||
13994 | << (FD->getNumParams() != 0) | ||||||
13995 | << (FD->getNumParams() == 0 | ||||||
13996 | ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") | ||||||
13997 | : FixItHint{}); | ||||||
13998 | } | ||||||
13999 | } else { | ||||||
14000 | Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | ||||||
14001 | << /* function */ 1 | ||||||
14002 | << (FD->getStorageClass() == SC_None | ||||||
14003 | ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), | ||||||
14004 | "static ") | ||||||
14005 | : FixItHint{}); | ||||||
14006 | } | ||||||
14007 | |||||||
14008 | // GNU warning -Wstrict-prototypes | ||||||
14009 | // Warn if K&R function is defined without a previous declaration. | ||||||
14010 | // This warning is issued only if the definition itself does not provide | ||||||
14011 | // a prototype. Only K&R definitions do not provide a prototype. | ||||||
14012 | // An empty list in a function declarator that is part of a definition | ||||||
14013 | // of that function specifies that the function has no parameters | ||||||
14014 | // (C99 6.7.5.3p14) | ||||||
14015 | if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && | ||||||
14016 | !LangOpts.CPlusPlus) { | ||||||
14017 | TypeSourceInfo *TI = FD->getTypeSourceInfo(); | ||||||
14018 | TypeLoc TL = TI->getTypeLoc(); | ||||||
14019 | FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); | ||||||
14020 | Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; | ||||||
14021 | } | ||||||
14022 | } | ||||||
14023 | |||||||
14024 | // Warn on CPUDispatch with an actual body. | ||||||
14025 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) | ||||||
14026 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) | ||||||
14027 | if (!CmpndBody->body_empty()) | ||||||
14028 | Diag(CmpndBody->body_front()->getBeginLoc(), | ||||||
14029 | diag::warn_dispatch_body_ignored); | ||||||
14030 | |||||||
14031 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
14032 | const CXXMethodDecl *KeyFunction; | ||||||
14033 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && | ||||||
14034 | MD->isVirtual() && | ||||||
14035 | (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && | ||||||
14036 | MD == KeyFunction->getCanonicalDecl()) { | ||||||
14037 | // Update the key-function state if necessary for this ABI. | ||||||
14038 | if (FD->isInlined() && | ||||||
14039 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { | ||||||
14040 | Context.setNonKeyFunction(MD); | ||||||
14041 | |||||||
14042 | // If the newly-chosen key function is already defined, then we | ||||||
14043 | // need to mark the vtable as used retroactively. | ||||||
14044 | KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); | ||||||
14045 | const FunctionDecl *Definition; | ||||||
14046 | if (KeyFunction && KeyFunction->isDefined(Definition)) | ||||||
14047 | MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); | ||||||
14048 | } else { | ||||||
14049 | // We just defined they key function; mark the vtable as used. | ||||||
14050 | MarkVTableUsed(FD->getLocation(), MD->getParent(), true); | ||||||
14051 | } | ||||||
14052 | } | ||||||
14053 | } | ||||||
14054 | |||||||
14055 | assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14056, __PRETTY_FUNCTION__)) | ||||||
14056 | "Function parsing confused")(((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && "Function parsing confused") ? static_cast <void> (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14056, __PRETTY_FUNCTION__)); | ||||||
14057 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { | ||||||
14058 | assert(MD == getCurMethodDecl() && "Method parsing confused")((MD == getCurMethodDecl() && "Method parsing confused" ) ? static_cast<void> (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14058, __PRETTY_FUNCTION__)); | ||||||
14059 | MD->setBody(Body); | ||||||
14060 | if (!MD->isInvalidDecl()) { | ||||||
14061 | DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), | ||||||
14062 | MD->getReturnType(), MD); | ||||||
14063 | |||||||
14064 | if (Body) | ||||||
14065 | computeNRVO(Body, getCurFunction()); | ||||||
14066 | } | ||||||
14067 | if (getCurFunction()->ObjCShouldCallSuper) { | ||||||
14068 | Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) | ||||||
14069 | << MD->getSelector().getAsString(); | ||||||
14070 | getCurFunction()->ObjCShouldCallSuper = false; | ||||||
14071 | } | ||||||
14072 | if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { | ||||||
14073 | const ObjCMethodDecl *InitMethod = nullptr; | ||||||
14074 | bool isDesignated = | ||||||
14075 | MD->isDesignatedInitializerForTheInterface(&InitMethod); | ||||||
14076 | assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void> (0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14076, __PRETTY_FUNCTION__)); | ||||||
14077 | (void)isDesignated; | ||||||
14078 | |||||||
14079 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { | ||||||
14080 | auto IFace = MD->getClassInterface(); | ||||||
14081 | if (!IFace) | ||||||
14082 | return false; | ||||||
14083 | auto SuperD = IFace->getSuperClass(); | ||||||
14084 | if (!SuperD) | ||||||
14085 | return false; | ||||||
14086 | return SuperD->getIdentifier() == | ||||||
14087 | NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); | ||||||
14088 | }; | ||||||
14089 | // Don't issue this warning for unavailable inits or direct subclasses | ||||||
14090 | // of NSObject. | ||||||
14091 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { | ||||||
14092 | Diag(MD->getLocation(), | ||||||
14093 | diag::warn_objc_designated_init_missing_super_call); | ||||||
14094 | Diag(InitMethod->getLocation(), | ||||||
14095 | diag::note_objc_designated_init_marked_here); | ||||||
14096 | } | ||||||
14097 | getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; | ||||||
14098 | } | ||||||
14099 | if (getCurFunction()->ObjCWarnForNoInitDelegation) { | ||||||
14100 | // Don't issue this warning for unavaialable inits. | ||||||
14101 | if (!MD->isUnavailable()) | ||||||
14102 | Diag(MD->getLocation(), | ||||||
14103 | diag::warn_objc_secondary_init_missing_init_call); | ||||||
14104 | getCurFunction()->ObjCWarnForNoInitDelegation = false; | ||||||
14105 | } | ||||||
14106 | |||||||
14107 | diagnoseImplicitlyRetainedSelf(*this); | ||||||
14108 | } else { | ||||||
14109 | // Parsing the function declaration failed in some way. Pop the fake scope | ||||||
14110 | // we pushed on. | ||||||
14111 | PopFunctionScopeInfo(ActivePolicy, dcl); | ||||||
14112 | return nullptr; | ||||||
14113 | } | ||||||
14114 | |||||||
14115 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||||
14116 | DiagnoseUnguardedAvailabilityViolations(dcl); | ||||||
14117 | |||||||
14118 | assert(!getCurFunction()->ObjCShouldCallSuper &&((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14120, __PRETTY_FUNCTION__)) | ||||||
14119 | "This should only be set for ObjC methods, which should have been "((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14120, __PRETTY_FUNCTION__)) | ||||||
14120 | "handled in the block above.")((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been " "handled in the block above.") ? static_cast<void> (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14120, __PRETTY_FUNCTION__)); | ||||||
14121 | |||||||
14122 | // Verify and clean out per-function state. | ||||||
14123 | if (Body && (!FD || !FD->isDefaulted())) { | ||||||
14124 | // C++ constructors that have function-try-blocks can't have return | ||||||
14125 | // statements in the handlers of that block. (C++ [except.handle]p14) | ||||||
14126 | // Verify this. | ||||||
14127 | if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) | ||||||
14128 | DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); | ||||||
14129 | |||||||
14130 | // Verify that gotos and switch cases don't jump into scopes illegally. | ||||||
14131 | if (getCurFunction()->NeedsScopeChecking() && | ||||||
14132 | !PP.isCodeCompletionEnabled()) | ||||||
14133 | DiagnoseInvalidJumps(Body); | ||||||
14134 | |||||||
14135 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { | ||||||
14136 | if (!Destructor->getParent()->isDependentType()) | ||||||
14137 | CheckDestructor(Destructor); | ||||||
14138 | |||||||
14139 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | ||||||
14140 | Destructor->getParent()); | ||||||
14141 | } | ||||||
14142 | |||||||
14143 | // If any errors have occurred, clear out any temporaries that may have | ||||||
14144 | // been leftover. This ensures that these temporaries won't be picked up for | ||||||
14145 | // deletion in some later function. | ||||||
14146 | if (getDiagnostics().hasErrorOccurred() || | ||||||
14147 | getDiagnostics().getSuppressAllDiagnostics()) { | ||||||
14148 | DiscardCleanupsInEvaluationContext(); | ||||||
14149 | } | ||||||
14150 | if (!getDiagnostics().hasUncompilableErrorOccurred() && | ||||||
14151 | !isa<FunctionTemplateDecl>(dcl)) { | ||||||
14152 | // Since the body is valid, issue any analysis-based warnings that are | ||||||
14153 | // enabled. | ||||||
14154 | ActivePolicy = &WP; | ||||||
14155 | } | ||||||
14156 | |||||||
14157 | if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && | ||||||
14158 | !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) | ||||||
14159 | FD->setInvalidDecl(); | ||||||
14160 | |||||||
14161 | if (FD && FD->hasAttr<NakedAttr>()) { | ||||||
14162 | for (const Stmt *S : Body->children()) { | ||||||
14163 | // Allow local register variables without initializer as they don't | ||||||
14164 | // require prologue. | ||||||
14165 | bool RegisterVariables = false; | ||||||
14166 | if (auto *DS = dyn_cast<DeclStmt>(S)) { | ||||||
14167 | for (const auto *Decl : DS->decls()) { | ||||||
14168 | if (const auto *Var = dyn_cast<VarDecl>(Decl)) { | ||||||
14169 | RegisterVariables = | ||||||
14170 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); | ||||||
14171 | if (!RegisterVariables) | ||||||
14172 | break; | ||||||
14173 | } | ||||||
14174 | } | ||||||
14175 | } | ||||||
14176 | if (RegisterVariables) | ||||||
14177 | continue; | ||||||
14178 | if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { | ||||||
14179 | Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); | ||||||
14180 | Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); | ||||||
14181 | FD->setInvalidDecl(); | ||||||
14182 | break; | ||||||
14183 | } | ||||||
14184 | } | ||||||
14185 | } | ||||||
14186 | |||||||
14187 | assert(ExprCleanupObjects.size() ==((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14189, __PRETTY_FUNCTION__)) | ||||||
14188 | ExprEvalContexts.back().NumCleanupObjects &&((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14189, __PRETTY_FUNCTION__)) | ||||||
14189 | "Leftover temporaries in function")((ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && "Leftover temporaries in function") ? static_cast <void> (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14189, __PRETTY_FUNCTION__)); | ||||||
14190 | assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function" ) ? static_cast<void> (0) : __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14190, __PRETTY_FUNCTION__)); | ||||||
14191 | assert(MaybeODRUseExprs.empty() &&((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14192, __PRETTY_FUNCTION__)) | ||||||
14192 | "Leftover expressions for odr-use checking")((MaybeODRUseExprs.empty() && "Leftover expressions for odr-use checking" ) ? static_cast<void> (0) : __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14192, __PRETTY_FUNCTION__)); | ||||||
14193 | } | ||||||
14194 | |||||||
14195 | if (!IsInstantiation) | ||||||
14196 | PopDeclContext(); | ||||||
14197 | |||||||
14198 | PopFunctionScopeInfo(ActivePolicy, dcl); | ||||||
14199 | // If any errors have occurred, clear out any temporaries that may have | ||||||
14200 | // been leftover. This ensures that these temporaries won't be picked up for | ||||||
14201 | // deletion in some later function. | ||||||
14202 | if (getDiagnostics().hasErrorOccurred()) { | ||||||
14203 | DiscardCleanupsInEvaluationContext(); | ||||||
14204 | } | ||||||
14205 | |||||||
14206 | return dcl; | ||||||
14207 | } | ||||||
14208 | |||||||
14209 | /// When we finish delayed parsing of an attribute, we must attach it to the | ||||||
14210 | /// relevant Decl. | ||||||
14211 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, | ||||||
14212 | ParsedAttributes &Attrs) { | ||||||
14213 | // Always attach attributes to the underlying decl. | ||||||
14214 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | ||||||
14215 | D = TD->getTemplatedDecl(); | ||||||
14216 | ProcessDeclAttributeList(S, D, Attrs); | ||||||
14217 | |||||||
14218 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) | ||||||
14219 | if (Method->isStatic()) | ||||||
14220 | checkThisInStaticMemberFunctionAttributes(Method); | ||||||
14221 | } | ||||||
14222 | |||||||
14223 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function | ||||||
14224 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). | ||||||
14225 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, | ||||||
14226 | IdentifierInfo &II, Scope *S) { | ||||||
14227 | // Find the scope in which the identifier is injected and the corresponding | ||||||
14228 | // DeclContext. | ||||||
14229 | // FIXME: C89 does not say what happens if there is no enclosing block scope. | ||||||
14230 | // In that case, we inject the declaration into the translation unit scope | ||||||
14231 | // instead. | ||||||
14232 | Scope *BlockScope = S; | ||||||
14233 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) | ||||||
14234 | BlockScope = BlockScope->getParent(); | ||||||
14235 | |||||||
14236 | Scope *ContextScope = BlockScope; | ||||||
14237 | while (!ContextScope->getEntity()) | ||||||
14238 | ContextScope = ContextScope->getParent(); | ||||||
14239 | ContextRAII SavedContext(*this, ContextScope->getEntity()); | ||||||
14240 | |||||||
14241 | // Before we produce a declaration for an implicitly defined | ||||||
14242 | // function, see whether there was a locally-scoped declaration of | ||||||
14243 | // this name as a function or variable. If so, use that | ||||||
14244 | // (non-visible) declaration, and complain about it. | ||||||
14245 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); | ||||||
14246 | if (ExternCPrev) { | ||||||
14247 | // We still need to inject the function into the enclosing block scope so | ||||||
14248 | // that later (non-call) uses can see it. | ||||||
14249 | PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); | ||||||
14250 | |||||||
14251 | // C89 footnote 38: | ||||||
14252 | // If in fact it is not defined as having type "function returning int", | ||||||
14253 | // the behavior is undefined. | ||||||
14254 | if (!isa<FunctionDecl>(ExternCPrev) || | ||||||
14255 | !Context.typesAreCompatible( | ||||||
14256 | cast<FunctionDecl>(ExternCPrev)->getType(), | ||||||
14257 | Context.getFunctionNoProtoType(Context.IntTy))) { | ||||||
14258 | Diag(Loc, diag::ext_use_out_of_scope_declaration) | ||||||
14259 | << ExternCPrev << !getLangOpts().C99; | ||||||
14260 | Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); | ||||||
14261 | return ExternCPrev; | ||||||
14262 | } | ||||||
14263 | } | ||||||
14264 | |||||||
14265 | // Extension in C99. Legal in C90, but warn about it. | ||||||
14266 | unsigned diag_id; | ||||||
14267 | if (II.getName().startswith("__builtin_")) | ||||||
14268 | diag_id = diag::warn_builtin_unknown; | ||||||
14269 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. | ||||||
14270 | else if (getLangOpts().OpenCL) | ||||||
14271 | diag_id = diag::err_opencl_implicit_function_decl; | ||||||
14272 | else if (getLangOpts().C99) | ||||||
14273 | diag_id = diag::ext_implicit_function_decl; | ||||||
14274 | else | ||||||
14275 | diag_id = diag::warn_implicit_function_decl; | ||||||
14276 | Diag(Loc, diag_id) << &II; | ||||||
14277 | |||||||
14278 | // If we found a prior declaration of this function, don't bother building | ||||||
14279 | // another one. We've already pushed that one into scope, so there's nothing | ||||||
14280 | // more to do. | ||||||
14281 | if (ExternCPrev) | ||||||
14282 | return ExternCPrev; | ||||||
14283 | |||||||
14284 | // Because typo correction is expensive, only do it if the implicit | ||||||
14285 | // function declaration is going to be treated as an error. | ||||||
14286 | if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { | ||||||
14287 | TypoCorrection Corrected; | ||||||
14288 | DeclFilterCCC<FunctionDecl> CCC{}; | ||||||
14289 | if (S && (Corrected = | ||||||
14290 | CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, | ||||||
14291 | S, nullptr, CCC, CTK_NonError))) | ||||||
14292 | diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), | ||||||
14293 | /*ErrorRecovery*/false); | ||||||
14294 | } | ||||||
14295 | |||||||
14296 | // Set a Declarator for the implicit definition: int foo(); | ||||||
14297 | const char *Dummy; | ||||||
14298 | AttributeFactory attrFactory; | ||||||
14299 | DeclSpec DS(attrFactory); | ||||||
14300 | unsigned DiagID; | ||||||
14301 | bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, | ||||||
14302 | Context.getPrintingPolicy()); | ||||||
14303 | (void)Error; // Silence warning. | ||||||
14304 | assert(!Error && "Error setting up implicit decl!")((!Error && "Error setting up implicit decl!") ? static_cast <void> (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14304, __PRETTY_FUNCTION__)); | ||||||
14305 | SourceLocation NoLoc; | ||||||
14306 | Declarator D(DS, DeclaratorContext::BlockContext); | ||||||
14307 | D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, | ||||||
14308 | /*IsAmbiguous=*/false, | ||||||
14309 | /*LParenLoc=*/NoLoc, | ||||||
14310 | /*Params=*/nullptr, | ||||||
14311 | /*NumParams=*/0, | ||||||
14312 | /*EllipsisLoc=*/NoLoc, | ||||||
14313 | /*RParenLoc=*/NoLoc, | ||||||
14314 | /*RefQualifierIsLvalueRef=*/true, | ||||||
14315 | /*RefQualifierLoc=*/NoLoc, | ||||||
14316 | /*MutableLoc=*/NoLoc, EST_None, | ||||||
14317 | /*ESpecRange=*/SourceRange(), | ||||||
14318 | /*Exceptions=*/nullptr, | ||||||
14319 | /*ExceptionRanges=*/nullptr, | ||||||
14320 | /*NumExceptions=*/0, | ||||||
14321 | /*NoexceptExpr=*/nullptr, | ||||||
14322 | /*ExceptionSpecTokens=*/nullptr, | ||||||
14323 | /*DeclsInPrototype=*/None, Loc, | ||||||
14324 | Loc, D), | ||||||
14325 | std::move(DS.getAttributes()), SourceLocation()); | ||||||
14326 | D.SetIdentifier(&II, Loc); | ||||||
14327 | |||||||
14328 | // Insert this function into the enclosing block scope. | ||||||
14329 | FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); | ||||||
14330 | FD->setImplicit(); | ||||||
14331 | |||||||
14332 | AddKnownFunctionAttributes(FD); | ||||||
14333 | |||||||
14334 | return FD; | ||||||
14335 | } | ||||||
14336 | |||||||
14337 | /// Adds any function attributes that we know a priori based on | ||||||
14338 | /// the declaration of this function. | ||||||
14339 | /// | ||||||
14340 | /// These attributes can apply both to implicitly-declared builtins | ||||||
14341 | /// (like __builtin___printf_chk) or to library-declared functions | ||||||
14342 | /// like NSLog or printf. | ||||||
14343 | /// | ||||||
14344 | /// We need to check for duplicate attributes both here and where user-written | ||||||
14345 | /// attributes are applied to declarations. | ||||||
14346 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { | ||||||
14347 | if (FD->isInvalidDecl()) | ||||||
14348 | return; | ||||||
14349 | |||||||
14350 | // If this is a built-in function, map its builtin attributes to | ||||||
14351 | // actual attributes. | ||||||
14352 | if (unsigned BuiltinID = FD->getBuiltinID()) { | ||||||
14353 | // Handle printf-formatting attributes. | ||||||
14354 | unsigned FormatIdx; | ||||||
14355 | bool HasVAListArg; | ||||||
14356 | if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { | ||||||
14357 | if (!FD->hasAttr<FormatAttr>()) { | ||||||
14358 | const char *fmt = "printf"; | ||||||
14359 | unsigned int NumParams = FD->getNumParams(); | ||||||
14360 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) | ||||||
14361 | FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) | ||||||
14362 | fmt = "NSString"; | ||||||
14363 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14364 | &Context.Idents.get(fmt), | ||||||
14365 | FormatIdx+1, | ||||||
14366 | HasVAListArg ? 0 : FormatIdx+2, | ||||||
14367 | FD->getLocation())); | ||||||
14368 | } | ||||||
14369 | } | ||||||
14370 | if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, | ||||||
14371 | HasVAListArg)) { | ||||||
14372 | if (!FD->hasAttr<FormatAttr>()) | ||||||
14373 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14374 | &Context.Idents.get("scanf"), | ||||||
14375 | FormatIdx+1, | ||||||
14376 | HasVAListArg ? 0 : FormatIdx+2, | ||||||
14377 | FD->getLocation())); | ||||||
14378 | } | ||||||
14379 | |||||||
14380 | // Handle automatically recognized callbacks. | ||||||
14381 | SmallVector<int, 4> Encoding; | ||||||
14382 | if (!FD->hasAttr<CallbackAttr>() && | ||||||
14383 | Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) | ||||||
14384 | FD->addAttr(CallbackAttr::CreateImplicit( | ||||||
14385 | Context, Encoding.data(), Encoding.size(), FD->getLocation())); | ||||||
14386 | |||||||
14387 | // Mark const if we don't care about errno and that is the only thing | ||||||
14388 | // preventing the function from being const. This allows IRgen to use LLVM | ||||||
14389 | // intrinsics for such functions. | ||||||
14390 | if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && | ||||||
14391 | Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) | ||||||
14392 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14393 | |||||||
14394 | // We make "fma" on some platforms const because we know it does not set | ||||||
14395 | // errno in those environments even though it could set errno based on the | ||||||
14396 | // C standard. | ||||||
14397 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); | ||||||
14398 | if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && | ||||||
14399 | !FD->hasAttr<ConstAttr>()) { | ||||||
14400 | switch (BuiltinID) { | ||||||
14401 | case Builtin::BI__builtin_fma: | ||||||
14402 | case Builtin::BI__builtin_fmaf: | ||||||
14403 | case Builtin::BI__builtin_fmal: | ||||||
14404 | case Builtin::BIfma: | ||||||
14405 | case Builtin::BIfmaf: | ||||||
14406 | case Builtin::BIfmal: | ||||||
14407 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14408 | break; | ||||||
14409 | default: | ||||||
14410 | break; | ||||||
14411 | } | ||||||
14412 | } | ||||||
14413 | |||||||
14414 | if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && | ||||||
14415 | !FD->hasAttr<ReturnsTwiceAttr>()) | ||||||
14416 | FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, | ||||||
14417 | FD->getLocation())); | ||||||
14418 | if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) | ||||||
14419 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14420 | if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) | ||||||
14421 | FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14422 | if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) | ||||||
14423 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14424 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && | ||||||
14425 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { | ||||||
14426 | // Add the appropriate attribute, depending on the CUDA compilation mode | ||||||
14427 | // and which target the builtin belongs to. For example, during host | ||||||
14428 | // compilation, aux builtins are __device__, while the rest are __host__. | ||||||
14429 | if (getLangOpts().CUDAIsDevice != | ||||||
14430 | Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) | ||||||
14431 | FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14432 | else | ||||||
14433 | FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14434 | } | ||||||
14435 | } | ||||||
14436 | |||||||
14437 | // If C++ exceptions are enabled but we are told extern "C" functions cannot | ||||||
14438 | // throw, add an implicit nothrow attribute to any extern "C" function we come | ||||||
14439 | // across. | ||||||
14440 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && | ||||||
14441 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { | ||||||
14442 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); | ||||||
14443 | if (!FPT || FPT->getExceptionSpecType() == EST_None) | ||||||
14444 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14445 | } | ||||||
14446 | |||||||
14447 | IdentifierInfo *Name = FD->getIdentifier(); | ||||||
14448 | if (!Name) | ||||||
14449 | return; | ||||||
14450 | if ((!getLangOpts().CPlusPlus && | ||||||
14451 | FD->getDeclContext()->isTranslationUnit()) || | ||||||
14452 | (isa<LinkageSpecDecl>(FD->getDeclContext()) && | ||||||
14453 | cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == | ||||||
14454 | LinkageSpecDecl::lang_c)) { | ||||||
14455 | // Okay: this could be a libc/libm/Objective-C function we know | ||||||
14456 | // about. | ||||||
14457 | } else | ||||||
14458 | return; | ||||||
14459 | |||||||
14460 | if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { | ||||||
14461 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be | ||||||
14462 | // target-specific builtins, perhaps? | ||||||
14463 | if (!FD->hasAttr<FormatAttr>()) | ||||||
14464 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14465 | &Context.Idents.get("printf"), 2, | ||||||
14466 | Name->isStr("vasprintf") ? 0 : 3, | ||||||
14467 | FD->getLocation())); | ||||||
14468 | } | ||||||
14469 | |||||||
14470 | if (Name->isStr("__CFStringMakeConstantString")) { | ||||||
14471 | // We already have a __builtin___CFStringMakeConstantString, | ||||||
14472 | // but builds that use -fno-constant-cfstrings don't go through that. | ||||||
14473 | if (!FD->hasAttr<FormatArgAttr>()) | ||||||
14474 | FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), | ||||||
14475 | FD->getLocation())); | ||||||
14476 | } | ||||||
14477 | } | ||||||
14478 | |||||||
14479 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, | ||||||
14480 | TypeSourceInfo *TInfo) { | ||||||
14481 | assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((D.getIdentifier() && "Wrong callback for declspec without declarator" ) ? static_cast<void> (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14481, __PRETTY_FUNCTION__)); | ||||||
14482 | assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((!T.isNull() && "GetTypeForDeclarator() returned null type" ) ? static_cast<void> (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14482, __PRETTY_FUNCTION__)); | ||||||
14483 | |||||||
14484 | if (!TInfo) { | ||||||
14485 | assert(D.isInvalidType() && "no declarator info for valid type")((D.isInvalidType() && "no declarator info for valid type" ) ? static_cast<void> (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14485, __PRETTY_FUNCTION__)); | ||||||
14486 | TInfo = Context.getTrivialTypeSourceInfo(T); | ||||||
14487 | } | ||||||
14488 | |||||||
14489 | // Scope manipulation handled by caller. | ||||||
14490 | TypedefDecl *NewTD = | ||||||
14491 | TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), | ||||||
14492 | D.getIdentifierLoc(), D.getIdentifier(), TInfo); | ||||||
14493 | |||||||
14494 | // Bail out immediately if we have an invalid declaration. | ||||||
14495 | if (D.isInvalidType()) { | ||||||
14496 | NewTD->setInvalidDecl(); | ||||||
14497 | return NewTD; | ||||||
14498 | } | ||||||
14499 | |||||||
14500 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
14501 | if (CurContext->isFunctionOrMethod()) | ||||||
14502 | Diag(NewTD->getLocation(), diag::err_module_private_local) | ||||||
14503 | << 2 << NewTD->getDeclName() | ||||||
14504 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
14505 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
14506 | else | ||||||
14507 | NewTD->setModulePrivate(); | ||||||
14508 | } | ||||||
14509 | |||||||
14510 | // C++ [dcl.typedef]p8: | ||||||
14511 | // If the typedef declaration defines an unnamed class (or | ||||||
14512 | // enum), the first typedef-name declared by the declaration | ||||||
14513 | // to be that class type (or enum type) is used to denote the | ||||||
14514 | // class type (or enum type) for linkage purposes only. | ||||||
14515 | // We need to check whether the type was declared in the declaration. | ||||||
14516 | switch (D.getDeclSpec().getTypeSpecType()) { | ||||||
14517 | case TST_enum: | ||||||
14518 | case TST_struct: | ||||||
14519 | case TST_interface: | ||||||
14520 | case TST_union: | ||||||
14521 | case TST_class: { | ||||||
14522 | TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | ||||||
14523 | setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); | ||||||
14524 | break; | ||||||
14525 | } | ||||||
14526 | |||||||
14527 | default: | ||||||
14528 | break; | ||||||
14529 | } | ||||||
14530 | |||||||
14531 | return NewTD; | ||||||
14532 | } | ||||||
14533 | |||||||
14534 | /// Check that this is a valid underlying type for an enum declaration. | ||||||
14535 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { | ||||||
14536 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); | ||||||
14537 | QualType T = TI->getType(); | ||||||
14538 | |||||||
14539 | if (T->isDependentType()) | ||||||
14540 | return false; | ||||||
14541 | |||||||
14542 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) | ||||||
14543 | if (BT->isInteger()) | ||||||
14544 | return false; | ||||||
14545 | |||||||
14546 | Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; | ||||||
14547 | return true; | ||||||
14548 | } | ||||||
14549 | |||||||
14550 | /// Check whether this is a valid redeclaration of a previous enumeration. | ||||||
14551 | /// \return true if the redeclaration was invalid. | ||||||
14552 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, | ||||||
14553 | QualType EnumUnderlyingTy, bool IsFixed, | ||||||
14554 | const EnumDecl *Prev) { | ||||||
14555 | if (IsScoped != Prev->isScoped()) { | ||||||
14556 | Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) | ||||||
14557 | << Prev->isScoped(); | ||||||
14558 | Diag(Prev->getLocation(), diag::note_previous_declaration); | ||||||
14559 | return true; | ||||||
14560 | } | ||||||
14561 | |||||||
14562 | if (IsFixed && Prev->isFixed()) { | ||||||
14563 | if (!EnumUnderlyingTy->isDependentType() && | ||||||
14564 | !Prev->getIntegerType()->isDependentType() && | ||||||
14565 | !Context.hasSameUnqualifiedType(EnumUnderlyingTy, | ||||||
14566 | Prev->getIntegerType())) { | ||||||
14567 | // TODO: Highlight the underlying type of the redeclaration. | ||||||
14568 | Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) | ||||||
14569 | << EnumUnderlyingTy << Prev->getIntegerType(); | ||||||
14570 | Diag(Prev->getLocation(), diag::note_previous_declaration) | ||||||
14571 | << Prev->getIntegerTypeRange(); | ||||||
14572 | return true; | ||||||
14573 | } | ||||||
14574 | } else if (IsFixed != Prev->isFixed()) { | ||||||
14575 | Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) | ||||||
14576 | << Prev->isFixed(); | ||||||
14577 | Diag(Prev->getLocation(), diag::note_previous_declaration); | ||||||
14578 | return true; | ||||||
14579 | } | ||||||
14580 | |||||||
14581 | return false; | ||||||
14582 | } | ||||||
14583 | |||||||
14584 | /// Get diagnostic %select index for tag kind for | ||||||
14585 | /// redeclaration diagnostic message. | ||||||
14586 | /// WARNING: Indexes apply to particular diagnostics only! | ||||||
14587 | /// | ||||||
14588 | /// \returns diagnostic %select index. | ||||||
14589 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { | ||||||
14590 | switch (Tag) { | ||||||
14591 | case TTK_Struct: return 0; | ||||||
14592 | case TTK_Interface: return 1; | ||||||
14593 | case TTK_Class: return 2; | ||||||
14594 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14594); | ||||||
14595 | } | ||||||
14596 | } | ||||||
14597 | |||||||
14598 | /// Determine if tag kind is a class-key compatible with | ||||||
14599 | /// class for redeclaration (class, struct, or __interface). | ||||||
14600 | /// | ||||||
14601 | /// \returns true iff the tag kind is compatible. | ||||||
14602 | static bool isClassCompatTagKind(TagTypeKind Tag) | ||||||
14603 | { | ||||||
14604 | return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; | ||||||
14605 | } | ||||||
14606 | |||||||
14607 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, | ||||||
14608 | TagTypeKind TTK) { | ||||||
14609 | if (isa<TypedefDecl>(PrevDecl)) | ||||||
14610 | return NTK_Typedef; | ||||||
14611 | else if (isa<TypeAliasDecl>(PrevDecl)) | ||||||
14612 | return NTK_TypeAlias; | ||||||
14613 | else if (isa<ClassTemplateDecl>(PrevDecl)) | ||||||
14614 | return NTK_Template; | ||||||
14615 | else if (isa<TypeAliasTemplateDecl>(PrevDecl)) | ||||||
14616 | return NTK_TypeAliasTemplate; | ||||||
14617 | else if (isa<TemplateTemplateParmDecl>(PrevDecl)) | ||||||
14618 | return NTK_TemplateTemplateArgument; | ||||||
14619 | switch (TTK) { | ||||||
14620 | case TTK_Struct: | ||||||
14621 | case TTK_Interface: | ||||||
14622 | case TTK_Class: | ||||||
14623 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; | ||||||
14624 | case TTK_Union: | ||||||
14625 | return NTK_NonUnion; | ||||||
14626 | case TTK_Enum: | ||||||
14627 | return NTK_NonEnum; | ||||||
14628 | } | ||||||
14629 | llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14629); | ||||||
14630 | } | ||||||
14631 | |||||||
14632 | /// Determine whether a tag with a given kind is acceptable | ||||||
14633 | /// as a redeclaration of the given tag declaration. | ||||||
14634 | /// | ||||||
14635 | /// \returns true if the new tag kind is acceptable, false otherwise. | ||||||
14636 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, | ||||||
14637 | TagTypeKind NewTag, bool isDefinition, | ||||||
14638 | SourceLocation NewTagLoc, | ||||||
14639 | const IdentifierInfo *Name) { | ||||||
14640 | // C++ [dcl.type.elab]p3: | ||||||
14641 | // The class-key or enum keyword present in the | ||||||
14642 | // elaborated-type-specifier shall agree in kind with the | ||||||
14643 | // declaration to which the name in the elaborated-type-specifier | ||||||
14644 | // refers. This rule also applies to the form of | ||||||
14645 | // elaborated-type-specifier that declares a class-name or | ||||||
14646 | // friend class since it can be construed as referring to the | ||||||
14647 | // definition of the class. Thus, in any | ||||||
14648 | // elaborated-type-specifier, the enum keyword shall be used to | ||||||
14649 | // refer to an enumeration (7.2), the union class-key shall be | ||||||
14650 | // used to refer to a union (clause 9), and either the class or | ||||||
14651 | // struct class-key shall be used to refer to a class (clause 9) | ||||||
14652 | // declared using the class or struct class-key. | ||||||
14653 | TagTypeKind OldTag = Previous->getTagKind(); | ||||||
14654 | if (OldTag != NewTag && | ||||||
14655 | !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) | ||||||
14656 | return false; | ||||||
14657 | |||||||
14658 | // Tags are compatible, but we might still want to warn on mismatched tags. | ||||||
14659 | // Non-class tags can't be mismatched at this point. | ||||||
14660 | if (!isClassCompatTagKind(NewTag)) | ||||||
14661 | return true; | ||||||
14662 | |||||||
14663 | // Declarations for which -Wmismatched-tags is disabled are entirely ignored | ||||||
14664 | // by our warning analysis. We don't want to warn about mismatches with (eg) | ||||||
14665 | // declarations in system headers that are designed to be specialized, but if | ||||||
14666 | // a user asks us to warn, we should warn if their code contains mismatched | ||||||
14667 | // declarations. | ||||||
14668 | auto IsIgnoredLoc = [&](SourceLocation Loc) { | ||||||
14669 | return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, | ||||||
14670 | Loc); | ||||||
14671 | }; | ||||||
14672 | if (IsIgnoredLoc(NewTagLoc)) | ||||||
14673 | return true; | ||||||
14674 | |||||||
14675 | auto IsIgnored = [&](const TagDecl *Tag) { | ||||||
14676 | return IsIgnoredLoc(Tag->getLocation()); | ||||||
14677 | }; | ||||||
14678 | while (IsIgnored(Previous)) { | ||||||
14679 | Previous = Previous->getPreviousDecl(); | ||||||
14680 | if (!Previous) | ||||||
14681 | return true; | ||||||
14682 | OldTag = Previous->getTagKind(); | ||||||
14683 | } | ||||||
14684 | |||||||
14685 | bool isTemplate = false; | ||||||
14686 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) | ||||||
14687 | isTemplate = Record->getDescribedClassTemplate(); | ||||||
14688 | |||||||
14689 | if (inTemplateInstantiation()) { | ||||||
14690 | if (OldTag != NewTag) { | ||||||
14691 | // In a template instantiation, do not offer fix-its for tag mismatches | ||||||
14692 | // since they usually mess up the template instead of fixing the problem. | ||||||
14693 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | ||||||
14694 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
14695 | << getRedeclDiagFromTagKind(OldTag); | ||||||
14696 | // FIXME: Note previous location? | ||||||
14697 | } | ||||||
14698 | return true; | ||||||
14699 | } | ||||||
14700 | |||||||
14701 | if (isDefinition) { | ||||||
14702 | // On definitions, check all previous tags and issue a fix-it for each | ||||||
14703 | // one that doesn't match the current tag. | ||||||
14704 | if (Previous->getDefinition()) { | ||||||
14705 | // Don't suggest fix-its for redefinitions. | ||||||
14706 | return true; | ||||||
14707 | } | ||||||
14708 | |||||||
14709 | bool previousMismatch = false; | ||||||
14710 | for (const TagDecl *I : Previous->redecls()) { | ||||||
14711 | if (I->getTagKind() != NewTag) { | ||||||
14712 | // Ignore previous declarations for which the warning was disabled. | ||||||
14713 | if (IsIgnored(I)) | ||||||
14714 | continue; | ||||||
14715 | |||||||
14716 | if (!previousMismatch) { | ||||||
14717 | previousMismatch = true; | ||||||
14718 | Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) | ||||||
14719 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
14720 | << getRedeclDiagFromTagKind(I->getTagKind()); | ||||||
14721 | } | ||||||
14722 | Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) | ||||||
14723 | << getRedeclDiagFromTagKind(NewTag) | ||||||
14724 | << FixItHint::CreateReplacement(I->getInnerLocStart(), | ||||||
14725 | TypeWithKeyword::getTagTypeKindName(NewTag)); | ||||||
14726 | } | ||||||
14727 | } | ||||||
14728 | return true; | ||||||
14729 | } | ||||||
14730 | |||||||
14731 | // Identify the prevailing tag kind: this is the kind of the definition (if | ||||||
14732 | // there is a non-ignored definition), or otherwise the kind of the prior | ||||||
14733 | // (non-ignored) declaration. | ||||||
14734 | const TagDecl *PrevDef = Previous->getDefinition(); | ||||||
14735 | if (PrevDef && IsIgnored(PrevDef)) | ||||||
14736 | PrevDef = nullptr; | ||||||
14737 | const TagDecl *Redecl = PrevDef ? PrevDef : Previous; | ||||||
14738 | if (Redecl->getTagKind() != NewTag) { | ||||||
14739 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | ||||||
14740 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
14741 | << getRedeclDiagFromTagKind(OldTag); | ||||||
14742 | Diag(Redecl->getLocation(), diag::note_previous_use); | ||||||
14743 | |||||||
14744 | // If there is a previous definition, suggest a fix-it. | ||||||
14745 | if (PrevDef) { | ||||||
14746 | Diag(NewTagLoc, diag::note_struct_class_suggestion) | ||||||
14747 | << getRedeclDiagFromTagKind(Redecl->getTagKind()) | ||||||
14748 | << FixItHint::CreateReplacement(SourceRange(NewTagLoc), | ||||||
14749 | TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); | ||||||
14750 | } | ||||||
14751 | } | ||||||
14752 | |||||||
14753 | return true; | ||||||
14754 | } | ||||||
14755 | |||||||
14756 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name | ||||||
14757 | /// from an outer enclosing namespace or file scope inside a friend declaration. | ||||||
14758 | /// This should provide the commented out code in the following snippet: | ||||||
14759 | /// namespace N { | ||||||
14760 | /// struct X; | ||||||
14761 | /// namespace M { | ||||||
14762 | /// struct Y { friend struct /*N::*/ X; }; | ||||||
14763 | /// } | ||||||
14764 | /// } | ||||||
14765 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, | ||||||
14766 | SourceLocation NameLoc) { | ||||||
14767 | // While the decl is in a namespace, do repeated lookup of that name and see | ||||||
14768 | // if we get the same namespace back. If we do not, continue until | ||||||
14769 | // translation unit scope, at which point we have a fully qualified NNS. | ||||||
14770 | SmallVector<IdentifierInfo *, 4> Namespaces; | ||||||
14771 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | ||||||
14772 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { | ||||||
14773 | // This tag should be declared in a namespace, which can only be enclosed by | ||||||
14774 | // other namespaces. Bail if there's an anonymous namespace in the chain. | ||||||
14775 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); | ||||||
14776 | if (!Namespace || Namespace->isAnonymousNamespace()) | ||||||
14777 | return FixItHint(); | ||||||
14778 | IdentifierInfo *II = Namespace->getIdentifier(); | ||||||
14779 | Namespaces.push_back(II); | ||||||
14780 | NamedDecl *Lookup = SemaRef.LookupSingleName( | ||||||
14781 | S, II, NameLoc, Sema::LookupNestedNameSpecifierName); | ||||||
14782 | if (Lookup == Namespace) | ||||||
14783 | break; | ||||||
14784 | } | ||||||
14785 | |||||||
14786 | // Once we have all the namespaces, reverse them to go outermost first, and | ||||||
14787 | // build an NNS. | ||||||
14788 | SmallString<64> Insertion; | ||||||
14789 | llvm::raw_svector_ostream OS(Insertion); | ||||||
14790 | if (DC->isTranslationUnit()) | ||||||
14791 | OS << "::"; | ||||||
14792 | std::reverse(Namespaces.begin(), Namespaces.end()); | ||||||
14793 | for (auto *II : Namespaces) | ||||||
14794 | OS << II->getName() << "::"; | ||||||
14795 | return FixItHint::CreateInsertion(NameLoc, Insertion); | ||||||
14796 | } | ||||||
14797 | |||||||
14798 | /// Determine whether a tag originally declared in context \p OldDC can | ||||||
14799 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup | ||||||
14800 | /// found a declaration in \p OldDC as a previous decl, perhaps through a | ||||||
14801 | /// using-declaration). | ||||||
14802 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, | ||||||
14803 | DeclContext *NewDC) { | ||||||
14804 | OldDC = OldDC->getRedeclContext(); | ||||||
14805 | NewDC = NewDC->getRedeclContext(); | ||||||
14806 | |||||||
14807 | if (OldDC->Equals(NewDC)) | ||||||
14808 | return true; | ||||||
14809 | |||||||
14810 | // In MSVC mode, we allow a redeclaration if the contexts are related (either | ||||||
14811 | // encloses the other). | ||||||
14812 | if (S.getLangOpts().MSVCCompat && | ||||||
14813 | (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) | ||||||
14814 | return true; | ||||||
14815 | |||||||
14816 | return false; | ||||||
14817 | } | ||||||
14818 | |||||||
14819 | /// This is invoked when we see 'struct foo' or 'struct {'. In the | ||||||
14820 | /// former case, Name will be non-null. In the later case, Name will be null. | ||||||
14821 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a | ||||||
14822 | /// reference/declaration/definition of a tag. | ||||||
14823 | /// | ||||||
14824 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or | ||||||
14825 | /// trailing-type-specifier) other than one in an alias-declaration. | ||||||
14826 | /// | ||||||
14827 | /// \param SkipBody If non-null, will be set to indicate if the caller should | ||||||
14828 | /// skip the definition of this tag and treat it as if it were a declaration. | ||||||
14829 | Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, | ||||||
14830 | SourceLocation KWLoc, CXXScopeSpec &SS, | ||||||
14831 | IdentifierInfo *Name, SourceLocation NameLoc, | ||||||
14832 | const ParsedAttributesView &Attrs, AccessSpecifier AS, | ||||||
14833 | SourceLocation ModulePrivateLoc, | ||||||
14834 | MultiTemplateParamsArg TemplateParameterLists, | ||||||
14835 | bool &OwnedDecl, bool &IsDependent, | ||||||
14836 | SourceLocation ScopedEnumKWLoc, | ||||||
14837 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, | ||||||
14838 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, | ||||||
14839 | SkipBodyInfo *SkipBody) { | ||||||
14840 | // If this is not a definition, it must have a name. | ||||||
14841 | IdentifierInfo *OrigName = Name; | ||||||
14842 | assert((Name != nullptr || TUK == TUK_Definition) &&(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14843, __PRETTY_FUNCTION__)) | ||||||
14843 | "Nameless record must be a definition!")(((Name != nullptr || TUK == TUK_Definition) && "Nameless record must be a definition!" ) ? static_cast<void> (0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14843, __PRETTY_FUNCTION__)); | ||||||
14844 | assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((TemplateParameterLists.size() == 0 || TUK != TUK_Reference) ? static_cast<void> (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14844, __PRETTY_FUNCTION__)); | ||||||
14845 | |||||||
14846 | OwnedDecl = false; | ||||||
14847 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | ||||||
14848 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); | ||||||
14849 | |||||||
14850 | // FIXME: Check member specializations more carefully. | ||||||
14851 | bool isMemberSpecialization = false; | ||||||
14852 | bool Invalid = false; | ||||||
14853 | |||||||
14854 | // We only need to do this matching if we have template parameters | ||||||
14855 | // or a scope specifier, which also conveniently avoids this work | ||||||
14856 | // for non-C++ cases. | ||||||
14857 | if (TemplateParameterLists.size() > 0 || | ||||||
14858 | (SS.isNotEmpty() && TUK != TUK_Reference)) { | ||||||
14859 | if (TemplateParameterList *TemplateParams = | ||||||
14860 | MatchTemplateParametersToScopeSpecifier( | ||||||
14861 | KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, | ||||||
14862 | TUK == TUK_Friend, isMemberSpecialization, Invalid)) { | ||||||
14863 | if (Kind == TTK_Enum) { | ||||||
14864 | Diag(KWLoc, diag::err_enum_template); | ||||||
14865 | return nullptr; | ||||||
14866 | } | ||||||
14867 | |||||||
14868 | if (TemplateParams->size() > 0) { | ||||||
14869 | // This is a declaration or definition of a class template (which may | ||||||
14870 | // be a member of another template). | ||||||
14871 | |||||||
14872 | if (Invalid) | ||||||
14873 | return nullptr; | ||||||
14874 | |||||||
14875 | OwnedDecl = false; | ||||||
14876 | DeclResult Result = CheckClassTemplate( | ||||||
14877 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, | ||||||
14878 | AS, ModulePrivateLoc, | ||||||
14879 | /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, | ||||||
14880 | TemplateParameterLists.data(), SkipBody); | ||||||
14881 | return Result.get(); | ||||||
14882 | } else { | ||||||
14883 | // The "template<>" header is extraneous. | ||||||
14884 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | ||||||
14885 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | ||||||
14886 | isMemberSpecialization = true; | ||||||
14887 | } | ||||||
14888 | } | ||||||
14889 | } | ||||||
14890 | |||||||
14891 | // Figure out the underlying type if this a enum declaration. We need to do | ||||||
14892 | // this early, because it's needed to detect if this is an incompatible | ||||||
14893 | // redeclaration. | ||||||
14894 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; | ||||||
14895 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; | ||||||
14896 | |||||||
14897 | if (Kind == TTK_Enum) { | ||||||
14898 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { | ||||||
14899 | // No underlying type explicitly specified, or we failed to parse the | ||||||
14900 | // type, default to int. | ||||||
14901 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
14902 | } else if (UnderlyingType.get()) { | ||||||
14903 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an | ||||||
14904 | // integral type; any cv-qualification is ignored. | ||||||
14905 | TypeSourceInfo *TI = nullptr; | ||||||
14906 | GetTypeFromParser(UnderlyingType.get(), &TI); | ||||||
14907 | EnumUnderlying = TI; | ||||||
14908 | |||||||
14909 | if (CheckEnumUnderlyingType(TI)) | ||||||
14910 | // Recover by falling back to int. | ||||||
14911 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
14912 | |||||||
14913 | if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, | ||||||
14914 | UPPC_FixedUnderlyingType)) | ||||||
14915 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
14916 | |||||||
14917 | } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { | ||||||
14918 | // For MSVC ABI compatibility, unfixed enums must use an underlying type | ||||||
14919 | // of 'int'. However, if this is an unfixed forward declaration, don't set | ||||||
14920 | // the underlying type unless the user enables -fms-compatibility. This | ||||||
14921 | // makes unfixed forward declared enums incomplete and is more conforming. | ||||||
14922 | if (TUK == TUK_Definition || getLangOpts().MSVCCompat) | ||||||
14923 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
14924 | } | ||||||
14925 | } | ||||||
14926 | |||||||
14927 | DeclContext *SearchDC = CurContext; | ||||||
14928 | DeclContext *DC = CurContext; | ||||||
14929 | bool isStdBadAlloc = false; | ||||||
14930 | bool isStdAlignValT = false; | ||||||
14931 | |||||||
14932 | RedeclarationKind Redecl = forRedeclarationInCurContext(); | ||||||
14933 | if (TUK == TUK_Friend || TUK == TUK_Reference) | ||||||
14934 | Redecl = NotForRedeclaration; | ||||||
14935 | |||||||
14936 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C | ||||||
14937 | /// implemented asks for structural equivalence checking, the returned decl | ||||||
14938 | /// here is passed back to the parser, allowing the tag body to be parsed. | ||||||
14939 | auto createTagFromNewDecl = [&]() -> TagDecl * { | ||||||
14940 | assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((!getLangOpts().CPlusPlus && "not meant for C++ usage" ) ? static_cast<void> (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 14940, __PRETTY_FUNCTION__)); | ||||||
14941 | // If there is an identifier, use the location of the identifier as the | ||||||
14942 | // location of the decl, otherwise use the location of the struct/union | ||||||
14943 | // keyword. | ||||||
14944 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | ||||||
14945 | TagDecl *New = nullptr; | ||||||
14946 | |||||||
14947 | if (Kind == TTK_Enum) { | ||||||
14948 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, | ||||||
14949 | ScopedEnum, ScopedEnumUsesClassTag, IsFixed); | ||||||
14950 | // If this is an undefined enum, bail. | ||||||
14951 | if (TUK != TUK_Definition && !Invalid) | ||||||
14952 | return nullptr; | ||||||
14953 | if (EnumUnderlying) { | ||||||
14954 | EnumDecl *ED = cast<EnumDecl>(New); | ||||||
14955 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) | ||||||
14956 | ED->setIntegerTypeSourceInfo(TI); | ||||||
14957 | else | ||||||
14958 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); | ||||||
14959 | ED->setPromotionType(ED->getIntegerType()); | ||||||
14960 | } | ||||||
14961 | } else { // struct/union | ||||||
14962 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
14963 | nullptr); | ||||||
14964 | } | ||||||
14965 | |||||||
14966 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | ||||||
14967 | // Add alignment attributes if necessary; these attributes are checked | ||||||
14968 | // when the ASTContext lays out the structure. | ||||||
14969 | // | ||||||
14970 | // It is important for implementing the correct semantics that this | ||||||
14971 | // happen here (in ActOnTag). The #pragma pack stack is | ||||||
14972 | // maintained as a result of parser callbacks which can occur at | ||||||
14973 | // many points during the parsing of a struct declaration (because | ||||||
14974 | // the #pragma tokens are effectively skipped over during the | ||||||
14975 | // parsing of the struct). | ||||||
14976 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | ||||||
14977 | AddAlignmentAttributesForRecord(RD); | ||||||
14978 | AddMsStructLayoutForRecord(RD); | ||||||
14979 | } | ||||||
14980 | } | ||||||
14981 | New->setLexicalDeclContext(CurContext); | ||||||
14982 | return New; | ||||||
14983 | }; | ||||||
14984 | |||||||
14985 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); | ||||||
14986 | if (Name && SS.isNotEmpty()) { | ||||||
14987 | // We have a nested-name tag ('struct foo::bar'). | ||||||
14988 | |||||||
14989 | // Check for invalid 'foo::'. | ||||||
14990 | if (SS.isInvalid()) { | ||||||
14991 | Name = nullptr; | ||||||
14992 | goto CreateNewDecl; | ||||||
14993 | } | ||||||
14994 | |||||||
14995 | // If this is a friend or a reference to a class in a dependent | ||||||
14996 | // context, don't try to make a decl for it. | ||||||
14997 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | ||||||
14998 | DC = computeDeclContext(SS, false); | ||||||
14999 | if (!DC) { | ||||||
15000 | IsDependent = true; | ||||||
15001 | return nullptr; | ||||||
15002 | } | ||||||
15003 | } else { | ||||||
15004 | DC = computeDeclContext(SS, true); | ||||||
15005 | if (!DC) { | ||||||
15006 | Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) | ||||||
15007 | << SS.getRange(); | ||||||
15008 | return nullptr; | ||||||
15009 | } | ||||||
15010 | } | ||||||
15011 | |||||||
15012 | if (RequireCompleteDeclContext(SS, DC)) | ||||||
15013 | return nullptr; | ||||||
15014 | |||||||
15015 | SearchDC = DC; | ||||||
15016 | // Look-up name inside 'foo::'. | ||||||
15017 | LookupQualifiedName(Previous, DC); | ||||||
15018 | |||||||
15019 | if (Previous.isAmbiguous()) | ||||||
15020 | return nullptr; | ||||||
15021 | |||||||
15022 | if (Previous.empty()) { | ||||||
15023 | // Name lookup did not find anything. However, if the | ||||||
15024 | // nested-name-specifier refers to the current instantiation, | ||||||
15025 | // and that current instantiation has any dependent base | ||||||
15026 | // classes, we might find something at instantiation time: treat | ||||||
15027 | // this as a dependent elaborated-type-specifier. | ||||||
15028 | // But this only makes any sense for reference-like lookups. | ||||||
15029 | if (Previous.wasNotFoundInCurrentInstantiation() && | ||||||
15030 | (TUK == TUK_Reference || TUK == TUK_Friend)) { | ||||||
15031 | IsDependent = true; | ||||||
15032 | return nullptr; | ||||||
15033 | } | ||||||
15034 | |||||||
15035 | // A tag 'foo::bar' must already exist. | ||||||
15036 | Diag(NameLoc, diag::err_not_tag_in_scope) | ||||||
15037 | << Kind << Name << DC << SS.getRange(); | ||||||
15038 | Name = nullptr; | ||||||
15039 | Invalid = true; | ||||||
15040 | goto CreateNewDecl; | ||||||
15041 | } | ||||||
15042 | } else if (Name) { | ||||||
15043 | // C++14 [class.mem]p14: | ||||||
15044 | // If T is the name of a class, then each of the following shall have a | ||||||
15045 | // name different from T: | ||||||
15046 | // -- every member of class T that is itself a type | ||||||
15047 | if (TUK != TUK_Reference && TUK != TUK_Friend && | ||||||
15048 | DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) | ||||||
15049 | return nullptr; | ||||||
15050 | |||||||
15051 | // If this is a named struct, check to see if there was a previous forward | ||||||
15052 | // declaration or definition. | ||||||
15053 | // FIXME: We're looking into outer scopes here, even when we | ||||||
15054 | // shouldn't be. Doing so can result in ambiguities that we | ||||||
15055 | // shouldn't be diagnosing. | ||||||
15056 | LookupName(Previous, S); | ||||||
15057 | |||||||
15058 | // When declaring or defining a tag, ignore ambiguities introduced | ||||||
15059 | // by types using'ed into this scope. | ||||||
15060 | if (Previous.isAmbiguous() && | ||||||
15061 | (TUK == TUK_Definition || TUK == TUK_Declaration)) { | ||||||
15062 | LookupResult::Filter F = Previous.makeFilter(); | ||||||
15063 | while (F.hasNext()) { | ||||||
15064 | NamedDecl *ND = F.next(); | ||||||
15065 | if (!ND->getDeclContext()->getRedeclContext()->Equals( | ||||||
15066 | SearchDC->getRedeclContext())) | ||||||
15067 | F.erase(); | ||||||
15068 | } | ||||||
15069 | F.done(); | ||||||
15070 | } | ||||||
15071 | |||||||
15072 | // C++11 [namespace.memdef]p3: | ||||||
15073 | // If the name in a friend declaration is neither qualified nor | ||||||
15074 | // a template-id and the declaration is a function or an | ||||||
15075 | // elaborated-type-specifier, the lookup to determine whether | ||||||
15076 | // the entity has been previously declared shall not consider | ||||||
15077 | // any scopes outside the innermost enclosing namespace. | ||||||
15078 | // | ||||||
15079 | // MSVC doesn't implement the above rule for types, so a friend tag | ||||||
15080 | // declaration may be a redeclaration of a type declared in an enclosing | ||||||
15081 | // scope. They do implement this rule for friend functions. | ||||||
15082 | // | ||||||
15083 | // Does it matter that this should be by scope instead of by | ||||||
15084 | // semantic context? | ||||||
15085 | if (!Previous.empty() && TUK == TUK_Friend) { | ||||||
15086 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); | ||||||
15087 | LookupResult::Filter F = Previous.makeFilter(); | ||||||
15088 | bool FriendSawTagOutsideEnclosingNamespace = false; | ||||||
15089 | while (F.hasNext()) { | ||||||
15090 | NamedDecl *ND = F.next(); | ||||||
15091 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | ||||||
15092 | if (DC->isFileContext() && | ||||||
15093 | !EnclosingNS->Encloses(ND->getDeclContext())) { | ||||||
15094 | if (getLangOpts().MSVCCompat) | ||||||
15095 | FriendSawTagOutsideEnclosingNamespace = true; | ||||||
15096 | else | ||||||
15097 | F.erase(); | ||||||
15098 | } | ||||||
15099 | } | ||||||
15100 | F.done(); | ||||||
15101 | |||||||
15102 | // Diagnose this MSVC extension in the easy case where lookup would have | ||||||
15103 | // unambiguously found something outside the enclosing namespace. | ||||||
15104 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { | ||||||
15105 | NamedDecl *ND = Previous.getFoundDecl(); | ||||||
15106 | Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) | ||||||
15107 | << createFriendTagNNSFixIt(*this, ND, S, NameLoc); | ||||||
15108 | } | ||||||
15109 | } | ||||||
15110 | |||||||
15111 | // Note: there used to be some attempt at recovery here. | ||||||
15112 | if (Previous.isAmbiguous()) | ||||||
15113 | return nullptr; | ||||||
15114 | |||||||
15115 | if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { | ||||||
15116 | // FIXME: This makes sure that we ignore the contexts associated | ||||||
15117 | // with C structs, unions, and enums when looking for a matching | ||||||
15118 | // tag declaration or definition. See the similar lookup tweak | ||||||
15119 | // in Sema::LookupName; is there a better way to deal with this? | ||||||
15120 | while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) | ||||||
15121 | SearchDC = SearchDC->getParent(); | ||||||
15122 | } | ||||||
15123 | } | ||||||
15124 | |||||||
15125 | if (Previous.isSingleResult() && | ||||||
15126 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||||
15127 | // Maybe we will complain about the shadowed template parameter. | ||||||
15128 | DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); | ||||||
15129 | // Just pretend that we didn't see the previous declaration. | ||||||
15130 | Previous.clear(); | ||||||
15131 | } | ||||||
15132 | |||||||
15133 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && | ||||||
15134 | DC->Equals(getStdNamespace())) { | ||||||
15135 | if (Name->isStr("bad_alloc")) { | ||||||
15136 | // This is a declaration of or a reference to "std::bad_alloc". | ||||||
15137 | isStdBadAlloc = true; | ||||||
15138 | |||||||
15139 | // If std::bad_alloc has been implicitly declared (but made invisible to | ||||||
15140 | // name lookup), fill in this implicit declaration as the previous | ||||||
15141 | // declaration, so that the declarations get chained appropriately. | ||||||
15142 | if (Previous.empty() && StdBadAlloc) | ||||||
15143 | Previous.addDecl(getStdBadAlloc()); | ||||||
15144 | } else if (Name->isStr("align_val_t")) { | ||||||
15145 | isStdAlignValT = true; | ||||||
15146 | if (Previous.empty() && StdAlignValT) | ||||||
15147 | Previous.addDecl(getStdAlignValT()); | ||||||
15148 | } | ||||||
15149 | } | ||||||
15150 | |||||||
15151 | // If we didn't find a previous declaration, and this is a reference | ||||||
15152 | // (or friend reference), move to the correct scope. In C++, we | ||||||
15153 | // also need to do a redeclaration lookup there, just in case | ||||||
15154 | // there's a shadow friend decl. | ||||||
15155 | if (Name && Previous.empty() && | ||||||
15156 | (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { | ||||||
15157 | if (Invalid) goto CreateNewDecl; | ||||||
15158 | assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15158, __PRETTY_FUNCTION__)); | ||||||
15159 | |||||||
15160 | if (TUK == TUK_Reference || IsTemplateParamOrArg) { | ||||||
15161 | // C++ [basic.scope.pdecl]p5: | ||||||
15162 | // -- for an elaborated-type-specifier of the form | ||||||
15163 | // | ||||||
15164 | // class-key identifier | ||||||
15165 | // | ||||||
15166 | // if the elaborated-type-specifier is used in the | ||||||
15167 | // decl-specifier-seq or parameter-declaration-clause of a | ||||||
15168 | // function defined in namespace scope, the identifier is | ||||||
15169 | // declared as a class-name in the namespace that contains | ||||||
15170 | // the declaration; otherwise, except as a friend | ||||||
15171 | // declaration, the identifier is declared in the smallest | ||||||
15172 | // non-class, non-function-prototype scope that contains the | ||||||
15173 | // declaration. | ||||||
15174 | // | ||||||
15175 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for | ||||||
15176 | // C structs and unions. | ||||||
15177 | // | ||||||
15178 | // It is an error in C++ to declare (rather than define) an enum | ||||||
15179 | // type, including via an elaborated type specifier. We'll | ||||||
15180 | // diagnose that later; for now, declare the enum in the same | ||||||
15181 | // scope as we would have picked for any other tag type. | ||||||
15182 | // | ||||||
15183 | // GNU C also supports this behavior as part of its incomplete | ||||||
15184 | // enum types extension, while GNU C++ does not. | ||||||
15185 | // | ||||||
15186 | // Find the context where we'll be declaring the tag. | ||||||
15187 | // FIXME: We would like to maintain the current DeclContext as the | ||||||
15188 | // lexical context, | ||||||
15189 | SearchDC = getTagInjectionContext(SearchDC); | ||||||
15190 | |||||||
15191 | // Find the scope where we'll be declaring the tag. | ||||||
15192 | S = getTagInjectionScope(S, getLangOpts()); | ||||||
15193 | } else { | ||||||
15194 | assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15194, __PRETTY_FUNCTION__)); | ||||||
15195 | // C++ [namespace.memdef]p3: | ||||||
15196 | // If a friend declaration in a non-local class first declares a | ||||||
15197 | // class or function, the friend class or function is a member of | ||||||
15198 | // the innermost enclosing namespace. | ||||||
15199 | SearchDC = SearchDC->getEnclosingNamespaceContext(); | ||||||
15200 | } | ||||||
15201 | |||||||
15202 | // In C++, we need to do a redeclaration lookup to properly | ||||||
15203 | // diagnose some problems. | ||||||
15204 | // FIXME: redeclaration lookup is also used (with and without C++) to find a | ||||||
15205 | // hidden declaration so that we don't get ambiguity errors when using a | ||||||
15206 | // type declared by an elaborated-type-specifier. In C that is not correct | ||||||
15207 | // and we should instead merge compatible types found by lookup. | ||||||
15208 | if (getLangOpts().CPlusPlus) { | ||||||
15209 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | ||||||
15210 | LookupQualifiedName(Previous, SearchDC); | ||||||
15211 | } else { | ||||||
15212 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | ||||||
15213 | LookupName(Previous, S); | ||||||
15214 | } | ||||||
15215 | } | ||||||
15216 | |||||||
15217 | // If we have a known previous declaration to use, then use it. | ||||||
15218 | if (Previous.empty() && SkipBody && SkipBody->Previous) | ||||||
15219 | Previous.addDecl(SkipBody->Previous); | ||||||
15220 | |||||||
15221 | if (!Previous.empty()) { | ||||||
15222 | NamedDecl *PrevDecl = Previous.getFoundDecl(); | ||||||
15223 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); | ||||||
15224 | |||||||
15225 | // It's okay to have a tag decl in the same scope as a typedef | ||||||
15226 | // which hides a tag decl in the same scope. Finding this | ||||||
15227 | // insanity with a redeclaration lookup can only actually happen | ||||||
15228 | // in C++. | ||||||
15229 | // | ||||||
15230 | // This is also okay for elaborated-type-specifiers, which is | ||||||
15231 | // technically forbidden by the current standard but which is | ||||||
15232 | // okay according to the likely resolution of an open issue; | ||||||
15233 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 | ||||||
15234 | if (getLangOpts().CPlusPlus) { | ||||||
15235 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { | ||||||
15236 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { | ||||||
15237 | TagDecl *Tag = TT->getDecl(); | ||||||
15238 | if (Tag->getDeclName() == Name && | ||||||
15239 | Tag->getDeclContext()->getRedeclContext() | ||||||
15240 | ->Equals(TD->getDeclContext()->getRedeclContext())) { | ||||||
15241 | PrevDecl = Tag; | ||||||
15242 | Previous.clear(); | ||||||
15243 | Previous.addDecl(Tag); | ||||||
15244 | Previous.resolveKind(); | ||||||
15245 | } | ||||||
15246 | } | ||||||
15247 | } | ||||||
15248 | } | ||||||
15249 | |||||||
15250 | // If this is a redeclaration of a using shadow declaration, it must | ||||||
15251 | // declare a tag in the same context. In MSVC mode, we allow a | ||||||
15252 | // redefinition if either context is within the other. | ||||||
15253 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { | ||||||
15254 | auto *OldTag = dyn_cast<TagDecl>(PrevDecl); | ||||||
15255 | if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && | ||||||
15256 | isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && | ||||||
15257 | !(OldTag && isAcceptableTagRedeclContext( | ||||||
15258 | *this, OldTag->getDeclContext(), SearchDC))) { | ||||||
15259 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); | ||||||
15260 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||||
15261 | diag::note_using_decl_target); | ||||||
15262 | Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) | ||||||
15263 | << 0; | ||||||
15264 | // Recover by ignoring the old declaration. | ||||||
15265 | Previous.clear(); | ||||||
15266 | goto CreateNewDecl; | ||||||
15267 | } | ||||||
15268 | } | ||||||
15269 | |||||||
15270 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { | ||||||
15271 | // If this is a use of a previous tag, or if the tag is already declared | ||||||
15272 | // in the same scope (so that the definition/declaration completes or | ||||||
15273 | // rementions the tag), reuse the decl. | ||||||
15274 | if (TUK == TUK_Reference || TUK == TUK_Friend || | ||||||
15275 | isDeclInScope(DirectPrevDecl, SearchDC, S, | ||||||
15276 | SS.isNotEmpty() || isMemberSpecialization)) { | ||||||
15277 | // Make sure that this wasn't declared as an enum and now used as a | ||||||
15278 | // struct or something similar. | ||||||
15279 | if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, | ||||||
15280 | TUK == TUK_Definition, KWLoc, | ||||||
15281 | Name)) { | ||||||
15282 | bool SafeToContinue | ||||||
15283 | = (PrevTagDecl->getTagKind() != TTK_Enum && | ||||||
15284 | Kind != TTK_Enum); | ||||||
15285 | if (SafeToContinue) | ||||||
15286 | Diag(KWLoc, diag::err_use_with_wrong_tag) | ||||||
15287 | << Name | ||||||
15288 | << FixItHint::CreateReplacement(SourceRange(KWLoc), | ||||||
15289 | PrevTagDecl->getKindName()); | ||||||
15290 | else | ||||||
15291 | Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; | ||||||
15292 | Diag(PrevTagDecl->getLocation(), diag::note_previous_use); | ||||||
15293 | |||||||
15294 | if (SafeToContinue) | ||||||
15295 | Kind = PrevTagDecl->getTagKind(); | ||||||
15296 | else { | ||||||
15297 | // Recover by making this an anonymous redefinition. | ||||||
15298 | Name = nullptr; | ||||||
15299 | Previous.clear(); | ||||||
15300 | Invalid = true; | ||||||
15301 | } | ||||||
15302 | } | ||||||
15303 | |||||||
15304 | if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { | ||||||
15305 | const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); | ||||||
15306 | |||||||
15307 | // If this is an elaborated-type-specifier for a scoped enumeration, | ||||||
15308 | // the 'class' keyword is not necessary and not permitted. | ||||||
15309 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||||
15310 | if (ScopedEnum) | ||||||
15311 | Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) | ||||||
15312 | << PrevEnum->isScoped() | ||||||
15313 | << FixItHint::CreateRemoval(ScopedEnumKWLoc); | ||||||
15314 | return PrevTagDecl; | ||||||
15315 | } | ||||||
15316 | |||||||
15317 | QualType EnumUnderlyingTy; | ||||||
15318 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | ||||||
15319 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); | ||||||
15320 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) | ||||||
15321 | EnumUnderlyingTy = QualType(T, 0); | ||||||
15322 | |||||||
15323 | // All conflicts with previous declarations are recovered by | ||||||
15324 | // returning the previous declaration, unless this is a definition, | ||||||
15325 | // in which case we want the caller to bail out. | ||||||
15326 | if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, | ||||||
15327 | ScopedEnum, EnumUnderlyingTy, | ||||||
15328 | IsFixed, PrevEnum)) | ||||||
15329 | return TUK == TUK_Declaration ? PrevTagDecl : nullptr; | ||||||
15330 | } | ||||||
15331 | |||||||
15332 | // C++11 [class.mem]p1: | ||||||
15333 | // A member shall not be declared twice in the member-specification, | ||||||
15334 | // except that a nested class or member class template can be declared | ||||||
15335 | // and then later defined. | ||||||
15336 | if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && | ||||||
15337 | S->isDeclScope(PrevDecl)) { | ||||||
15338 | Diag(NameLoc, diag::ext_member_redeclared); | ||||||
15339 | Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); | ||||||
15340 | } | ||||||
15341 | |||||||
15342 | if (!Invalid) { | ||||||
15343 | // If this is a use, just return the declaration we found, unless | ||||||
15344 | // we have attributes. | ||||||
15345 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||||
15346 | if (!Attrs.empty()) { | ||||||
15347 | // FIXME: Diagnose these attributes. For now, we create a new | ||||||
15348 | // declaration to hold them. | ||||||
15349 | } else if (TUK == TUK_Reference && | ||||||
15350 | (PrevTagDecl->getFriendObjectKind() == | ||||||
15351 | Decl::FOK_Undeclared || | ||||||
15352 | PrevDecl->getOwningModule() != getCurrentModule()) && | ||||||
15353 | SS.isEmpty()) { | ||||||
15354 | // This declaration is a reference to an existing entity, but | ||||||
15355 | // has different visibility from that entity: it either makes | ||||||
15356 | // a friend visible or it makes a type visible in a new module. | ||||||
15357 | // In either case, create a new declaration. We only do this if | ||||||
15358 | // the declaration would have meant the same thing if no prior | ||||||
15359 | // declaration were found, that is, if it was found in the same | ||||||
15360 | // scope where we would have injected a declaration. | ||||||
15361 | if (!getTagInjectionContext(CurContext)->getRedeclContext() | ||||||
15362 | ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) | ||||||
15363 | return PrevTagDecl; | ||||||
15364 | // This is in the injected scope, create a new declaration in | ||||||
15365 | // that scope. | ||||||
15366 | S = getTagInjectionScope(S, getLangOpts()); | ||||||
15367 | } else { | ||||||
15368 | return PrevTagDecl; | ||||||
15369 | } | ||||||
15370 | } | ||||||
15371 | |||||||
15372 | // Diagnose attempts to redefine a tag. | ||||||
15373 | if (TUK == TUK_Definition) { | ||||||
15374 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { | ||||||
15375 | // If we're defining a specialization and the previous definition | ||||||
15376 | // is from an implicit instantiation, don't emit an error | ||||||
15377 | // here; we'll catch this in the general case below. | ||||||
15378 | bool IsExplicitSpecializationAfterInstantiation = false; | ||||||
15379 | if (isMemberSpecialization) { | ||||||
15380 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) | ||||||
15381 | IsExplicitSpecializationAfterInstantiation = | ||||||
15382 | RD->getTemplateSpecializationKind() != | ||||||
15383 | TSK_ExplicitSpecialization; | ||||||
15384 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) | ||||||
15385 | IsExplicitSpecializationAfterInstantiation = | ||||||
15386 | ED->getTemplateSpecializationKind() != | ||||||
15387 | TSK_ExplicitSpecialization; | ||||||
15388 | } | ||||||
15389 | |||||||
15390 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do | ||||||
15391 | // not keep more that one definition around (merge them). However, | ||||||
15392 | // ensure the decl passes the structural compatibility check in | ||||||
15393 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). | ||||||
15394 | NamedDecl *Hidden = nullptr; | ||||||
15395 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { | ||||||
15396 | // There is a definition of this tag, but it is not visible. We | ||||||
15397 | // explicitly make use of C++'s one definition rule here, and | ||||||
15398 | // assume that this definition is identical to the hidden one | ||||||
15399 | // we already have. Make the existing definition visible and | ||||||
15400 | // use it in place of this one. | ||||||
15401 | if (!getLangOpts().CPlusPlus) { | ||||||
15402 | // Postpone making the old definition visible until after we | ||||||
15403 | // complete parsing the new one and do the structural | ||||||
15404 | // comparison. | ||||||
15405 | SkipBody->CheckSameAsPrevious = true; | ||||||
15406 | SkipBody->New = createTagFromNewDecl(); | ||||||
15407 | SkipBody->Previous = Def; | ||||||
15408 | return Def; | ||||||
15409 | } else { | ||||||
15410 | SkipBody->ShouldSkip = true; | ||||||
15411 | SkipBody->Previous = Def; | ||||||
15412 | makeMergedDefinitionVisible(Hidden); | ||||||
15413 | // Carry on and handle it like a normal definition. We'll | ||||||
15414 | // skip starting the definitiion later. | ||||||
15415 | } | ||||||
15416 | } else if (!IsExplicitSpecializationAfterInstantiation) { | ||||||
15417 | // A redeclaration in function prototype scope in C isn't | ||||||
15418 | // visible elsewhere, so merely issue a warning. | ||||||
15419 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) | ||||||
15420 | Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; | ||||||
15421 | else | ||||||
15422 | Diag(NameLoc, diag::err_redefinition) << Name; | ||||||
15423 | notePreviousDefinition(Def, | ||||||
15424 | NameLoc.isValid() ? NameLoc : KWLoc); | ||||||
15425 | // If this is a redefinition, recover by making this | ||||||
15426 | // struct be anonymous, which will make any later | ||||||
15427 | // references get the previous definition. | ||||||
15428 | Name = nullptr; | ||||||
15429 | Previous.clear(); | ||||||
15430 | Invalid = true; | ||||||
15431 | } | ||||||
15432 | } else { | ||||||
15433 | // If the type is currently being defined, complain | ||||||
15434 | // about a nested redefinition. | ||||||
15435 | auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); | ||||||
15436 | if (TD->isBeingDefined()) { | ||||||
15437 | Diag(NameLoc, diag::err_nested_redefinition) << Name; | ||||||
15438 | Diag(PrevTagDecl->getLocation(), | ||||||
15439 | diag::note_previous_definition); | ||||||
15440 | Name = nullptr; | ||||||
15441 | Previous.clear(); | ||||||
15442 | Invalid = true; | ||||||
15443 | } | ||||||
15444 | } | ||||||
15445 | |||||||
15446 | // Okay, this is definition of a previously declared or referenced | ||||||
15447 | // tag. We're going to create a new Decl for it. | ||||||
15448 | } | ||||||
15449 | |||||||
15450 | // Okay, we're going to make a redeclaration. If this is some kind | ||||||
15451 | // of reference, make sure we build the redeclaration in the same DC | ||||||
15452 | // as the original, and ignore the current access specifier. | ||||||
15453 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | ||||||
15454 | SearchDC = PrevTagDecl->getDeclContext(); | ||||||
15455 | AS = AS_none; | ||||||
15456 | } | ||||||
15457 | } | ||||||
15458 | // If we get here we have (another) forward declaration or we | ||||||
15459 | // have a definition. Just create a new decl. | ||||||
15460 | |||||||
15461 | } else { | ||||||
15462 | // If we get here, this is a definition of a new tag type in a nested | ||||||
15463 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a | ||||||
15464 | // new decl/type. We set PrevDecl to NULL so that the entities | ||||||
15465 | // have distinct types. | ||||||
15466 | Previous.clear(); | ||||||
15467 | } | ||||||
15468 | // If we get here, we're going to create a new Decl. If PrevDecl | ||||||
15469 | // is non-NULL, it's a definition of the tag declared by | ||||||
15470 | // PrevDecl. If it's NULL, we have a new definition. | ||||||
15471 | |||||||
15472 | // Otherwise, PrevDecl is not a tag, but was found with tag | ||||||
15473 | // lookup. This is only actually possible in C++, where a few | ||||||
15474 | // things like templates still live in the tag namespace. | ||||||
15475 | } else { | ||||||
15476 | // Use a better diagnostic if an elaborated-type-specifier | ||||||
15477 | // found the wrong kind of type on the first | ||||||
15478 | // (non-redeclaration) lookup. | ||||||
15479 | if ((TUK == TUK_Reference || TUK == TUK_Friend) && | ||||||
15480 | !Previous.isForRedeclaration()) { | ||||||
15481 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | ||||||
15482 | Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK | ||||||
15483 | << Kind; | ||||||
15484 | Diag(PrevDecl->getLocation(), diag::note_declared_at); | ||||||
15485 | Invalid = true; | ||||||
15486 | |||||||
15487 | // Otherwise, only diagnose if the declaration is in scope. | ||||||
15488 | } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, | ||||||
15489 | SS.isNotEmpty() || isMemberSpecialization)) { | ||||||
15490 | // do nothing | ||||||
15491 | |||||||
15492 | // Diagnose implicit declarations introduced by elaborated types. | ||||||
15493 | } else if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||||
15494 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | ||||||
15495 | Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; | ||||||
15496 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | ||||||
15497 | Invalid = true; | ||||||
15498 | |||||||
15499 | // Otherwise it's a declaration. Call out a particularly common | ||||||
15500 | // case here. | ||||||
15501 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { | ||||||
15502 | unsigned Kind = 0; | ||||||
15503 | if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; | ||||||
15504 | Diag(NameLoc, diag::err_tag_definition_of_typedef) | ||||||
15505 | << Name << Kind << TND->getUnderlyingType(); | ||||||
15506 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | ||||||
15507 | Invalid = true; | ||||||
15508 | |||||||
15509 | // Otherwise, diagnose. | ||||||
15510 | } else { | ||||||
15511 | // The tag name clashes with something else in the target scope, | ||||||
15512 | // issue an error and recover by making this tag be anonymous. | ||||||
15513 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; | ||||||
15514 | notePreviousDefinition(PrevDecl, NameLoc); | ||||||
15515 | Name = nullptr; | ||||||
15516 | Invalid = true; | ||||||
15517 | } | ||||||
15518 | |||||||
15519 | // The existing declaration isn't relevant to us; we're in a | ||||||
15520 | // new scope, so clear out the previous declaration. | ||||||
15521 | Previous.clear(); | ||||||
15522 | } | ||||||
15523 | } | ||||||
15524 | |||||||
15525 | CreateNewDecl: | ||||||
15526 | |||||||
15527 | TagDecl *PrevDecl = nullptr; | ||||||
15528 | if (Previous.isSingleResult()) | ||||||
15529 | PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); | ||||||
15530 | |||||||
15531 | // If there is an identifier, use the location of the identifier as the | ||||||
15532 | // location of the decl, otherwise use the location of the struct/union | ||||||
15533 | // keyword. | ||||||
15534 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | ||||||
15535 | |||||||
15536 | // Otherwise, create a new declaration. If there is a previous | ||||||
15537 | // declaration of the same entity, the two will be linked via | ||||||
15538 | // PrevDecl. | ||||||
15539 | TagDecl *New; | ||||||
15540 | |||||||
15541 | if (Kind == TTK_Enum) { | ||||||
15542 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | ||||||
15543 | // enum X { A, B, C } D; D should chain to X. | ||||||
15544 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, | ||||||
15545 | cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, | ||||||
15546 | ScopedEnumUsesClassTag, IsFixed); | ||||||
15547 | |||||||
15548 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) | ||||||
15549 | StdAlignValT = cast<EnumDecl>(New); | ||||||
15550 | |||||||
15551 | // If this is an undefined enum, warn. | ||||||
15552 | if (TUK != TUK_Definition && !Invalid) { | ||||||
15553 | TagDecl *Def; | ||||||
15554 | if (IsFixed && cast<EnumDecl>(New)->isFixed()) { | ||||||
15555 | // C++0x: 7.2p2: opaque-enum-declaration. | ||||||
15556 | // Conflicts are diagnosed above. Do nothing. | ||||||
15557 | } | ||||||
15558 | else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { | ||||||
15559 | Diag(Loc, diag::ext_forward_ref_enum_def) | ||||||
15560 | << New; | ||||||
15561 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
15562 | } else { | ||||||
15563 | unsigned DiagID = diag::ext_forward_ref_enum; | ||||||
15564 | if (getLangOpts().MSVCCompat) | ||||||
15565 | DiagID = diag::ext_ms_forward_ref_enum; | ||||||
15566 | else if (getLangOpts().CPlusPlus) | ||||||
15567 | DiagID = diag::err_forward_ref_enum; | ||||||
15568 | Diag(Loc, DiagID); | ||||||
15569 | } | ||||||
15570 | } | ||||||
15571 | |||||||
15572 | if (EnumUnderlying) { | ||||||
15573 | EnumDecl *ED = cast<EnumDecl>(New); | ||||||
15574 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | ||||||
15575 | ED->setIntegerTypeSourceInfo(TI); | ||||||
15576 | else | ||||||
15577 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); | ||||||
15578 | ED->setPromotionType(ED->getIntegerType()); | ||||||
15579 | assert(ED->isComplete() && "enum with type should be complete")((ED->isComplete() && "enum with type should be complete" ) ? static_cast<void> (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15579, __PRETTY_FUNCTION__)); | ||||||
15580 | } | ||||||
15581 | } else { | ||||||
15582 | // struct/union/class | ||||||
15583 | |||||||
15584 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | ||||||
15585 | // struct X { int A; } D; D should chain to X. | ||||||
15586 | if (getLangOpts().CPlusPlus) { | ||||||
15587 | // FIXME: Look for a way to use RecordDecl for simple structs. | ||||||
15588 | New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
15589 | cast_or_null<CXXRecordDecl>(PrevDecl)); | ||||||
15590 | |||||||
15591 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) | ||||||
15592 | StdBadAlloc = cast<CXXRecordDecl>(New); | ||||||
15593 | } else | ||||||
15594 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
15595 | cast_or_null<RecordDecl>(PrevDecl)); | ||||||
15596 | } | ||||||
15597 | |||||||
15598 | // C++11 [dcl.type]p3: | ||||||
15599 | // A type-specifier-seq shall not define a class or enumeration [...]. | ||||||
15600 | if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && | ||||||
15601 | TUK == TUK_Definition) { | ||||||
15602 | Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) | ||||||
15603 | << Context.getTagDeclType(New); | ||||||
15604 | Invalid = true; | ||||||
15605 | } | ||||||
15606 | |||||||
15607 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && | ||||||
15608 | DC->getDeclKind() == Decl::Enum) { | ||||||
15609 | Diag(New->getLocation(), diag::err_type_defined_in_enum) | ||||||
15610 | << Context.getTagDeclType(New); | ||||||
15611 | Invalid = true; | ||||||
15612 | } | ||||||
15613 | |||||||
15614 | // Maybe add qualifier info. | ||||||
15615 | if (SS.isNotEmpty()) { | ||||||
15616 | if (SS.isSet()) { | ||||||
15617 | // If this is either a declaration or a definition, check the | ||||||
15618 | // nested-name-specifier against the current context. | ||||||
15619 | if ((TUK == TUK_Definition || TUK == TUK_Declaration) && | ||||||
15620 | diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, | ||||||
15621 | isMemberSpecialization)) | ||||||
15622 | Invalid = true; | ||||||
15623 | |||||||
15624 | New->setQualifierInfo(SS.getWithLocInContext(Context)); | ||||||
15625 | if (TemplateParameterLists.size() > 0) { | ||||||
15626 | New->setTemplateParameterListsInfo(Context, TemplateParameterLists); | ||||||
15627 | } | ||||||
15628 | } | ||||||
15629 | else | ||||||
15630 | Invalid = true; | ||||||
15631 | } | ||||||
15632 | |||||||
15633 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | ||||||
15634 | // Add alignment attributes if necessary; these attributes are checked when | ||||||
15635 | // the ASTContext lays out the structure. | ||||||
15636 | // | ||||||
15637 | // It is important for implementing the correct semantics that this | ||||||
15638 | // happen here (in ActOnTag). The #pragma pack stack is | ||||||
15639 | // maintained as a result of parser callbacks which can occur at | ||||||
15640 | // many points during the parsing of a struct declaration (because | ||||||
15641 | // the #pragma tokens are effectively skipped over during the | ||||||
15642 | // parsing of the struct). | ||||||
15643 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | ||||||
15644 | AddAlignmentAttributesForRecord(RD); | ||||||
15645 | AddMsStructLayoutForRecord(RD); | ||||||
15646 | } | ||||||
15647 | } | ||||||
15648 | |||||||
15649 | if (ModulePrivateLoc.isValid()) { | ||||||
15650 | if (isMemberSpecialization) | ||||||
15651 | Diag(New->getLocation(), diag::err_module_private_specialization) | ||||||
15652 | << 2 | ||||||
15653 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||||
15654 | // __module_private__ does not apply to local classes. However, we only | ||||||
15655 | // diagnose this as an error when the declaration specifiers are | ||||||
15656 | // freestanding. Here, we just ignore the __module_private__. | ||||||
15657 | else if (!SearchDC->isFunctionOrMethod()) | ||||||
15658 | New->setModulePrivate(); | ||||||
15659 | } | ||||||
15660 | |||||||
15661 | // If this is a specialization of a member class (of a class template), | ||||||
15662 | // check the specialization. | ||||||
15663 | if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) | ||||||
15664 | Invalid = true; | ||||||
15665 | |||||||
15666 | // If we're declaring or defining a tag in function prototype scope in C, | ||||||
15667 | // note that this type can only be used within the function and add it to | ||||||
15668 | // the list of decls to inject into the function definition scope. | ||||||
15669 | if ((Name || Kind == TTK_Enum) && | ||||||
15670 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { | ||||||
15671 | if (getLangOpts().CPlusPlus) { | ||||||
15672 | // C++ [dcl.fct]p6: | ||||||
15673 | // Types shall not be defined in return or parameter types. | ||||||
15674 | if (TUK == TUK_Definition && !IsTypeSpecifier) { | ||||||
15675 | Diag(Loc, diag::err_type_defined_in_param_type) | ||||||
15676 | << Name; | ||||||
15677 | Invalid = true; | ||||||
15678 | } | ||||||
15679 | } else if (!PrevDecl) { | ||||||
15680 | Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); | ||||||
15681 | } | ||||||
15682 | } | ||||||
15683 | |||||||
15684 | if (Invalid) | ||||||
15685 | New->setInvalidDecl(); | ||||||
15686 | |||||||
15687 | // Set the lexical context. If the tag has a C++ scope specifier, the | ||||||
15688 | // lexical context will be different from the semantic context. | ||||||
15689 | New->setLexicalDeclContext(CurContext); | ||||||
15690 | |||||||
15691 | // Mark this as a friend decl if applicable. | ||||||
15692 | // In Microsoft mode, a friend declaration also acts as a forward | ||||||
15693 | // declaration so we always pass true to setObjectOfFriendDecl to make | ||||||
15694 | // the tag name visible. | ||||||
15695 | if (TUK == TUK_Friend) | ||||||
15696 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); | ||||||
15697 | |||||||
15698 | // Set the access specifier. | ||||||
15699 | if (!Invalid && SearchDC->isRecord()) | ||||||
15700 | SetMemberAccessSpecifier(New, PrevDecl, AS); | ||||||
15701 | |||||||
15702 | if (PrevDecl) | ||||||
15703 | CheckRedeclarationModuleOwnership(New, PrevDecl); | ||||||
15704 | |||||||
15705 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) | ||||||
15706 | New->startDefinition(); | ||||||
15707 | |||||||
15708 | ProcessDeclAttributeList(S, New, Attrs); | ||||||
15709 | AddPragmaAttributes(S, New); | ||||||
15710 | |||||||
15711 | // If this has an identifier, add it to the scope stack. | ||||||
15712 | if (TUK == TUK_Friend) { | ||||||
15713 | // We might be replacing an existing declaration in the lookup tables; | ||||||
15714 | // if so, borrow its access specifier. | ||||||
15715 | if (PrevDecl) | ||||||
15716 | New->setAccess(PrevDecl->getAccess()); | ||||||
15717 | |||||||
15718 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); | ||||||
15719 | DC->makeDeclVisibleInContext(New); | ||||||
15720 | if (Name) // can be null along some error paths | ||||||
15721 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | ||||||
15722 | PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); | ||||||
15723 | } else if (Name) { | ||||||
15724 | S = getNonFieldDeclScope(S); | ||||||
15725 | PushOnScopeChains(New, S, true); | ||||||
15726 | } else { | ||||||
15727 | CurContext->addDecl(New); | ||||||
15728 | } | ||||||
15729 | |||||||
15730 | // If this is the C FILE type, notify the AST context. | ||||||
15731 | if (IdentifierInfo *II = New->getIdentifier()) | ||||||
15732 | if (!New->isInvalidDecl() && | ||||||
15733 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||||
15734 | II->isStr("FILE")) | ||||||
15735 | Context.setFILEDecl(New); | ||||||
15736 | |||||||
15737 | if (PrevDecl) | ||||||
15738 | mergeDeclAttributes(New, PrevDecl); | ||||||
15739 | |||||||
15740 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) | ||||||
15741 | inferGslOwnerPointerAttribute(CXXRD); | ||||||
15742 | |||||||
15743 | // If there's a #pragma GCC visibility in scope, set the visibility of this | ||||||
15744 | // record. | ||||||
15745 | AddPushedVisibilityAttribute(New); | ||||||
15746 | |||||||
15747 | if (isMemberSpecialization && !New->isInvalidDecl()) | ||||||
15748 | CompleteMemberSpecialization(New, Previous); | ||||||
15749 | |||||||
15750 | OwnedDecl = true; | ||||||
15751 | // In C++, don't return an invalid declaration. We can't recover well from | ||||||
15752 | // the cases where we make the type anonymous. | ||||||
15753 | if (Invalid && getLangOpts().CPlusPlus) { | ||||||
15754 | if (New->isBeingDefined()) | ||||||
15755 | if (auto RD = dyn_cast<RecordDecl>(New)) | ||||||
15756 | RD->completeDefinition(); | ||||||
15757 | return nullptr; | ||||||
15758 | } else if (SkipBody && SkipBody->ShouldSkip) { | ||||||
15759 | return SkipBody->Previous; | ||||||
15760 | } else { | ||||||
15761 | return New; | ||||||
15762 | } | ||||||
15763 | } | ||||||
15764 | |||||||
15765 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { | ||||||
15766 | AdjustDeclIfTemplate(TagD); | ||||||
15767 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
15768 | |||||||
15769 | // Enter the tag context. | ||||||
15770 | PushDeclContext(S, Tag); | ||||||
15771 | |||||||
15772 | ActOnDocumentableDecl(TagD); | ||||||
15773 | |||||||
15774 | // If there's a #pragma GCC visibility in scope, set the visibility of this | ||||||
15775 | // record. | ||||||
15776 | AddPushedVisibilityAttribute(Tag); | ||||||
15777 | } | ||||||
15778 | |||||||
15779 | bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, | ||||||
15780 | SkipBodyInfo &SkipBody) { | ||||||
15781 | if (!hasStructuralCompatLayout(Prev, SkipBody.New)) | ||||||
15782 | return false; | ||||||
15783 | |||||||
15784 | // Make the previous decl visible. | ||||||
15785 | makeMergedDefinitionVisible(SkipBody.Previous); | ||||||
15786 | return true; | ||||||
15787 | } | ||||||
15788 | |||||||
15789 | Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { | ||||||
15790 | assert(isa<ObjCContainerDecl>(IDecl) &&((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15791, __PRETTY_FUNCTION__)) | ||||||
15791 | "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((isa<ObjCContainerDecl>(IDecl) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl" ) ? static_cast<void> (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15791, __PRETTY_FUNCTION__)); | ||||||
15792 | DeclContext *OCD = cast<DeclContext>(IDecl); | ||||||
15793 | assert(getContainingDC(OCD) == CurContext &&((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15794, __PRETTY_FUNCTION__)) | ||||||
15794 | "The next DeclContext should be lexically contained in the current one.")((getContainingDC(OCD) == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15794, __PRETTY_FUNCTION__)); | ||||||
15795 | CurContext = OCD; | ||||||
15796 | return IDecl; | ||||||
15797 | } | ||||||
15798 | |||||||
15799 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, | ||||||
15800 | SourceLocation FinalLoc, | ||||||
15801 | bool IsFinalSpelledSealed, | ||||||
15802 | SourceLocation LBraceLoc) { | ||||||
15803 | AdjustDeclIfTemplate(TagD); | ||||||
15804 | CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); | ||||||
15805 | |||||||
15806 | FieldCollector->StartClass(); | ||||||
15807 | |||||||
15808 | if (!Record->getIdentifier()) | ||||||
15809 | return; | ||||||
15810 | |||||||
15811 | if (FinalLoc.isValid()) | ||||||
15812 | Record->addAttr(FinalAttr::Create( | ||||||
15813 | Context, FinalLoc, AttributeCommonInfo::AS_Keyword, | ||||||
15814 | static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); | ||||||
15815 | |||||||
15816 | // C++ [class]p2: | ||||||
15817 | // [...] The class-name is also inserted into the scope of the | ||||||
15818 | // class itself; this is known as the injected-class-name. For | ||||||
15819 | // purposes of access checking, the injected-class-name is treated | ||||||
15820 | // as if it were a public member name. | ||||||
15821 | CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( | ||||||
15822 | Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), | ||||||
15823 | Record->getLocation(), Record->getIdentifier(), | ||||||
15824 | /*PrevDecl=*/nullptr, | ||||||
15825 | /*DelayTypeCreation=*/true); | ||||||
15826 | Context.getTypeDeclType(InjectedClassName, Record); | ||||||
15827 | InjectedClassName->setImplicit(); | ||||||
15828 | InjectedClassName->setAccess(AS_public); | ||||||
15829 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) | ||||||
15830 | InjectedClassName->setDescribedClassTemplate(Template); | ||||||
15831 | PushOnScopeChains(InjectedClassName, S); | ||||||
15832 | assert(InjectedClassName->isInjectedClassName() &&((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15833, __PRETTY_FUNCTION__)) | ||||||
15833 | "Broken injected-class-name")((InjectedClassName->isInjectedClassName() && "Broken injected-class-name" ) ? static_cast<void> (0) : __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15833, __PRETTY_FUNCTION__)); | ||||||
15834 | } | ||||||
15835 | |||||||
15836 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, | ||||||
15837 | SourceRange BraceRange) { | ||||||
15838 | AdjustDeclIfTemplate(TagD); | ||||||
15839 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
15840 | Tag->setBraceRange(BraceRange); | ||||||
15841 | |||||||
15842 | // Make sure we "complete" the definition even it is invalid. | ||||||
15843 | if (Tag->isBeingDefined()) { | ||||||
15844 | assert(Tag->isInvalidDecl() && "We should already have completed it")((Tag->isInvalidDecl() && "We should already have completed it" ) ? static_cast<void> (0) : __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15844, __PRETTY_FUNCTION__)); | ||||||
15845 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | ||||||
15846 | RD->completeDefinition(); | ||||||
15847 | } | ||||||
15848 | |||||||
15849 | if (isa<CXXRecordDecl>(Tag)) { | ||||||
15850 | FieldCollector->FinishClass(); | ||||||
15851 | } | ||||||
15852 | |||||||
15853 | // Exit this scope of this tag's definition. | ||||||
15854 | PopDeclContext(); | ||||||
15855 | |||||||
15856 | if (getCurLexicalContext()->isObjCContainer() && | ||||||
15857 | Tag->getDeclContext()->isFileContext()) | ||||||
15858 | Tag->setTopLevelDeclInObjCContainer(); | ||||||
15859 | |||||||
15860 | // Notify the consumer that we've defined a tag. | ||||||
15861 | if (!Tag->isInvalidDecl()) | ||||||
15862 | Consumer.HandleTagDeclDefinition(Tag); | ||||||
15863 | } | ||||||
15864 | |||||||
15865 | void Sema::ActOnObjCContainerFinishDefinition() { | ||||||
15866 | // Exit this scope of this interface definition. | ||||||
15867 | PopDeclContext(); | ||||||
15868 | } | ||||||
15869 | |||||||
15870 | void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { | ||||||
15871 | assert(DC == CurContext && "Mismatch of container contexts")((DC == CurContext && "Mismatch of container contexts" ) ? static_cast<void> (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 15871, __PRETTY_FUNCTION__)); | ||||||
15872 | OriginalLexicalContext = DC; | ||||||
15873 | ActOnObjCContainerFinishDefinition(); | ||||||
15874 | } | ||||||
15875 | |||||||
15876 | void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { | ||||||
15877 | ActOnObjCContainerStartDefinition(cast<Decl>(DC)); | ||||||
15878 | OriginalLexicalContext = nullptr; | ||||||
15879 | } | ||||||
15880 | |||||||
15881 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { | ||||||
15882 | AdjustDeclIfTemplate(TagD); | ||||||
15883 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
15884 | Tag->setInvalidDecl(); | ||||||
15885 | |||||||
15886 | // Make sure we "complete" the definition even it is invalid. | ||||||
15887 | if (Tag->isBeingDefined()) { | ||||||
15888 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | ||||||
15889 | RD->completeDefinition(); | ||||||
15890 | } | ||||||
15891 | |||||||
15892 | // We're undoing ActOnTagStartDefinition here, not | ||||||
15893 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with | ||||||
15894 | // the FieldCollector. | ||||||
15895 | |||||||
15896 | PopDeclContext(); | ||||||
15897 | } | ||||||
15898 | |||||||
15899 | // Note that FieldName may be null for anonymous bitfields. | ||||||
15900 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, | ||||||
15901 | IdentifierInfo *FieldName, | ||||||
15902 | QualType FieldTy, bool IsMsStruct, | ||||||
15903 | Expr *BitWidth, bool *ZeroWidth) { | ||||||
15904 | // Default to true; that shouldn't confuse checks for emptiness | ||||||
15905 | if (ZeroWidth) | ||||||
15906 | *ZeroWidth = true; | ||||||
15907 | |||||||
15908 | // C99 6.7.2.1p4 - verify the field type. | ||||||
15909 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | ||||||
15910 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { | ||||||
15911 | // Handle incomplete types with specific error. | ||||||
15912 | if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) | ||||||
15913 | return ExprError(); | ||||||
15914 | if (FieldName) | ||||||
15915 | return Diag(FieldLoc, diag::err_not_integral_type_bitfield) | ||||||
15916 | << FieldName << FieldTy << BitWidth->getSourceRange(); | ||||||
15917 | return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) | ||||||
15918 | << FieldTy << BitWidth->getSourceRange(); | ||||||
15919 | } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), | ||||||
15920 | UPPC_BitFieldWidth)) | ||||||
15921 | return ExprError(); | ||||||
15922 | |||||||
15923 | // If the bit-width is type- or value-dependent, don't try to check | ||||||
15924 | // it now. | ||||||
15925 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) | ||||||
15926 | return BitWidth; | ||||||
15927 | |||||||
15928 | llvm::APSInt Value; | ||||||
15929 | ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); | ||||||
15930 | if (ICE.isInvalid()) | ||||||
15931 | return ICE; | ||||||
15932 | BitWidth = ICE.get(); | ||||||
15933 | |||||||
15934 | if (Value != 0 && ZeroWidth) | ||||||
15935 | *ZeroWidth = false; | ||||||
15936 | |||||||
15937 | // Zero-width bitfield is ok for anonymous field. | ||||||
15938 | if (Value == 0 && FieldName) | ||||||
15939 | return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; | ||||||
15940 | |||||||
15941 | if (Value.isSigned() && Value.isNegative()) { | ||||||
15942 | if (FieldName) | ||||||
15943 | return Diag(FieldLoc, diag::err_bitfield_has_negative_width) | ||||||
15944 | << FieldName << Value.toString(10); | ||||||
15945 | return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) | ||||||
15946 | << Value.toString(10); | ||||||
15947 | } | ||||||
15948 | |||||||
15949 | if (!FieldTy->isDependentType()) { | ||||||
15950 | uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); | ||||||
15951 | uint64_t TypeWidth = Context.getIntWidth(FieldTy); | ||||||
15952 | bool BitfieldIsOverwide = Value.ugt(TypeWidth); | ||||||
15953 | |||||||
15954 | // Over-wide bitfields are an error in C or when using the MSVC bitfield | ||||||
15955 | // ABI. | ||||||
15956 | bool CStdConstraintViolation = | ||||||
15957 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; | ||||||
15958 | bool MSBitfieldViolation = | ||||||
15959 | Value.ugt(TypeStorageSize) && | ||||||
15960 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); | ||||||
15961 | if (CStdConstraintViolation || MSBitfieldViolation) { | ||||||
15962 | unsigned DiagWidth = | ||||||
15963 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; | ||||||
15964 | if (FieldName) | ||||||
15965 | return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) | ||||||
15966 | << FieldName << (unsigned)Value.getZExtValue() | ||||||
15967 | << !CStdConstraintViolation << DiagWidth; | ||||||
15968 | |||||||
15969 | return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) | ||||||
15970 | << (unsigned)Value.getZExtValue() << !CStdConstraintViolation | ||||||
15971 | << DiagWidth; | ||||||
15972 | } | ||||||
15973 | |||||||
15974 | // Warn on types where the user might conceivably expect to get all | ||||||
15975 | // specified bits as value bits: that's all integral types other than | ||||||
15976 | // 'bool'. | ||||||
15977 | if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { | ||||||
15978 | if (FieldName) | ||||||
15979 | Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) | ||||||
15980 | << FieldName << (unsigned)Value.getZExtValue() | ||||||
15981 | << (unsigned)TypeWidth; | ||||||
15982 | else | ||||||
15983 | Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) | ||||||
15984 | << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; | ||||||
15985 | } | ||||||
15986 | } | ||||||
15987 | |||||||
15988 | return BitWidth; | ||||||
15989 | } | ||||||
15990 | |||||||
15991 | /// ActOnField - Each field of a C struct/union is passed into this in order | ||||||
15992 | /// to create a FieldDecl object for it. | ||||||
15993 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, | ||||||
15994 | Declarator &D, Expr *BitfieldWidth) { | ||||||
15995 | FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), | ||||||
15996 | DeclStart, D, static_cast<Expr*>(BitfieldWidth), | ||||||
15997 | /*InitStyle=*/ICIS_NoInit, AS_public); | ||||||
15998 | return Res; | ||||||
15999 | } | ||||||
16000 | |||||||
16001 | /// HandleField - Analyze a field of a C struct or a C++ data member. | ||||||
16002 | /// | ||||||
16003 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, | ||||||
16004 | SourceLocation DeclStart, | ||||||
16005 | Declarator &D, Expr *BitWidth, | ||||||
16006 | InClassInitStyle InitStyle, | ||||||
16007 | AccessSpecifier AS) { | ||||||
16008 | if (D.isDecompositionDeclarator()) { | ||||||
16009 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | ||||||
16010 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | ||||||
16011 | << Decomp.getSourceRange(); | ||||||
16012 | return nullptr; | ||||||
16013 | } | ||||||
16014 | |||||||
16015 | IdentifierInfo *II = D.getIdentifier(); | ||||||
16016 | SourceLocation Loc = DeclStart; | ||||||
16017 | if (II) Loc = D.getIdentifierLoc(); | ||||||
16018 | |||||||
16019 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
16020 | QualType T = TInfo->getType(); | ||||||
16021 | if (getLangOpts().CPlusPlus) { | ||||||
16022 | CheckExtraCXXDefaultArguments(D); | ||||||
16023 | |||||||
16024 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||||
16025 | UPPC_DataMemberType)) { | ||||||
16026 | D.setInvalidType(); | ||||||
16027 | T = Context.IntTy; | ||||||
16028 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | ||||||
16029 | } | ||||||
16030 | } | ||||||
16031 | |||||||
16032 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
16033 | |||||||
16034 | if (D.getDeclSpec().isInlineSpecified()) | ||||||
16035 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
16036 | << getLangOpts().CPlusPlus17; | ||||||
16037 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||||
16038 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
16039 | diag::err_invalid_thread) | ||||||
16040 | << DeclSpec::getSpecifierName(TSCS); | ||||||
16041 | |||||||
16042 | // Check to see if this name was declared as a member previously | ||||||
16043 | NamedDecl *PrevDecl = nullptr; | ||||||
16044 | LookupResult Previous(*this, II, Loc, LookupMemberName, | ||||||
16045 | ForVisibleRedeclaration); | ||||||
16046 | LookupName(Previous, S); | ||||||
16047 | switch (Previous.getResultKind()) { | ||||||
16048 | case LookupResult::Found: | ||||||
16049 | case LookupResult::FoundUnresolvedValue: | ||||||
16050 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | ||||||
16051 | break; | ||||||
16052 | |||||||
16053 | case LookupResult::FoundOverloaded: | ||||||
16054 | PrevDecl = Previous.getRepresentativeDecl(); | ||||||
16055 | break; | ||||||
16056 | |||||||
16057 | case LookupResult::NotFound: | ||||||
16058 | case LookupResult::NotFoundInCurrentInstantiation: | ||||||
16059 | case LookupResult::Ambiguous: | ||||||
16060 | break; | ||||||
16061 | } | ||||||
16062 | Previous.suppressDiagnostics(); | ||||||
16063 | |||||||
16064 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||||
16065 | // Maybe we will complain about the shadowed template parameter. | ||||||
16066 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||||
16067 | // Just pretend that we didn't see the previous declaration. | ||||||
16068 | PrevDecl = nullptr; | ||||||
16069 | } | ||||||
16070 | |||||||
16071 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | ||||||
16072 | PrevDecl = nullptr; | ||||||
16073 | |||||||
16074 | bool Mutable | ||||||
16075 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); | ||||||
16076 | SourceLocation TSSL = D.getBeginLoc(); | ||||||
16077 | FieldDecl *NewFD | ||||||
16078 | = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, | ||||||
16079 | TSSL, AS, PrevDecl, &D); | ||||||
16080 | |||||||
16081 | if (NewFD->isInvalidDecl()) | ||||||
16082 | Record->setInvalidDecl(); | ||||||
16083 | |||||||
16084 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
16085 | NewFD->setModulePrivate(); | ||||||
16086 | |||||||
16087 | if (NewFD->isInvalidDecl() && PrevDecl) { | ||||||
16088 | // Don't introduce NewFD into scope; there's already something | ||||||
16089 | // with the same name in the same scope. | ||||||
16090 | } else if (II) { | ||||||
16091 | PushOnScopeChains(NewFD, S); | ||||||
16092 | } else | ||||||
16093 | Record->addDecl(NewFD); | ||||||
16094 | |||||||
16095 | return NewFD; | ||||||
16096 | } | ||||||
16097 | |||||||
16098 | /// Build a new FieldDecl and check its well-formedness. | ||||||
16099 | /// | ||||||
16100 | /// This routine builds a new FieldDecl given the fields name, type, | ||||||
16101 | /// record, etc. \p PrevDecl should refer to any previous declaration | ||||||
16102 | /// with the same name and in the same scope as the field to be | ||||||
16103 | /// created. | ||||||
16104 | /// | ||||||
16105 | /// \returns a new FieldDecl. | ||||||
16106 | /// | ||||||
16107 | /// \todo The Declarator argument is a hack. It will be removed once | ||||||
16108 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, | ||||||
16109 | TypeSourceInfo *TInfo, | ||||||
16110 | RecordDecl *Record, SourceLocation Loc, | ||||||
16111 | bool Mutable, Expr *BitWidth, | ||||||
16112 | InClassInitStyle InitStyle, | ||||||
16113 | SourceLocation TSSL, | ||||||
16114 | AccessSpecifier AS, NamedDecl *PrevDecl, | ||||||
16115 | Declarator *D) { | ||||||
16116 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||
16117 | bool InvalidDecl = false; | ||||||
16118 | if (D) InvalidDecl = D->isInvalidType(); | ||||||
16119 | |||||||
16120 | // If we receive a broken type, recover by assuming 'int' and | ||||||
16121 | // marking this declaration as invalid. | ||||||
16122 | if (T.isNull()) { | ||||||
16123 | InvalidDecl = true; | ||||||
16124 | T = Context.IntTy; | ||||||
16125 | } | ||||||
16126 | |||||||
16127 | QualType EltTy = Context.getBaseElementType(T); | ||||||
16128 | if (!EltTy->isDependentType()) { | ||||||
16129 | if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { | ||||||
16130 | // Fields of incomplete type force their record to be invalid. | ||||||
16131 | Record->setInvalidDecl(); | ||||||
16132 | InvalidDecl = true; | ||||||
16133 | } else { | ||||||
16134 | NamedDecl *Def; | ||||||
16135 | EltTy->isIncompleteType(&Def); | ||||||
16136 | if (Def && Def->isInvalidDecl()) { | ||||||
16137 | Record->setInvalidDecl(); | ||||||
16138 | InvalidDecl = true; | ||||||
16139 | } | ||||||
16140 | } | ||||||
16141 | } | ||||||
16142 | |||||||
16143 | // TR 18037 does not allow fields to be declared with address space | ||||||
16144 | if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || | ||||||
16145 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { | ||||||
16146 | Diag(Loc, diag::err_field_with_address_space); | ||||||
16147 | Record->setInvalidDecl(); | ||||||
16148 | InvalidDecl = true; | ||||||
16149 | } | ||||||
16150 | |||||||
16151 | if (LangOpts.OpenCL) { | ||||||
16152 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be | ||||||
16153 | // used as structure or union field: image, sampler, event or block types. | ||||||
16154 | if (T->isEventT() || T->isImageType() || T->isSamplerT() || | ||||||
16155 | T->isBlockPointerType()) { | ||||||
16156 | Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; | ||||||
16157 | Record->setInvalidDecl(); | ||||||
16158 | InvalidDecl = true; | ||||||
16159 | } | ||||||
16160 | // OpenCL v1.2 s6.9.c: bitfields are not supported. | ||||||
16161 | if (BitWidth) { | ||||||
16162 | Diag(Loc, diag::err_opencl_bitfields); | ||||||
16163 | InvalidDecl = true; | ||||||
16164 | } | ||||||
16165 | } | ||||||
16166 | |||||||
16167 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). | ||||||
16168 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && | ||||||
16169 | T.hasQualifiers()) { | ||||||
16170 | InvalidDecl = true; | ||||||
16171 | Diag(Loc, diag::err_anon_bitfield_qualifiers); | ||||||
16172 | } | ||||||
16173 | |||||||
16174 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | ||||||
16175 | // than a variably modified type. | ||||||
16176 | if (!InvalidDecl && T->isVariablyModifiedType()) { | ||||||
16177 | bool SizeIsNegative; | ||||||
16178 | llvm::APSInt Oversized; | ||||||
16179 | |||||||
16180 | TypeSourceInfo *FixedTInfo = | ||||||
16181 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||||
16182 | SizeIsNegative, | ||||||
16183 | Oversized); | ||||||
16184 | if (FixedTInfo) { | ||||||
16185 | Diag(Loc, diag::warn_illegal_constant_array_size); | ||||||
16186 | TInfo = FixedTInfo; | ||||||
16187 | T = FixedTInfo->getType(); | ||||||
16188 | } else { | ||||||
16189 | if (SizeIsNegative) | ||||||
16190 | Diag(Loc, diag::err_typecheck_negative_array_size); | ||||||
16191 | else if (Oversized.getBoolValue()) | ||||||
16192 | Diag(Loc, diag::err_array_too_large) | ||||||
16193 | << Oversized.toString(10); | ||||||
16194 | else | ||||||
16195 | Diag(Loc, diag::err_typecheck_field_variable_size); | ||||||
16196 | InvalidDecl = true; | ||||||
16197 | } | ||||||
16198 | } | ||||||
16199 | |||||||
16200 | // Fields can not have abstract class types | ||||||
16201 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, | ||||||
16202 | diag::err_abstract_type_in_decl, | ||||||
16203 | AbstractFieldType)) | ||||||
16204 | InvalidDecl = true; | ||||||
16205 | |||||||
16206 | bool ZeroWidth = false; | ||||||
16207 | if (InvalidDecl) | ||||||
16208 | BitWidth = nullptr; | ||||||
16209 | // If this is declared as a bit-field, check the bit-field. | ||||||
16210 | if (BitWidth) { | ||||||
16211 | BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, | ||||||
16212 | &ZeroWidth).get(); | ||||||
16213 | if (!BitWidth) { | ||||||
16214 | InvalidDecl = true; | ||||||
16215 | BitWidth = nullptr; | ||||||
16216 | ZeroWidth = false; | ||||||
16217 | } | ||||||
16218 | } | ||||||
16219 | |||||||
16220 | // Check that 'mutable' is consistent with the type of the declaration. | ||||||
16221 | if (!InvalidDecl && Mutable) { | ||||||
16222 | unsigned DiagID = 0; | ||||||
16223 | if (T->isReferenceType()) | ||||||
16224 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference | ||||||
16225 | : diag::err_mutable_reference; | ||||||
16226 | else if (T.isConstQualified()) | ||||||
16227 | DiagID = diag::err_mutable_const; | ||||||
16228 | |||||||
16229 | if (DiagID) { | ||||||
16230 | SourceLocation ErrLoc = Loc; | ||||||
16231 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) | ||||||
16232 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); | ||||||
16233 | Diag(ErrLoc, DiagID); | ||||||
16234 | if (DiagID != diag::ext_mutable_reference) { | ||||||
16235 | Mutable = false; | ||||||
16236 | InvalidDecl = true; | ||||||
16237 | } | ||||||
16238 | } | ||||||
16239 | } | ||||||
16240 | |||||||
16241 | // C++11 [class.union]p8 (DR1460): | ||||||
16242 | // At most one variant member of a union may have a | ||||||
16243 | // brace-or-equal-initializer. | ||||||
16244 | if (InitStyle != ICIS_NoInit) | ||||||
16245 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); | ||||||
16246 | |||||||
16247 | FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, | ||||||
16248 | BitWidth, Mutable, InitStyle); | ||||||
16249 | if (InvalidDecl) | ||||||
16250 | NewFD->setInvalidDecl(); | ||||||
16251 | |||||||
16252 | if (PrevDecl && !isa<TagDecl>(PrevDecl)) { | ||||||
16253 | Diag(Loc, diag::err_duplicate_member) << II; | ||||||
16254 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
16255 | NewFD->setInvalidDecl(); | ||||||
16256 | } | ||||||
16257 | |||||||
16258 | if (!InvalidDecl && getLangOpts().CPlusPlus) { | ||||||
16259 | if (Record->isUnion()) { | ||||||
16260 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | ||||||
16261 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||||
16262 | if (RDecl->getDefinition()) { | ||||||
16263 | // C++ [class.union]p1: An object of a class with a non-trivial | ||||||
16264 | // constructor, a non-trivial copy constructor, a non-trivial | ||||||
16265 | // destructor, or a non-trivial copy assignment operator | ||||||
16266 | // cannot be a member of a union, nor can an array of such | ||||||
16267 | // objects. | ||||||
16268 | if (CheckNontrivialField(NewFD)) | ||||||
16269 | NewFD->setInvalidDecl(); | ||||||
16270 | } | ||||||
16271 | } | ||||||
16272 | |||||||
16273 | // C++ [class.union]p1: If a union contains a member of reference type, | ||||||
16274 | // the program is ill-formed, except when compiling with MSVC extensions | ||||||
16275 | // enabled. | ||||||
16276 | if (EltTy->isReferenceType()) { | ||||||
16277 | Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? | ||||||
16278 | diag::ext_union_member_of_reference_type : | ||||||
16279 | diag::err_union_member_of_reference_type) | ||||||
16280 | << NewFD->getDeclName() << EltTy; | ||||||
16281 | if (!getLangOpts().MicrosoftExt) | ||||||
16282 | NewFD->setInvalidDecl(); | ||||||
16283 | } | ||||||
16284 | } | ||||||
16285 | } | ||||||
16286 | |||||||
16287 | // FIXME: We need to pass in the attributes given an AST | ||||||
16288 | // representation, not a parser representation. | ||||||
16289 | if (D) { | ||||||
16290 | // FIXME: The current scope is almost... but not entirely... correct here. | ||||||
16291 | ProcessDeclAttributes(getCurScope(), NewFD, *D); | ||||||
16292 | |||||||
16293 | if (NewFD->hasAttrs()) | ||||||
16294 | CheckAlignasUnderalignment(NewFD); | ||||||
16295 | } | ||||||
16296 | |||||||
16297 | // In auto-retain/release, infer strong retension for fields of | ||||||
16298 | // retainable type. | ||||||
16299 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) | ||||||
16300 | NewFD->setInvalidDecl(); | ||||||
16301 | |||||||
16302 | if (T.isObjCGCWeak()) | ||||||
16303 | Diag(Loc, diag::warn_attribute_weak_on_field); | ||||||
16304 | |||||||
16305 | NewFD->setAccess(AS); | ||||||
16306 | return NewFD; | ||||||
16307 | } | ||||||
16308 | |||||||
16309 | bool Sema::CheckNontrivialField(FieldDecl *FD) { | ||||||
16310 | assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16310, __PRETTY_FUNCTION__)); | ||||||
16311 | assert(getLangOpts().CPlusPlus && "valid check only for C++")((getLangOpts().CPlusPlus && "valid check only for C++" ) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16311, __PRETTY_FUNCTION__)); | ||||||
16312 | |||||||
16313 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) | ||||||
16314 | return false; | ||||||
16315 | |||||||
16316 | QualType EltTy = Context.getBaseElementType(FD->getType()); | ||||||
16317 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | ||||||
16318 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||||
16319 | if (RDecl->getDefinition()) { | ||||||
16320 | // We check for copy constructors before constructors | ||||||
16321 | // because otherwise we'll never get complaints about | ||||||
16322 | // copy constructors. | ||||||
16323 | |||||||
16324 | CXXSpecialMember member = CXXInvalid; | ||||||
16325 | // We're required to check for any non-trivial constructors. Since the | ||||||
16326 | // implicit default constructor is suppressed if there are any | ||||||
16327 | // user-declared constructors, we just need to check that there is a | ||||||
16328 | // trivial default constructor and a trivial copy constructor. (We don't | ||||||
16329 | // worry about move constructors here, since this is a C++98 check.) | ||||||
16330 | if (RDecl->hasNonTrivialCopyConstructor()) | ||||||
16331 | member = CXXCopyConstructor; | ||||||
16332 | else if (!RDecl->hasTrivialDefaultConstructor()) | ||||||
16333 | member = CXXDefaultConstructor; | ||||||
16334 | else if (RDecl->hasNonTrivialCopyAssignment()) | ||||||
16335 | member = CXXCopyAssignment; | ||||||
16336 | else if (RDecl->hasNonTrivialDestructor()) | ||||||
16337 | member = CXXDestructor; | ||||||
16338 | |||||||
16339 | if (member != CXXInvalid) { | ||||||
16340 | if (!getLangOpts().CPlusPlus11 && | ||||||
16341 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { | ||||||
16342 | // Objective-C++ ARC: it is an error to have a non-trivial field of | ||||||
16343 | // a union. However, system headers in Objective-C programs | ||||||
16344 | // occasionally have Objective-C lifetime objects within unions, | ||||||
16345 | // and rather than cause the program to fail, we make those | ||||||
16346 | // members unavailable. | ||||||
16347 | SourceLocation Loc = FD->getLocation(); | ||||||
16348 | if (getSourceManager().isInSystemHeader(Loc)) { | ||||||
16349 | if (!FD->hasAttr<UnavailableAttr>()) | ||||||
16350 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | ||||||
16351 | UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); | ||||||
16352 | return false; | ||||||
16353 | } | ||||||
16354 | } | ||||||
16355 | |||||||
16356 | Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? | ||||||
16357 | diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : | ||||||
16358 | diag::err_illegal_union_or_anon_struct_member) | ||||||
16359 | << FD->getParent()->isUnion() << FD->getDeclName() << member; | ||||||
16360 | DiagnoseNontrivial(RDecl, member); | ||||||
16361 | return !getLangOpts().CPlusPlus11; | ||||||
16362 | } | ||||||
16363 | } | ||||||
16364 | } | ||||||
16365 | |||||||
16366 | return false; | ||||||
16367 | } | ||||||
16368 | |||||||
16369 | /// TranslateIvarVisibility - Translate visibility from a token ID to an | ||||||
16370 | /// AST enum value. | ||||||
16371 | static ObjCIvarDecl::AccessControl | ||||||
16372 | TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { | ||||||
16373 | switch (ivarVisibility) { | ||||||
16374 | default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16374); | ||||||
16375 | case tok::objc_private: return ObjCIvarDecl::Private; | ||||||
16376 | case tok::objc_public: return ObjCIvarDecl::Public; | ||||||
16377 | case tok::objc_protected: return ObjCIvarDecl::Protected; | ||||||
16378 | case tok::objc_package: return ObjCIvarDecl::Package; | ||||||
16379 | } | ||||||
16380 | } | ||||||
16381 | |||||||
16382 | /// ActOnIvar - Each ivar field of an objective-c class is passed into this | ||||||
16383 | /// in order to create an IvarDecl object for it. | ||||||
16384 | Decl *Sema::ActOnIvar(Scope *S, | ||||||
16385 | SourceLocation DeclStart, | ||||||
16386 | Declarator &D, Expr *BitfieldWidth, | ||||||
16387 | tok::ObjCKeywordKind Visibility) { | ||||||
16388 | |||||||
16389 | IdentifierInfo *II = D.getIdentifier(); | ||||||
16390 | Expr *BitWidth = (Expr*)BitfieldWidth; | ||||||
16391 | SourceLocation Loc = DeclStart; | ||||||
16392 | if (II) Loc = D.getIdentifierLoc(); | ||||||
16393 | |||||||
16394 | // FIXME: Unnamed fields can be handled in various different ways, for | ||||||
16395 | // example, unnamed unions inject all members into the struct namespace! | ||||||
16396 | |||||||
16397 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
16398 | QualType T = TInfo->getType(); | ||||||
16399 | |||||||
16400 | if (BitWidth) { | ||||||
16401 | // 6.7.2.1p3, 6.7.2.1p4 | ||||||
16402 | BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); | ||||||
16403 | if (!BitWidth) | ||||||
16404 | D.setInvalidType(); | ||||||
16405 | } else { | ||||||
16406 | // Not a bitfield. | ||||||
16407 | |||||||
16408 | // validate II. | ||||||
16409 | |||||||
16410 | } | ||||||
16411 | if (T->isReferenceType()) { | ||||||
16412 | Diag(Loc, diag::err_ivar_reference_type); | ||||||
16413 | D.setInvalidType(); | ||||||
16414 | } | ||||||
16415 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | ||||||
16416 | // than a variably modified type. | ||||||
16417 | else if (T->isVariablyModifiedType()) { | ||||||
16418 | Diag(Loc, diag::err_typecheck_ivar_variable_size); | ||||||
16419 | D.setInvalidType(); | ||||||
16420 | } | ||||||
16421 | |||||||
16422 | // Get the visibility (access control) for this ivar. | ||||||
16423 | ObjCIvarDecl::AccessControl ac = | ||||||
16424 | Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) | ||||||
16425 | : ObjCIvarDecl::None; | ||||||
16426 | // Must set ivar's DeclContext to its enclosing interface. | ||||||
16427 | ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); | ||||||
16428 | if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) | ||||||
16429 | return nullptr; | ||||||
16430 | ObjCContainerDecl *EnclosingContext; | ||||||
16431 | if (ObjCImplementationDecl *IMPDecl = | ||||||
16432 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | ||||||
16433 | if (LangOpts.ObjCRuntime.isFragile()) { | ||||||
16434 | // Case of ivar declared in an implementation. Context is that of its class. | ||||||
16435 | EnclosingContext = IMPDecl->getClassInterface(); | ||||||
16436 | assert(EnclosingContext && "Implementation has no class interface!")((EnclosingContext && "Implementation has no class interface!" ) ? static_cast<void> (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16436, __PRETTY_FUNCTION__)); | ||||||
16437 | } | ||||||
16438 | else | ||||||
16439 | EnclosingContext = EnclosingDecl; | ||||||
16440 | } else { | ||||||
16441 | if (ObjCCategoryDecl *CDecl = | ||||||
16442 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | ||||||
16443 | if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { | ||||||
16444 | Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); | ||||||
16445 | return nullptr; | ||||||
16446 | } | ||||||
16447 | } | ||||||
16448 | EnclosingContext = EnclosingDecl; | ||||||
16449 | } | ||||||
16450 | |||||||
16451 | // Construct the decl. | ||||||
16452 | ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, | ||||||
16453 | DeclStart, Loc, II, T, | ||||||
16454 | TInfo, ac, (Expr *)BitfieldWidth); | ||||||
16455 | |||||||
16456 | if (II) { | ||||||
16457 | NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, | ||||||
16458 | ForVisibleRedeclaration); | ||||||
16459 | if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) | ||||||
16460 | && !isa<TagDecl>(PrevDecl)) { | ||||||
16461 | Diag(Loc, diag::err_duplicate_member) << II; | ||||||
16462 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
16463 | NewID->setInvalidDecl(); | ||||||
16464 | } | ||||||
16465 | } | ||||||
16466 | |||||||
16467 | // Process attributes attached to the ivar. | ||||||
16468 | ProcessDeclAttributes(S, NewID, D); | ||||||
16469 | |||||||
16470 | if (D.isInvalidType()) | ||||||
16471 | NewID->setInvalidDecl(); | ||||||
16472 | |||||||
16473 | // In ARC, infer 'retaining' for ivars of retainable type. | ||||||
16474 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) | ||||||
16475 | NewID->setInvalidDecl(); | ||||||
16476 | |||||||
16477 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
16478 | NewID->setModulePrivate(); | ||||||
16479 | |||||||
16480 | if (II) { | ||||||
16481 | // FIXME: When interfaces are DeclContexts, we'll need to add | ||||||
16482 | // these to the interface. | ||||||
16483 | S->AddDecl(NewID); | ||||||
16484 | IdResolver.AddDecl(NewID); | ||||||
16485 | } | ||||||
16486 | |||||||
16487 | if (LangOpts.ObjCRuntime.isNonFragile() && | ||||||
16488 | !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) | ||||||
16489 | Diag(Loc, diag::warn_ivars_in_interface); | ||||||
16490 | |||||||
16491 | return NewID; | ||||||
16492 | } | ||||||
16493 | |||||||
16494 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for | ||||||
16495 | /// class and class extensions. For every class \@interface and class | ||||||
16496 | /// extension \@interface, if the last ivar is a bitfield of any type, | ||||||
16497 | /// then add an implicit `char :0` ivar to the end of that interface. | ||||||
16498 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, | ||||||
16499 | SmallVectorImpl<Decl *> &AllIvarDecls) { | ||||||
16500 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) | ||||||
16501 | return; | ||||||
16502 | |||||||
16503 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; | ||||||
16504 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); | ||||||
16505 | |||||||
16506 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) | ||||||
16507 | return; | ||||||
16508 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); | ||||||
16509 | if (!ID) { | ||||||
16510 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { | ||||||
16511 | if (!CD->IsClassExtension()) | ||||||
16512 | return; | ||||||
16513 | } | ||||||
16514 | // No need to add this to end of @implementation. | ||||||
16515 | else | ||||||
16516 | return; | ||||||
16517 | } | ||||||
16518 | // All conditions are met. Add a new bitfield to the tail end of ivars. | ||||||
16519 | llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); | ||||||
16520 | Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); | ||||||
16521 | |||||||
16522 | Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), | ||||||
16523 | DeclLoc, DeclLoc, nullptr, | ||||||
16524 | Context.CharTy, | ||||||
16525 | Context.getTrivialTypeSourceInfo(Context.CharTy, | ||||||
16526 | DeclLoc), | ||||||
16527 | ObjCIvarDecl::Private, BW, | ||||||
16528 | true); | ||||||
16529 | AllIvarDecls.push_back(Ivar); | ||||||
16530 | } | ||||||
16531 | |||||||
16532 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, | ||||||
16533 | ArrayRef<Decl *> Fields, SourceLocation LBrac, | ||||||
16534 | SourceLocation RBrac, | ||||||
16535 | const ParsedAttributesView &Attrs) { | ||||||
16536 | assert(EnclosingDecl && "missing record or interface decl")((EnclosingDecl && "missing record or interface decl" ) ? static_cast<void> (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16536, __PRETTY_FUNCTION__)); | ||||||
16537 | |||||||
16538 | // If this is an Objective-C @implementation or category and we have | ||||||
16539 | // new fields here we should reset the layout of the interface since | ||||||
16540 | // it will now change. | ||||||
16541 | if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { | ||||||
16542 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); | ||||||
16543 | switch (DC->getKind()) { | ||||||
16544 | default: break; | ||||||
16545 | case Decl::ObjCCategory: | ||||||
16546 | Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); | ||||||
16547 | break; | ||||||
16548 | case Decl::ObjCImplementation: | ||||||
16549 | Context. | ||||||
16550 | ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); | ||||||
16551 | break; | ||||||
16552 | } | ||||||
16553 | } | ||||||
16554 | |||||||
16555 | RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); | ||||||
16556 | CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); | ||||||
16557 | |||||||
16558 | // Start counting up the number of named members; make sure to include | ||||||
16559 | // members of anonymous structs and unions in the total. | ||||||
16560 | unsigned NumNamedMembers = 0; | ||||||
16561 | if (Record) { | ||||||
16562 | for (const auto *I : Record->decls()) { | ||||||
16563 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||||
16564 | if (IFD->getDeclName()) | ||||||
16565 | ++NumNamedMembers; | ||||||
16566 | } | ||||||
16567 | } | ||||||
16568 | |||||||
16569 | // Verify that all the fields are okay. | ||||||
16570 | SmallVector<FieldDecl*, 32> RecFields; | ||||||
16571 | |||||||
16572 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); | ||||||
16573 | i != end; ++i) { | ||||||
16574 | FieldDecl *FD = cast<FieldDecl>(*i); | ||||||
16575 | |||||||
16576 | // Get the type for the field. | ||||||
16577 | const Type *FDTy = FD->getType().getTypePtr(); | ||||||
16578 | |||||||
16579 | if (!FD->isAnonymousStructOrUnion()) { | ||||||
16580 | // Remember all fields written by the user. | ||||||
16581 | RecFields.push_back(FD); | ||||||
16582 | } | ||||||
16583 | |||||||
16584 | // If the field is already invalid for some reason, don't emit more | ||||||
16585 | // diagnostics about it. | ||||||
16586 | if (FD->isInvalidDecl()) { | ||||||
16587 | EnclosingDecl->setInvalidDecl(); | ||||||
16588 | continue; | ||||||
16589 | } | ||||||
16590 | |||||||
16591 | // C99 6.7.2.1p2: | ||||||
16592 | // A structure or union shall not contain a member with | ||||||
16593 | // incomplete or function type (hence, a structure shall not | ||||||
16594 | // contain an instance of itself, but may contain a pointer to | ||||||
16595 | // an instance of itself), except that the last member of a | ||||||
16596 | // structure with more than one named member may have incomplete | ||||||
16597 | // array type; such a structure (and any union containing, | ||||||
16598 | // possibly recursively, a member that is such a structure) | ||||||
16599 | // shall not be a member of a structure or an element of an | ||||||
16600 | // array. | ||||||
16601 | bool IsLastField = (i + 1 == Fields.end()); | ||||||
16602 | if (FDTy->isFunctionType()) { | ||||||
16603 | // Field declared as a function. | ||||||
16604 | Diag(FD->getLocation(), diag::err_field_declared_as_function) | ||||||
16605 | << FD->getDeclName(); | ||||||
16606 | FD->setInvalidDecl(); | ||||||
16607 | EnclosingDecl->setInvalidDecl(); | ||||||
16608 | continue; | ||||||
16609 | } else if (FDTy->isIncompleteArrayType() && | ||||||
16610 | (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { | ||||||
16611 | if (Record) { | ||||||
16612 | // Flexible array member. | ||||||
16613 | // Microsoft and g++ is more permissive regarding flexible array. | ||||||
16614 | // It will accept flexible array in union and also | ||||||
16615 | // as the sole element of a struct/class. | ||||||
16616 | unsigned DiagID = 0; | ||||||
16617 | if (!Record->isUnion() && !IsLastField) { | ||||||
16618 | Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) | ||||||
16619 | << FD->getDeclName() << FD->getType() << Record->getTagKind(); | ||||||
16620 | Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); | ||||||
16621 | FD->setInvalidDecl(); | ||||||
16622 | EnclosingDecl->setInvalidDecl(); | ||||||
16623 | continue; | ||||||
16624 | } else if (Record->isUnion()) | ||||||
16625 | DiagID = getLangOpts().MicrosoftExt | ||||||
16626 | ? diag::ext_flexible_array_union_ms | ||||||
16627 | : getLangOpts().CPlusPlus | ||||||
16628 | ? diag::ext_flexible_array_union_gnu | ||||||
16629 | : diag::err_flexible_array_union; | ||||||
16630 | else if (NumNamedMembers < 1) | ||||||
16631 | DiagID = getLangOpts().MicrosoftExt | ||||||
16632 | ? diag::ext_flexible_array_empty_aggregate_ms | ||||||
16633 | : getLangOpts().CPlusPlus | ||||||
16634 | ? diag::ext_flexible_array_empty_aggregate_gnu | ||||||
16635 | : diag::err_flexible_array_empty_aggregate; | ||||||
16636 | |||||||
16637 | if (DiagID) | ||||||
16638 | Diag(FD->getLocation(), DiagID) << FD->getDeclName() | ||||||
16639 | << Record->getTagKind(); | ||||||
16640 | // While the layout of types that contain virtual bases is not specified | ||||||
16641 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place | ||||||
16642 | // virtual bases after the derived members. This would make a flexible | ||||||
16643 | // array member declared at the end of an object not adjacent to the end | ||||||
16644 | // of the type. | ||||||
16645 | if (CXXRecord && CXXRecord->getNumVBases() != 0) | ||||||
16646 | Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) | ||||||
16647 | << FD->getDeclName() << Record->getTagKind(); | ||||||
16648 | if (!getLangOpts().C99) | ||||||
16649 | Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) | ||||||
16650 | << FD->getDeclName() << Record->getTagKind(); | ||||||
16651 | |||||||
16652 | // If the element type has a non-trivial destructor, we would not | ||||||
16653 | // implicitly destroy the elements, so disallow it for now. | ||||||
16654 | // | ||||||
16655 | // FIXME: GCC allows this. We should probably either implicitly delete | ||||||
16656 | // the destructor of the containing class, or just allow this. | ||||||
16657 | QualType BaseElem = Context.getBaseElementType(FD->getType()); | ||||||
16658 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { | ||||||
16659 | Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) | ||||||
16660 | << FD->getDeclName() << FD->getType(); | ||||||
16661 | FD->setInvalidDecl(); | ||||||
16662 | EnclosingDecl->setInvalidDecl(); | ||||||
16663 | continue; | ||||||
16664 | } | ||||||
16665 | // Okay, we have a legal flexible array member at the end of the struct. | ||||||
16666 | Record->setHasFlexibleArrayMember(true); | ||||||
16667 | } else { | ||||||
16668 | // In ObjCContainerDecl ivars with incomplete array type are accepted, | ||||||
16669 | // unless they are followed by another ivar. That check is done | ||||||
16670 | // elsewhere, after synthesized ivars are known. | ||||||
16671 | } | ||||||
16672 | } else if (!FDTy->isDependentType() && | ||||||
16673 | RequireCompleteType(FD->getLocation(), FD->getType(), | ||||||
16674 | diag::err_field_incomplete)) { | ||||||
16675 | // Incomplete type | ||||||
16676 | FD->setInvalidDecl(); | ||||||
16677 | EnclosingDecl->setInvalidDecl(); | ||||||
16678 | continue; | ||||||
16679 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { | ||||||
16680 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { | ||||||
16681 | // A type which contains a flexible array member is considered to be a | ||||||
16682 | // flexible array member. | ||||||
16683 | Record->setHasFlexibleArrayMember(true); | ||||||
16684 | if (!Record->isUnion()) { | ||||||
16685 | // If this is a struct/class and this is not the last element, reject | ||||||
16686 | // it. Note that GCC supports variable sized arrays in the middle of | ||||||
16687 | // structures. | ||||||
16688 | if (!IsLastField) | ||||||
16689 | Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) | ||||||
16690 | << FD->getDeclName() << FD->getType(); | ||||||
16691 | else { | ||||||
16692 | // We support flexible arrays at the end of structs in | ||||||
16693 | // other structs as an extension. | ||||||
16694 | Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) | ||||||
16695 | << FD->getDeclName(); | ||||||
16696 | } | ||||||
16697 | } | ||||||
16698 | } | ||||||
16699 | if (isa<ObjCContainerDecl>(EnclosingDecl) && | ||||||
16700 | RequireNonAbstractType(FD->getLocation(), FD->getType(), | ||||||
16701 | diag::err_abstract_type_in_decl, | ||||||
16702 | AbstractIvarType)) { | ||||||
16703 | // Ivars can not have abstract class types | ||||||
16704 | FD->setInvalidDecl(); | ||||||
16705 | } | ||||||
16706 | if (Record && FDTTy->getDecl()->hasObjectMember()) | ||||||
16707 | Record->setHasObjectMember(true); | ||||||
16708 | if (Record && FDTTy->getDecl()->hasVolatileMember()) | ||||||
16709 | Record->setHasVolatileMember(true); | ||||||
16710 | } else if (FDTy->isObjCObjectType()) { | ||||||
16711 | /// A field cannot be an Objective-c object | ||||||
16712 | Diag(FD->getLocation(), diag::err_statically_allocated_object) | ||||||
16713 | << FixItHint::CreateInsertion(FD->getLocation(), "*"); | ||||||
16714 | QualType T = Context.getObjCObjectPointerType(FD->getType()); | ||||||
16715 | FD->setType(T); | ||||||
16716 | } else if (Record && Record->isUnion() && | ||||||
16717 | FD->getType().hasNonTrivialObjCLifetime() && | ||||||
16718 | getSourceManager().isInSystemHeader(FD->getLocation()) && | ||||||
16719 | !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && | ||||||
16720 | (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || | ||||||
16721 | !Context.hasDirectOwnershipQualifier(FD->getType()))) { | ||||||
16722 | // For backward compatibility, fields of C unions declared in system | ||||||
16723 | // headers that have non-trivial ObjC ownership qualifications are marked | ||||||
16724 | // as unavailable unless the qualifier is explicit and __strong. This can | ||||||
16725 | // break ABI compatibility between programs compiled with ARC and MRR, but | ||||||
16726 | // is a better option than rejecting programs using those unions under | ||||||
16727 | // ARC. | ||||||
16728 | FD->addAttr(UnavailableAttr::CreateImplicit( | ||||||
16729 | Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, | ||||||
16730 | FD->getLocation())); | ||||||
16731 | } else if (getLangOpts().ObjC && | ||||||
16732 | getLangOpts().getGC() != LangOptions::NonGC && | ||||||
16733 | Record && !Record->hasObjectMember()) { | ||||||
16734 | if (FD->getType()->isObjCObjectPointerType() || | ||||||
16735 | FD->getType().isObjCGCStrong()) | ||||||
16736 | Record->setHasObjectMember(true); | ||||||
16737 | else if (Context.getAsArrayType(FD->getType())) { | ||||||
16738 | QualType BaseType = Context.getBaseElementType(FD->getType()); | ||||||
16739 | if (BaseType->isRecordType() && | ||||||
16740 | BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) | ||||||
16741 | Record->setHasObjectMember(true); | ||||||
16742 | else if (BaseType->isObjCObjectPointerType() || | ||||||
16743 | BaseType.isObjCGCStrong()) | ||||||
16744 | Record->setHasObjectMember(true); | ||||||
16745 | } | ||||||
16746 | } | ||||||
16747 | |||||||
16748 | if (Record && !getLangOpts().CPlusPlus && | ||||||
16749 | !shouldIgnoreForRecordTriviality(FD)) { | ||||||
16750 | QualType FT = FD->getType(); | ||||||
16751 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { | ||||||
16752 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); | ||||||
16753 | if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||||
16754 | Record->isUnion()) | ||||||
16755 | Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); | ||||||
16756 | } | ||||||
16757 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); | ||||||
16758 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { | ||||||
16759 | Record->setNonTrivialToPrimitiveCopy(true); | ||||||
16760 | if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) | ||||||
16761 | Record->setHasNonTrivialToPrimitiveCopyCUnion(true); | ||||||
16762 | } | ||||||
16763 | if (FT.isDestructedType()) { | ||||||
16764 | Record->setNonTrivialToPrimitiveDestroy(true); | ||||||
16765 | Record->setParamDestroyedInCallee(true); | ||||||
16766 | if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) | ||||||
16767 | Record->setHasNonTrivialToPrimitiveDestructCUnion(true); | ||||||
16768 | } | ||||||
16769 | |||||||
16770 | if (const auto *RT = FT->getAs<RecordType>()) { | ||||||
16771 | if (RT->getDecl()->getArgPassingRestrictions() == | ||||||
16772 | RecordDecl::APK_CanNeverPassInRegs) | ||||||
16773 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | ||||||
16774 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||||
16775 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | ||||||
16776 | } | ||||||
16777 | |||||||
16778 | if (Record && FD->getType().isVolatileQualified()) | ||||||
16779 | Record->setHasVolatileMember(true); | ||||||
16780 | // Keep track of the number of named members. | ||||||
16781 | if (FD->getIdentifier()) | ||||||
16782 | ++NumNamedMembers; | ||||||
16783 | } | ||||||
16784 | |||||||
16785 | // Okay, we successfully defined 'Record'. | ||||||
16786 | if (Record) { | ||||||
16787 | bool Completed = false; | ||||||
16788 | if (CXXRecord) { | ||||||
16789 | if (!CXXRecord->isInvalidDecl()) { | ||||||
16790 | // Set access bits correctly on the directly-declared conversions. | ||||||
16791 | for (CXXRecordDecl::conversion_iterator | ||||||
16792 | I = CXXRecord->conversion_begin(), | ||||||
16793 | E = CXXRecord->conversion_end(); I != E; ++I) | ||||||
16794 | I.setAccess((*I)->getAccess()); | ||||||
16795 | } | ||||||
16796 | |||||||
16797 | if (!CXXRecord->isDependentType()) { | ||||||
16798 | // Add any implicitly-declared members to this class. | ||||||
16799 | AddImplicitlyDeclaredMembersToClass(CXXRecord); | ||||||
16800 | |||||||
16801 | if (!CXXRecord->isInvalidDecl()) { | ||||||
16802 | // If we have virtual base classes, we may end up finding multiple | ||||||
16803 | // final overriders for a given virtual function. Check for this | ||||||
16804 | // problem now. | ||||||
16805 | if (CXXRecord->getNumVBases()) { | ||||||
16806 | CXXFinalOverriderMap FinalOverriders; | ||||||
16807 | CXXRecord->getFinalOverriders(FinalOverriders); | ||||||
16808 | |||||||
16809 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | ||||||
16810 | MEnd = FinalOverriders.end(); | ||||||
16811 | M != MEnd; ++M) { | ||||||
16812 | for (OverridingMethods::iterator SO = M->second.begin(), | ||||||
16813 | SOEnd = M->second.end(); | ||||||
16814 | SO != SOEnd; ++SO) { | ||||||
16815 | assert(SO->second.size() > 0 &&((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16816, __PRETTY_FUNCTION__)) | ||||||
16816 | "Virtual function without overriding functions?")((SO->second.size() > 0 && "Virtual function without overriding functions?" ) ? static_cast<void> (0) : __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16816, __PRETTY_FUNCTION__)); | ||||||
16817 | if (SO->second.size() == 1) | ||||||
16818 | continue; | ||||||
16819 | |||||||
16820 | // C++ [class.virtual]p2: | ||||||
16821 | // In a derived class, if a virtual member function of a base | ||||||
16822 | // class subobject has more than one final overrider the | ||||||
16823 | // program is ill-formed. | ||||||
16824 | Diag(Record->getLocation(), diag::err_multiple_final_overriders) | ||||||
16825 | << (const NamedDecl *)M->first << Record; | ||||||
16826 | Diag(M->first->getLocation(), | ||||||
16827 | diag::note_overridden_virtual_function); | ||||||
16828 | for (OverridingMethods::overriding_iterator | ||||||
16829 | OM = SO->second.begin(), | ||||||
16830 | OMEnd = SO->second.end(); | ||||||
16831 | OM != OMEnd; ++OM) | ||||||
16832 | Diag(OM->Method->getLocation(), diag::note_final_overrider) | ||||||
16833 | << (const NamedDecl *)M->first << OM->Method->getParent(); | ||||||
16834 | |||||||
16835 | Record->setInvalidDecl(); | ||||||
16836 | } | ||||||
16837 | } | ||||||
16838 | CXXRecord->completeDefinition(&FinalOverriders); | ||||||
16839 | Completed = true; | ||||||
16840 | } | ||||||
16841 | } | ||||||
16842 | } | ||||||
16843 | } | ||||||
16844 | |||||||
16845 | if (!Completed) | ||||||
16846 | Record->completeDefinition(); | ||||||
16847 | |||||||
16848 | // Handle attributes before checking the layout. | ||||||
16849 | ProcessDeclAttributeList(S, Record, Attrs); | ||||||
16850 | |||||||
16851 | // We may have deferred checking for a deleted destructor. Check now. | ||||||
16852 | if (CXXRecord) { | ||||||
16853 | auto *Dtor = CXXRecord->getDestructor(); | ||||||
16854 | if (Dtor && Dtor->isImplicit() && | ||||||
16855 | ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { | ||||||
16856 | CXXRecord->setImplicitDestructorIsDeleted(); | ||||||
16857 | SetDeclDeleted(Dtor, CXXRecord->getLocation()); | ||||||
16858 | } | ||||||
16859 | } | ||||||
16860 | |||||||
16861 | if (Record->hasAttrs()) { | ||||||
16862 | CheckAlignasUnderalignment(Record); | ||||||
16863 | |||||||
16864 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) | ||||||
16865 | checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), | ||||||
16866 | IA->getRange(), IA->getBestCase(), | ||||||
16867 | IA->getInheritanceModel()); | ||||||
16868 | } | ||||||
16869 | |||||||
16870 | // Check if the structure/union declaration is a type that can have zero | ||||||
16871 | // size in C. For C this is a language extension, for C++ it may cause | ||||||
16872 | // compatibility problems. | ||||||
16873 | bool CheckForZeroSize; | ||||||
16874 | if (!getLangOpts().CPlusPlus) { | ||||||
16875 | CheckForZeroSize = true; | ||||||
16876 | } else { | ||||||
16877 | // For C++ filter out types that cannot be referenced in C code. | ||||||
16878 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); | ||||||
16879 | CheckForZeroSize = | ||||||
16880 | CXXRecord->getLexicalDeclContext()->isExternCContext() && | ||||||
16881 | !CXXRecord->isDependentType() && | ||||||
16882 | CXXRecord->isCLike(); | ||||||
16883 | } | ||||||
16884 | if (CheckForZeroSize) { | ||||||
16885 | bool ZeroSize = true; | ||||||
16886 | bool IsEmpty = true; | ||||||
16887 | unsigned NonBitFields = 0; | ||||||
16888 | for (RecordDecl::field_iterator I = Record->field_begin(), | ||||||
16889 | E = Record->field_end(); | ||||||
16890 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { | ||||||
16891 | IsEmpty = false; | ||||||
16892 | if (I->isUnnamedBitfield()) { | ||||||
16893 | if (!I->isZeroLengthBitField(Context)) | ||||||
16894 | ZeroSize = false; | ||||||
16895 | } else { | ||||||
16896 | ++NonBitFields; | ||||||
16897 | QualType FieldType = I->getType(); | ||||||
16898 | if (FieldType->isIncompleteType() || | ||||||
16899 | !Context.getTypeSizeInChars(FieldType).isZero()) | ||||||
16900 | ZeroSize = false; | ||||||
16901 | } | ||||||
16902 | } | ||||||
16903 | |||||||
16904 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are | ||||||
16905 | // allowed in C++, but warn if its declaration is inside | ||||||
16906 | // extern "C" block. | ||||||
16907 | if (ZeroSize) { | ||||||
16908 | Diag(RecLoc, getLangOpts().CPlusPlus ? | ||||||
16909 | diag::warn_zero_size_struct_union_in_extern_c : | ||||||
16910 | diag::warn_zero_size_struct_union_compat) | ||||||
16911 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); | ||||||
16912 | } | ||||||
16913 | |||||||
16914 | // Structs without named members are extension in C (C99 6.7.2.1p7), | ||||||
16915 | // but are accepted by GCC. | ||||||
16916 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { | ||||||
16917 | Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : | ||||||
16918 | diag::ext_no_named_members_in_struct_union) | ||||||
16919 | << Record->isUnion(); | ||||||
16920 | } | ||||||
16921 | } | ||||||
16922 | } else { | ||||||
16923 | ObjCIvarDecl **ClsFields = | ||||||
16924 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); | ||||||
16925 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { | ||||||
16926 | ID->setEndOfDefinitionLoc(RBrac); | ||||||
16927 | // Add ivar's to class's DeclContext. | ||||||
16928 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | ||||||
16929 | ClsFields[i]->setLexicalDeclContext(ID); | ||||||
16930 | ID->addDecl(ClsFields[i]); | ||||||
16931 | } | ||||||
16932 | // Must enforce the rule that ivars in the base classes may not be | ||||||
16933 | // duplicates. | ||||||
16934 | if (ID->getSuperClass()) | ||||||
16935 | DiagnoseDuplicateIvars(ID, ID->getSuperClass()); | ||||||
16936 | } else if (ObjCImplementationDecl *IMPDecl = | ||||||
16937 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | ||||||
16938 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16938, __PRETTY_FUNCTION__)); | ||||||
16939 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) | ||||||
16940 | // Ivar declared in @implementation never belongs to the implementation. | ||||||
16941 | // Only it is in implementation's lexical context. | ||||||
16942 | ClsFields[I]->setLexicalDeclContext(IMPDecl); | ||||||
16943 | CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); | ||||||
16944 | IMPDecl->setIvarLBraceLoc(LBrac); | ||||||
16945 | IMPDecl->setIvarRBraceLoc(RBrac); | ||||||
16946 | } else if (ObjCCategoryDecl *CDecl = | ||||||
16947 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | ||||||
16948 | // case of ivars in class extension; all other cases have been | ||||||
16949 | // reported as errors elsewhere. | ||||||
16950 | // FIXME. Class extension does not have a LocEnd field. | ||||||
16951 | // CDecl->setLocEnd(RBrac); | ||||||
16952 | // Add ivar's to class extension's DeclContext. | ||||||
16953 | // Diagnose redeclaration of private ivars. | ||||||
16954 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); | ||||||
16955 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | ||||||
16956 | if (IDecl) { | ||||||
16957 | if (const ObjCIvarDecl *ClsIvar = | ||||||
16958 | IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { | ||||||
16959 | Diag(ClsFields[i]->getLocation(), | ||||||
16960 | diag::err_duplicate_ivar_declaration); | ||||||
16961 | Diag(ClsIvar->getLocation(), diag::note_previous_definition); | ||||||
16962 | continue; | ||||||
16963 | } | ||||||
16964 | for (const auto *Ext : IDecl->known_extensions()) { | ||||||
16965 | if (const ObjCIvarDecl *ClsExtIvar | ||||||
16966 | = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { | ||||||
16967 | Diag(ClsFields[i]->getLocation(), | ||||||
16968 | diag::err_duplicate_ivar_declaration); | ||||||
16969 | Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); | ||||||
16970 | continue; | ||||||
16971 | } | ||||||
16972 | } | ||||||
16973 | } | ||||||
16974 | ClsFields[i]->setLexicalDeclContext(CDecl); | ||||||
16975 | CDecl->addDecl(ClsFields[i]); | ||||||
16976 | } | ||||||
16977 | CDecl->setIvarLBraceLoc(LBrac); | ||||||
16978 | CDecl->setIvarRBraceLoc(RBrac); | ||||||
16979 | } | ||||||
16980 | } | ||||||
16981 | } | ||||||
16982 | |||||||
16983 | /// Determine whether the given integral value is representable within | ||||||
16984 | /// the given type T. | ||||||
16985 | static bool isRepresentableIntegerValue(ASTContext &Context, | ||||||
16986 | llvm::APSInt &Value, | ||||||
16987 | QualType T) { | ||||||
16988 | assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16989, __PRETTY_FUNCTION__)) | ||||||
16989 | "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 16989, __PRETTY_FUNCTION__)); | ||||||
16990 | unsigned BitWidth = Context.getIntWidth(T); | ||||||
16991 | |||||||
16992 | if (Value.isUnsigned() || Value.isNonNegative()) { | ||||||
16993 | if (T->isSignedIntegerOrEnumerationType()) | ||||||
16994 | --BitWidth; | ||||||
16995 | return Value.getActiveBits() <= BitWidth; | ||||||
16996 | } | ||||||
16997 | return Value.getMinSignedBits() <= BitWidth; | ||||||
16998 | } | ||||||
16999 | |||||||
17000 | // Given an integral type, return the next larger integral type | ||||||
17001 | // (or a NULL type of no such type exists). | ||||||
17002 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { | ||||||
17003 | // FIXME: Int128/UInt128 support, which also needs to be introduced into | ||||||
17004 | // enum checking below. | ||||||
17005 | assert((T->isIntegralType(Context) ||(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17006, __PRETTY_FUNCTION__)) | ||||||
17006 | T->isEnumeralType()) && "Integral type required!")(((T->isIntegralType(Context) || T->isEnumeralType()) && "Integral type required!") ? static_cast<void> (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17006, __PRETTY_FUNCTION__)); | ||||||
17007 | const unsigned NumTypes = 4; | ||||||
17008 | QualType SignedIntegralTypes[NumTypes] = { | ||||||
17009 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy | ||||||
17010 | }; | ||||||
17011 | QualType UnsignedIntegralTypes[NumTypes] = { | ||||||
17012 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, | ||||||
17013 | Context.UnsignedLongLongTy | ||||||
17014 | }; | ||||||
17015 | |||||||
17016 | unsigned BitWidth = Context.getTypeSize(T); | ||||||
17017 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes | ||||||
17018 | : UnsignedIntegralTypes; | ||||||
17019 | for (unsigned I = 0; I != NumTypes; ++I) | ||||||
17020 | if (Context.getTypeSize(Types[I]) > BitWidth) | ||||||
17021 | return Types[I]; | ||||||
17022 | |||||||
17023 | return QualType(); | ||||||
17024 | } | ||||||
17025 | |||||||
17026 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, | ||||||
17027 | EnumConstantDecl *LastEnumConst, | ||||||
17028 | SourceLocation IdLoc, | ||||||
17029 | IdentifierInfo *Id, | ||||||
17030 | Expr *Val) { | ||||||
17031 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | ||||||
17032 | llvm::APSInt EnumVal(IntWidth); | ||||||
17033 | QualType EltTy; | ||||||
17034 | |||||||
17035 | if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) | ||||||
17036 | Val = nullptr; | ||||||
17037 | |||||||
17038 | if (Val) | ||||||
17039 | Val = DefaultLvalueConversion(Val).get(); | ||||||
17040 | |||||||
17041 | if (Val) { | ||||||
17042 | if (Enum->isDependentType() || Val->isTypeDependent()) | ||||||
17043 | EltTy = Context.DependentTy; | ||||||
17044 | else { | ||||||
17045 | if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { | ||||||
17046 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the | ||||||
17047 | // constant-expression in the enumerator-definition shall be a converted | ||||||
17048 | // constant expression of the underlying type. | ||||||
17049 | EltTy = Enum->getIntegerType(); | ||||||
17050 | ExprResult Converted = | ||||||
17051 | CheckConvertedConstantExpression(Val, EltTy, EnumVal, | ||||||
17052 | CCEK_Enumerator); | ||||||
17053 | if (Converted.isInvalid()) | ||||||
17054 | Val = nullptr; | ||||||
17055 | else | ||||||
17056 | Val = Converted.get(); | ||||||
17057 | } else if (!Val->isValueDependent() && | ||||||
17058 | !(Val = VerifyIntegerConstantExpression(Val, | ||||||
17059 | &EnumVal).get())) { | ||||||
17060 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. | ||||||
17061 | } else { | ||||||
17062 | if (Enum->isComplete()) { | ||||||
17063 | EltTy = Enum->getIntegerType(); | ||||||
17064 | |||||||
17065 | // In Obj-C and Microsoft mode, require the enumeration value to be | ||||||
17066 | // representable in the underlying type of the enumeration. In C++11, | ||||||
17067 | // we perform a non-narrowing conversion as part of converted constant | ||||||
17068 | // expression checking. | ||||||
17069 | if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | ||||||
17070 | if (Context.getTargetInfo() | ||||||
17071 | .getTriple() | ||||||
17072 | .isWindowsMSVCEnvironment()) { | ||||||
17073 | Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; | ||||||
17074 | } else { | ||||||
17075 | Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; | ||||||
17076 | } | ||||||
17077 | } | ||||||
17078 | |||||||
17079 | // Cast to the underlying type. | ||||||
17080 | Val = ImpCastExprToType(Val, EltTy, | ||||||
17081 | EltTy->isBooleanType() ? CK_IntegralToBoolean | ||||||
17082 | : CK_IntegralCast) | ||||||
17083 | .get(); | ||||||
17084 | } else if (getLangOpts().CPlusPlus) { | ||||||
17085 | // C++11 [dcl.enum]p5: | ||||||
17086 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17087 | // is the type of its initializing value: | ||||||
17088 | // - If an initializer is specified for an enumerator, the | ||||||
17089 | // initializing value has the same type as the expression. | ||||||
17090 | EltTy = Val->getType(); | ||||||
17091 | } else { | ||||||
17092 | // C99 6.7.2.2p2: | ||||||
17093 | // The expression that defines the value of an enumeration constant | ||||||
17094 | // shall be an integer constant expression that has a value | ||||||
17095 | // representable as an int. | ||||||
17096 | |||||||
17097 | // Complain if the value is not representable in an int. | ||||||
17098 | if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) | ||||||
17099 | Diag(IdLoc, diag::ext_enum_value_not_int) | ||||||
17100 | << EnumVal.toString(10) << Val->getSourceRange() | ||||||
17101 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); | ||||||
17102 | else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { | ||||||
17103 | // Force the type of the expression to 'int'. | ||||||
17104 | Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); | ||||||
17105 | } | ||||||
17106 | EltTy = Val->getType(); | ||||||
17107 | } | ||||||
17108 | } | ||||||
17109 | } | ||||||
17110 | } | ||||||
17111 | |||||||
17112 | if (!Val) { | ||||||
17113 | if (Enum->isDependentType()) | ||||||
17114 | EltTy = Context.DependentTy; | ||||||
17115 | else if (!LastEnumConst) { | ||||||
17116 | // C++0x [dcl.enum]p5: | ||||||
17117 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17118 | // is the type of its initializing value: | ||||||
17119 | // - If no initializer is specified for the first enumerator, the | ||||||
17120 | // initializing value has an unspecified integral type. | ||||||
17121 | // | ||||||
17122 | // GCC uses 'int' for its unspecified integral type, as does | ||||||
17123 | // C99 6.7.2.2p3. | ||||||
17124 | if (Enum->isFixed()) { | ||||||
17125 | EltTy = Enum->getIntegerType(); | ||||||
17126 | } | ||||||
17127 | else { | ||||||
17128 | EltTy = Context.IntTy; | ||||||
17129 | } | ||||||
17130 | } else { | ||||||
17131 | // Assign the last value + 1. | ||||||
17132 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17133 | ++EnumVal; | ||||||
17134 | EltTy = LastEnumConst->getType(); | ||||||
17135 | |||||||
17136 | // Check for overflow on increment. | ||||||
17137 | if (EnumVal < LastEnumConst->getInitVal()) { | ||||||
17138 | // C++0x [dcl.enum]p5: | ||||||
17139 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17140 | // is the type of its initializing value: | ||||||
17141 | // | ||||||
17142 | // - Otherwise the type of the initializing value is the same as | ||||||
17143 | // the type of the initializing value of the preceding enumerator | ||||||
17144 | // unless the incremented value is not representable in that type, | ||||||
17145 | // in which case the type is an unspecified integral type | ||||||
17146 | // sufficient to contain the incremented value. If no such type | ||||||
17147 | // exists, the program is ill-formed. | ||||||
17148 | QualType T = getNextLargerIntegralType(Context, EltTy); | ||||||
17149 | if (T.isNull() || Enum->isFixed()) { | ||||||
17150 | // There is no integral type larger enough to represent this | ||||||
17151 | // value. Complain, then allow the value to wrap around. | ||||||
17152 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17153 | EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); | ||||||
17154 | ++EnumVal; | ||||||
17155 | if (Enum->isFixed()) | ||||||
17156 | // When the underlying type is fixed, this is ill-formed. | ||||||
17157 | Diag(IdLoc, diag::err_enumerator_wrapped) | ||||||
17158 | << EnumVal.toString(10) | ||||||
17159 | << EltTy; | ||||||
17160 | else | ||||||
17161 | Diag(IdLoc, diag::ext_enumerator_increment_too_large) | ||||||
17162 | << EnumVal.toString(10); | ||||||
17163 | } else { | ||||||
17164 | EltTy = T; | ||||||
17165 | } | ||||||
17166 | |||||||
17167 | // Retrieve the last enumerator's value, extent that type to the | ||||||
17168 | // type that is supposed to be large enough to represent the incremented | ||||||
17169 | // value, then increment. | ||||||
17170 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17171 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | ||||||
17172 | EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); | ||||||
17173 | ++EnumVal; | ||||||
17174 | |||||||
17175 | // If we're not in C++, diagnose the overflow of enumerator values, | ||||||
17176 | // which in C99 means that the enumerator value is not representable in | ||||||
17177 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that | ||||||
17178 | // permits enumerator values that are representable in some larger | ||||||
17179 | // integral type. | ||||||
17180 | if (!getLangOpts().CPlusPlus && !T.isNull()) | ||||||
17181 | Diag(IdLoc, diag::warn_enum_value_overflow); | ||||||
17182 | } else if (!getLangOpts().CPlusPlus && | ||||||
17183 | !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | ||||||
17184 | // Enforce C99 6.7.2.2p2 even when we compute the next value. | ||||||
17185 | Diag(IdLoc, diag::ext_enum_value_not_int) | ||||||
17186 | << EnumVal.toString(10) << 1; | ||||||
17187 | } | ||||||
17188 | } | ||||||
17189 | } | ||||||
17190 | |||||||
17191 | if (!EltTy->isDependentType()) { | ||||||
17192 | // Make the enumerator value match the signedness and size of the | ||||||
17193 | // enumerator's type. | ||||||
17194 | EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); | ||||||
17195 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | ||||||
17196 | } | ||||||
17197 | |||||||
17198 | return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, | ||||||
17199 | Val, EnumVal); | ||||||
17200 | } | ||||||
17201 | |||||||
17202 | Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, | ||||||
17203 | SourceLocation IILoc) { | ||||||
17204 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || | ||||||
17205 | !getLangOpts().CPlusPlus) | ||||||
17206 | return SkipBodyInfo(); | ||||||
17207 | |||||||
17208 | // We have an anonymous enum definition. Look up the first enumerator to | ||||||
17209 | // determine if we should merge the definition with an existing one and | ||||||
17210 | // skip the body. | ||||||
17211 | NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, | ||||||
17212 | forRedeclarationInCurContext()); | ||||||
17213 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); | ||||||
17214 | if (!PrevECD) | ||||||
17215 | return SkipBodyInfo(); | ||||||
17216 | |||||||
17217 | EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); | ||||||
17218 | NamedDecl *Hidden; | ||||||
17219 | if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { | ||||||
17220 | SkipBodyInfo Skip; | ||||||
17221 | Skip.Previous = Hidden; | ||||||
17222 | return Skip; | ||||||
17223 | } | ||||||
17224 | |||||||
17225 | return SkipBodyInfo(); | ||||||
17226 | } | ||||||
17227 | |||||||
17228 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, | ||||||
17229 | SourceLocation IdLoc, IdentifierInfo *Id, | ||||||
17230 | const ParsedAttributesView &Attrs, | ||||||
17231 | SourceLocation EqualLoc, Expr *Val) { | ||||||
17232 | EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); | ||||||
17233 | EnumConstantDecl *LastEnumConst = | ||||||
17234 | cast_or_null<EnumConstantDecl>(lastEnumConst); | ||||||
17235 | |||||||
17236 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||||
17237 | // we find one that is. | ||||||
17238 | S = getNonFieldDeclScope(S); | ||||||
17239 | |||||||
17240 | // Verify that there isn't already something declared with this name in this | ||||||
17241 | // scope. | ||||||
17242 | LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); | ||||||
17243 | LookupName(R, S); | ||||||
17244 | NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); | ||||||
17245 | |||||||
17246 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||||
17247 | // Maybe we will complain about the shadowed template parameter. | ||||||
17248 | DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); | ||||||
17249 | // Just pretend that we didn't see the previous declaration. | ||||||
17250 | PrevDecl = nullptr; | ||||||
17251 | } | ||||||
17252 | |||||||
17253 | // C++ [class.mem]p15: | ||||||
17254 | // If T is the name of a class, then each of the following shall have a name | ||||||
17255 | // different from T: | ||||||
17256 | // - every enumerator of every member of class T that is an unscoped | ||||||
17257 | // enumerated type | ||||||
17258 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) | ||||||
17259 | DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), | ||||||
17260 | DeclarationNameInfo(Id, IdLoc)); | ||||||
17261 | |||||||
17262 | EnumConstantDecl *New = | ||||||
17263 | CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); | ||||||
17264 | if (!New) | ||||||
17265 | return nullptr; | ||||||
17266 | |||||||
17267 | if (PrevDecl) { | ||||||
17268 | if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { | ||||||
17269 | // Check for other kinds of shadowing not already handled. | ||||||
17270 | CheckShadow(New, PrevDecl, R); | ||||||
17271 | } | ||||||
17272 | |||||||
17273 | // When in C++, we may get a TagDecl with the same name; in this case the | ||||||
17274 | // enum constant will 'hide' the tag. | ||||||
17275 | assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17276, __PRETTY_FUNCTION__)) | ||||||
17276 | "Received TagDecl when not in C++!")(((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!") ? static_cast<void> (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17276, __PRETTY_FUNCTION__)); | ||||||
17277 | if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { | ||||||
17278 | if (isa<EnumConstantDecl>(PrevDecl)) | ||||||
17279 | Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; | ||||||
17280 | else | ||||||
17281 | Diag(IdLoc, diag::err_redefinition) << Id; | ||||||
17282 | notePreviousDefinition(PrevDecl, IdLoc); | ||||||
17283 | return nullptr; | ||||||
17284 | } | ||||||
17285 | } | ||||||
17286 | |||||||
17287 | // Process attributes. | ||||||
17288 | ProcessDeclAttributeList(S, New, Attrs); | ||||||
17289 | AddPragmaAttributes(S, New); | ||||||
17290 | |||||||
17291 | // Register this decl in the current scope stack. | ||||||
17292 | New->setAccess(TheEnumDecl->getAccess()); | ||||||
17293 | PushOnScopeChains(New, S); | ||||||
17294 | |||||||
17295 | ActOnDocumentableDecl(New); | ||||||
17296 | |||||||
17297 | return New; | ||||||
17298 | } | ||||||
17299 | |||||||
17300 | // Returns true when the enum initial expression does not trigger the | ||||||
17301 | // duplicate enum warning. A few common cases are exempted as follows: | ||||||
17302 | // Element2 = Element1 | ||||||
17303 | // Element2 = Element1 + 1 | ||||||
17304 | // Element2 = Element1 - 1 | ||||||
17305 | // Where Element2 and Element1 are from the same enum. | ||||||
17306 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { | ||||||
17307 | Expr *InitExpr = ECD->getInitExpr(); | ||||||
17308 | if (!InitExpr) | ||||||
17309 | return true; | ||||||
17310 | InitExpr = InitExpr->IgnoreImpCasts(); | ||||||
17311 | |||||||
17312 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { | ||||||
17313 | if (!BO->isAdditiveOp()) | ||||||
17314 | return true; | ||||||
17315 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); | ||||||
17316 | if (!IL) | ||||||
17317 | return true; | ||||||
17318 | if (IL->getValue() != 1) | ||||||
17319 | return true; | ||||||
17320 | |||||||
17321 | InitExpr = BO->getLHS(); | ||||||
17322 | } | ||||||
17323 | |||||||
17324 | // This checks if the elements are from the same enum. | ||||||
17325 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); | ||||||
17326 | if (!DRE) | ||||||
17327 | return true; | ||||||
17328 | |||||||
17329 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); | ||||||
17330 | if (!EnumConstant) | ||||||
17331 | return true; | ||||||
17332 | |||||||
17333 | if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != | ||||||
17334 | Enum) | ||||||
17335 | return true; | ||||||
17336 | |||||||
17337 | return false; | ||||||
17338 | } | ||||||
17339 | |||||||
17340 | // Emits a warning when an element is implicitly set a value that | ||||||
17341 | // a previous element has already been set to. | ||||||
17342 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, | ||||||
17343 | EnumDecl *Enum, QualType EnumType) { | ||||||
17344 | // Avoid anonymous enums | ||||||
17345 | if (!Enum->getIdentifier()) | ||||||
17346 | return; | ||||||
17347 | |||||||
17348 | // Only check for small enums. | ||||||
17349 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) | ||||||
17350 | return; | ||||||
17351 | |||||||
17352 | if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) | ||||||
17353 | return; | ||||||
17354 | |||||||
17355 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; | ||||||
17356 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; | ||||||
17357 | |||||||
17358 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; | ||||||
17359 | typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; | ||||||
17360 | |||||||
17361 | // Use int64_t as a key to avoid needing special handling for DenseMap keys. | ||||||
17362 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { | ||||||
17363 | llvm::APSInt Val = D->getInitVal(); | ||||||
17364 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); | ||||||
17365 | }; | ||||||
17366 | |||||||
17367 | DuplicatesVector DupVector; | ||||||
17368 | ValueToVectorMap EnumMap; | ||||||
17369 | |||||||
17370 | // Populate the EnumMap with all values represented by enum constants without | ||||||
17371 | // an initializer. | ||||||
17372 | for (auto *Element : Elements) { | ||||||
17373 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); | ||||||
17374 | |||||||
17375 | // Null EnumConstantDecl means a previous diagnostic has been emitted for | ||||||
17376 | // this constant. Skip this enum since it may be ill-formed. | ||||||
17377 | if (!ECD) { | ||||||
17378 | return; | ||||||
17379 | } | ||||||
17380 | |||||||
17381 | // Constants with initalizers are handled in the next loop. | ||||||
17382 | if (ECD->getInitExpr()) | ||||||
17383 | continue; | ||||||
17384 | |||||||
17385 | // Duplicate values are handled in the next loop. | ||||||
17386 | EnumMap.insert({EnumConstantToKey(ECD), ECD}); | ||||||
17387 | } | ||||||
17388 | |||||||
17389 | if (EnumMap.size() == 0) | ||||||
17390 | return; | ||||||
17391 | |||||||
17392 | // Create vectors for any values that has duplicates. | ||||||
17393 | for (auto *Element : Elements) { | ||||||
17394 | // The last loop returned if any constant was null. | ||||||
17395 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); | ||||||
17396 | if (!ValidDuplicateEnum(ECD, Enum)) | ||||||
17397 | continue; | ||||||
17398 | |||||||
17399 | auto Iter = EnumMap.find(EnumConstantToKey(ECD)); | ||||||
17400 | if (Iter == EnumMap.end()) | ||||||
17401 | continue; | ||||||
17402 | |||||||
17403 | DeclOrVector& Entry = Iter->second; | ||||||
17404 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { | ||||||
17405 | // Ensure constants are different. | ||||||
17406 | if (D == ECD) | ||||||
17407 | continue; | ||||||
17408 | |||||||
17409 | // Create new vector and push values onto it. | ||||||
17410 | auto Vec = std::make_unique<ECDVector>(); | ||||||
17411 | Vec->push_back(D); | ||||||
17412 | Vec->push_back(ECD); | ||||||
17413 | |||||||
17414 | // Update entry to point to the duplicates vector. | ||||||
17415 | Entry = Vec.get(); | ||||||
17416 | |||||||
17417 | // Store the vector somewhere we can consult later for quick emission of | ||||||
17418 | // diagnostics. | ||||||
17419 | DupVector.emplace_back(std::move(Vec)); | ||||||
17420 | continue; | ||||||
17421 | } | ||||||
17422 | |||||||
17423 | ECDVector *Vec = Entry.get<ECDVector*>(); | ||||||
17424 | // Make sure constants are not added more than once. | ||||||
17425 | if (*Vec->begin() == ECD) | ||||||
17426 | continue; | ||||||
17427 | |||||||
17428 | Vec->push_back(ECD); | ||||||
17429 | } | ||||||
17430 | |||||||
17431 | // Emit diagnostics. | ||||||
17432 | for (const auto &Vec : DupVector) { | ||||||
17433 | assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((Vec->size() > 1 && "ECDVector should have at least 2 elements." ) ? static_cast<void> (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17433, __PRETTY_FUNCTION__)); | ||||||
17434 | |||||||
17435 | // Emit warning for one enum constant. | ||||||
17436 | auto *FirstECD = Vec->front(); | ||||||
17437 | S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) | ||||||
17438 | << FirstECD << FirstECD->getInitVal().toString(10) | ||||||
17439 | << FirstECD->getSourceRange(); | ||||||
17440 | |||||||
17441 | // Emit one note for each of the remaining enum constants with | ||||||
17442 | // the same value. | ||||||
17443 | for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) | ||||||
17444 | S.Diag(ECD->getLocation(), diag::note_duplicate_element) | ||||||
17445 | << ECD << ECD->getInitVal().toString(10) | ||||||
17446 | << ECD->getSourceRange(); | ||||||
17447 | } | ||||||
17448 | } | ||||||
17449 | |||||||
17450 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, | ||||||
17451 | bool AllowMask) const { | ||||||
17452 | assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((ED->isClosedFlag() && "looking for value in non-flag or open enum" ) ? static_cast<void> (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17452, __PRETTY_FUNCTION__)); | ||||||
17453 | assert(ED->isCompleteDefinition() && "expected enum definition")((ED->isCompleteDefinition() && "expected enum definition" ) ? static_cast<void> (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17453, __PRETTY_FUNCTION__)); | ||||||
17454 | |||||||
17455 | auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); | ||||||
17456 | llvm::APInt &FlagBits = R.first->second; | ||||||
17457 | |||||||
17458 | if (R.second) { | ||||||
17459 | for (auto *E : ED->enumerators()) { | ||||||
17460 | const auto &EVal = E->getInitVal(); | ||||||
17461 | // Only single-bit enumerators introduce new flag values. | ||||||
17462 | if (EVal.isPowerOf2()) | ||||||
17463 | FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; | ||||||
17464 | } | ||||||
17465 | } | ||||||
17466 | |||||||
17467 | // A value is in a flag enum if either its bits are a subset of the enum's | ||||||
17468 | // flag bits (the first condition) or we are allowing masks and the same is | ||||||
17469 | // true of its complement (the second condition). When masks are allowed, we | ||||||
17470 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. | ||||||
17471 | // | ||||||
17472 | // While it's true that any value could be used as a mask, the assumption is | ||||||
17473 | // that a mask will have all of the insignificant bits set. Anything else is | ||||||
17474 | // likely a logic error. | ||||||
17475 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); | ||||||
17476 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); | ||||||
17477 | } | ||||||
17478 | |||||||
17479 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, | ||||||
17480 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, | ||||||
17481 | const ParsedAttributesView &Attrs) { | ||||||
17482 | EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); | ||||||
17483 | QualType EnumType = Context.getTypeDeclType(Enum); | ||||||
17484 | |||||||
17485 | ProcessDeclAttributeList(S, Enum, Attrs); | ||||||
17486 | |||||||
17487 | if (Enum->isDependentType()) { | ||||||
17488 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | ||||||
17489 | EnumConstantDecl *ECD = | ||||||
17490 | cast_or_null<EnumConstantDecl>(Elements[i]); | ||||||
17491 | if (!ECD) continue; | ||||||
17492 | |||||||
17493 | ECD->setType(EnumType); | ||||||
17494 | } | ||||||
17495 | |||||||
17496 | Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); | ||||||
17497 | return; | ||||||
17498 | } | ||||||
17499 | |||||||
17500 | // TODO: If the result value doesn't fit in an int, it must be a long or long | ||||||
17501 | // long value. ISO C does not support this, but GCC does as an extension, | ||||||
17502 | // emit a warning. | ||||||
17503 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | ||||||
17504 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); | ||||||
17505 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); | ||||||
17506 | |||||||
17507 | // Verify that all the values are okay, compute the size of the values, and | ||||||
17508 | // reverse the list. | ||||||
17509 | unsigned NumNegativeBits = 0; | ||||||
17510 | unsigned NumPositiveBits = 0; | ||||||
17511 | |||||||
17512 | // Keep track of whether all elements have type int. | ||||||
17513 | bool AllElementsInt = true; | ||||||
17514 | |||||||
17515 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | ||||||
17516 | EnumConstantDecl *ECD = | ||||||
17517 | cast_or_null<EnumConstantDecl>(Elements[i]); | ||||||
17518 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
17519 | |||||||
17520 | const llvm::APSInt &InitVal = ECD->getInitVal(); | ||||||
17521 | |||||||
17522 | // Keep track of the size of positive and negative values. | ||||||
17523 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) | ||||||
17524 | NumPositiveBits = std::max(NumPositiveBits, | ||||||
17525 | (unsigned)InitVal.getActiveBits()); | ||||||
17526 | else | ||||||
17527 | NumNegativeBits = std::max(NumNegativeBits, | ||||||
17528 | (unsigned)InitVal.getMinSignedBits()); | ||||||
17529 | |||||||
17530 | // Keep track of whether every enum element has type int (very common). | ||||||
17531 | if (AllElementsInt) | ||||||
17532 | AllElementsInt = ECD->getType() == Context.IntTy; | ||||||
17533 | } | ||||||
17534 | |||||||
17535 | // Figure out the type that should be used for this enum. | ||||||
17536 | QualType BestType; | ||||||
17537 | unsigned BestWidth; | ||||||
17538 | |||||||
17539 | // C++0x N3000 [conv.prom]p3: | ||||||
17540 | // An rvalue of an unscoped enumeration type whose underlying | ||||||
17541 | // type is not fixed can be converted to an rvalue of the first | ||||||
17542 | // of the following types that can represent all the values of | ||||||
17543 | // the enumeration: int, unsigned int, long int, unsigned long | ||||||
17544 | // int, long long int, or unsigned long long int. | ||||||
17545 | // C99 6.4.4.3p2: | ||||||
17546 | // An identifier declared as an enumeration constant has type int. | ||||||
17547 | // The C99 rule is modified by a gcc extension | ||||||
17548 | QualType BestPromotionType; | ||||||
17549 | |||||||
17550 | bool Packed = Enum->hasAttr<PackedAttr>(); | ||||||
17551 | // -fshort-enums is the equivalent to specifying the packed attribute on all | ||||||
17552 | // enum definitions. | ||||||
17553 | if (LangOpts.ShortEnums) | ||||||
17554 | Packed = true; | ||||||
17555 | |||||||
17556 | // If the enum already has a type because it is fixed or dictated by the | ||||||
17557 | // target, promote that type instead of analyzing the enumerators. | ||||||
17558 | if (Enum->isComplete()) { | ||||||
17559 | BestType = Enum->getIntegerType(); | ||||||
17560 | if (BestType->isPromotableIntegerType()) | ||||||
17561 | BestPromotionType = Context.getPromotedIntegerType(BestType); | ||||||
17562 | else | ||||||
17563 | BestPromotionType = BestType; | ||||||
17564 | |||||||
17565 | BestWidth = Context.getIntWidth(BestType); | ||||||
17566 | } | ||||||
17567 | else if (NumNegativeBits) { | ||||||
17568 | // If there is a negative value, figure out the smallest integer type (of | ||||||
17569 | // int/long/longlong) that fits. | ||||||
17570 | // If it's packed, check also if it fits a char or a short. | ||||||
17571 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { | ||||||
17572 | BestType = Context.SignedCharTy; | ||||||
17573 | BestWidth = CharWidth; | ||||||
17574 | } else if (Packed && NumNegativeBits <= ShortWidth && | ||||||
17575 | NumPositiveBits < ShortWidth) { | ||||||
17576 | BestType = Context.ShortTy; | ||||||
17577 | BestWidth = ShortWidth; | ||||||
17578 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { | ||||||
17579 | BestType = Context.IntTy; | ||||||
17580 | BestWidth = IntWidth; | ||||||
17581 | } else { | ||||||
17582 | BestWidth = Context.getTargetInfo().getLongWidth(); | ||||||
17583 | |||||||
17584 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { | ||||||
17585 | BestType = Context.LongTy; | ||||||
17586 | } else { | ||||||
17587 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | ||||||
17588 | |||||||
17589 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) | ||||||
17590 | Diag(Enum->getLocation(), diag::ext_enum_too_large); | ||||||
17591 | BestType = Context.LongLongTy; | ||||||
17592 | } | ||||||
17593 | } | ||||||
17594 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); | ||||||
17595 | } else { | ||||||
17596 | // If there is no negative value, figure out the smallest type that fits | ||||||
17597 | // all of the enumerator values. | ||||||
17598 | // If it's packed, check also if it fits a char or a short. | ||||||
17599 | if (Packed && NumPositiveBits <= CharWidth) { | ||||||
17600 | BestType = Context.UnsignedCharTy; | ||||||
17601 | BestPromotionType = Context.IntTy; | ||||||
17602 | BestWidth = CharWidth; | ||||||
17603 | } else if (Packed && NumPositiveBits <= ShortWidth) { | ||||||
17604 | BestType = Context.UnsignedShortTy; | ||||||
17605 | BestPromotionType = Context.IntTy; | ||||||
17606 | BestWidth = ShortWidth; | ||||||
17607 | } else if (NumPositiveBits <= IntWidth) { | ||||||
17608 | BestType = Context.UnsignedIntTy; | ||||||
17609 | BestWidth = IntWidth; | ||||||
17610 | BestPromotionType | ||||||
17611 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
17612 | ? Context.UnsignedIntTy : Context.IntTy; | ||||||
17613 | } else if (NumPositiveBits <= | ||||||
17614 | (BestWidth = Context.getTargetInfo().getLongWidth())) { | ||||||
17615 | BestType = Context.UnsignedLongTy; | ||||||
17616 | BestPromotionType | ||||||
17617 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
17618 | ? Context.UnsignedLongTy : Context.LongTy; | ||||||
17619 | } else { | ||||||
17620 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | ||||||
17621 | assert(NumPositiveBits <= BestWidth &&((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17622, __PRETTY_FUNCTION__)) | ||||||
17622 | "How could an initializer get larger than ULL?")((NumPositiveBits <= BestWidth && "How could an initializer get larger than ULL?" ) ? static_cast<void> (0) : __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/lib/Sema/SemaDecl.cpp" , 17622, __PRETTY_FUNCTION__)); | ||||||
17623 | BestType = Context.UnsignedLongLongTy; | ||||||
17624 | BestPromotionType | ||||||
17625 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
17626 | ? Context.UnsignedLongLongTy : Context.LongLongTy; | ||||||
17627 | } | ||||||
17628 | } | ||||||
17629 | |||||||
17630 | // Loop over all of the enumerator constants, changing their types to match | ||||||
17631 | // the type of the enum if needed. | ||||||
17632 | for (auto *D : Elements) { | ||||||
17633 | auto *ECD = cast_or_null<EnumConstantDecl>(D); | ||||||
17634 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
17635 | |||||||
17636 | // Standard C says the enumerators have int type, but we allow, as an | ||||||
17637 | // extension, the enumerators to be larger than int size. If each | ||||||
17638 | // enumerator value fits in an int, type it as an int, otherwise type it the | ||||||
17639 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" | ||||||
17640 | // that X has type 'int', not 'unsigned'. | ||||||
17641 | |||||||
17642 | // Determine whether the value fits into an int. | ||||||
17643 | llvm::APSInt InitVal = ECD->getInitVal(); | ||||||
17644 | |||||||
17645 | // If it fits into an integer type, force it. Otherwise force it to match | ||||||
17646 | // the enum decl type. | ||||||
17647 | QualType NewTy; | ||||||
17648 | unsigned NewWidth; | ||||||
17649 | bool NewSign; | ||||||
17650 | if (!getLangOpts().CPlusPlus && | ||||||
17651 | !Enum->isFixed() && | ||||||
17652 | isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { | ||||||
17653 | NewTy = Context.IntTy; | ||||||
17654 | NewWidth = IntWidth; | ||||||
17655 | NewSign = true; | ||||||
17656 | } else if (ECD->getType() == BestType) { | ||||||
17657 | // Already the right type! | ||||||
17658 | if (getLangOpts().CPlusPlus) | ||||||
17659 | // C++ [dcl.enum]p4: Following the closing brace of an | ||||||
17660 | // enum-specifier, each enumerator has the type of its | ||||||
17661 | // enumeration. | ||||||
17662 | ECD->setType(EnumType); | ||||||
17663 | continue; | ||||||
17664 | } else { | ||||||
17665 | NewTy = BestType; | ||||||
17666 | NewWidth = BestWidth; | ||||||
17667 | NewSign = BestType->isSignedIntegerOrEnumerationType(); | ||||||
17668 | } | ||||||
17669 | |||||||
17670 | // Adjust the APSInt value. | ||||||
17671 | InitVal = InitVal.extOrTrunc(NewWidth); | ||||||
17672 | InitVal.setIsSigned(NewSign); | ||||||
17673 | ECD->setInitVal(InitVal); | ||||||
17674 | |||||||
17675 | // Adjust the Expr initializer and type. | ||||||
17676 | if (ECD->getInitExpr() && | ||||||
17677 | !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) | ||||||
17678 | ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, | ||||||
17679 | CK_IntegralCast, | ||||||
17680 | ECD->getInitExpr(), | ||||||
17681 | /*base paths*/ nullptr, | ||||||
17682 | VK_RValue)); | ||||||
17683 | if (getLangOpts().CPlusPlus) | ||||||
17684 | // C++ [dcl.enum]p4: Following the closing brace of an | ||||||
17685 | // enum-specifier, each enumerator has the type of its | ||||||
17686 | // enumeration. | ||||||
17687 | ECD->setType(EnumType); | ||||||
17688 | else | ||||||
17689 | ECD->setType(NewTy); | ||||||
17690 | } | ||||||
17691 | |||||||
17692 | Enum->completeDefinition(BestType, BestPromotionType, | ||||||
17693 | NumPositiveBits, NumNegativeBits); | ||||||
17694 | |||||||
17695 | CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); | ||||||
17696 | |||||||
17697 | if (Enum->isClosedFlag()) { | ||||||
17698 | for (Decl *D : Elements) { | ||||||
17699 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); | ||||||
17700 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
17701 | |||||||
17702 | llvm::APSInt InitVal = ECD->getInitVal(); | ||||||
17703 | if (InitVal != 0 && !InitVal.isPowerOf2() && | ||||||
17704 | !IsValueInFlagEnum(Enum, InitVal, true)) | ||||||
17705 | Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) | ||||||
17706 | << ECD << Enum; | ||||||
17707 | } | ||||||
17708 | } | ||||||
17709 | |||||||
17710 | // Now that the enum type is defined, ensure it's not been underaligned. | ||||||
17711 | if (Enum->hasAttrs()) | ||||||
17712 | CheckAlignasUnderalignment(Enum); | ||||||
17713 | } | ||||||
17714 | |||||||
17715 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, | ||||||
17716 | SourceLocation StartLoc, | ||||||
17717 | SourceLocation EndLoc) { | ||||||
17718 | StringLiteral *AsmString = cast<StringLiteral>(expr); | ||||||
17719 | |||||||
17720 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, | ||||||
17721 | AsmString, StartLoc, | ||||||
17722 | EndLoc); | ||||||
17723 | CurContext->addDecl(New); | ||||||
17724 | return New; | ||||||
17725 | } | ||||||
17726 | |||||||
17727 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, | ||||||
17728 | IdentifierInfo* AliasName, | ||||||
17729 | SourceLocation PragmaLoc, | ||||||
17730 | SourceLocation NameLoc, | ||||||
17731 | SourceLocation AliasNameLoc) { | ||||||
17732 | NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, | ||||||
17733 | LookupOrdinaryName); | ||||||
17734 | AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), | ||||||
17735 | AttributeCommonInfo::AS_Pragma); | ||||||
17736 | AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( | ||||||
17737 | Context, AliasName->getName(), /*LiteralLabel=*/true, Info); | ||||||
17738 | |||||||
17739 | // If a declaration that: | ||||||
17740 | // 1) declares a function or a variable | ||||||
17741 | // 2) has external linkage | ||||||
17742 | // already exists, add a label attribute to it. | ||||||
17743 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | ||||||
17744 | if (isDeclExternC(PrevDecl)) | ||||||
17745 | PrevDecl->addAttr(Attr); | ||||||
17746 | else | ||||||
17747 | Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
17748 | << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; | ||||||
17749 | // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. | ||||||
17750 | } else | ||||||
17751 | (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); | ||||||
17752 | } | ||||||
17753 | |||||||
17754 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, | ||||||
17755 | SourceLocation PragmaLoc, | ||||||
17756 | SourceLocation NameLoc) { | ||||||
17757 | Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); | ||||||
17758 | |||||||
17759 | if (PrevDecl) { | ||||||
17760 | PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); | ||||||
17761 | } else { | ||||||
17762 | (void)WeakUndeclaredIdentifiers.insert( | ||||||
17763 | std::pair<IdentifierInfo*,WeakInfo> | ||||||
17764 | (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); | ||||||
17765 | } | ||||||
17766 | } | ||||||
17767 | |||||||
17768 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, | ||||||
17769 | IdentifierInfo* AliasName, | ||||||
17770 | SourceLocation PragmaLoc, | ||||||
17771 | SourceLocation NameLoc, | ||||||
17772 | SourceLocation AliasNameLoc) { | ||||||
17773 | Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, | ||||||
17774 | LookupOrdinaryName); | ||||||
17775 | WeakInfo W = WeakInfo(Name, NameLoc); | ||||||
17776 | |||||||
17777 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | ||||||
17778 | if (!PrevDecl->hasAttr<AliasAttr>()) | ||||||
17779 | if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) | ||||||
17780 | DeclApplyPragmaWeak(TUScope, ND, W); | ||||||
17781 | } else { | ||||||
17782 | (void)WeakUndeclaredIdentifiers.insert( | ||||||
17783 | std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); | ||||||
17784 | } | ||||||
17785 | } | ||||||
17786 | |||||||
17787 | Decl *Sema::getObjCDeclContext() const { | ||||||
17788 | return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); | ||||||
17789 | } | ||||||
17790 | |||||||
17791 | Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) { | ||||||
17792 | // Templates are emitted when they're instantiated. | ||||||
17793 | if (FD->isDependentContext()) | ||||||
17794 | return FunctionEmissionStatus::TemplateDiscarded; | ||||||
17795 | |||||||
17796 | FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; | ||||||
17797 | if (LangOpts.OpenMPIsDevice) { | ||||||
17798 | Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = | ||||||
17799 | OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); | ||||||
17800 | if (DevTy.hasValue()) { | ||||||
17801 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) | ||||||
17802 | OMPES = FunctionEmissionStatus::OMPDiscarded; | ||||||
17803 | else if (DeviceKnownEmittedFns.count(FD) > 0) | ||||||
17804 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
17805 | } | ||||||
17806 | } else if (LangOpts.OpenMP) { | ||||||
17807 | // In OpenMP 4.5 all the functions are host functions. | ||||||
17808 | if (LangOpts.OpenMP <= 45) { | ||||||
17809 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
17810 | } else { | ||||||
17811 | Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = | ||||||
17812 | OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); | ||||||
17813 | // In OpenMP 5.0 or above, DevTy may be changed later by | ||||||
17814 | // #pragma omp declare target to(*) device_type(*). Therefore DevTy | ||||||
17815 | // having no value does not imply host. The emission status will be | ||||||
17816 | // checked again at the end of compilation unit. | ||||||
17817 | if (DevTy.hasValue()) { | ||||||
17818 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { | ||||||
17819 | OMPES = FunctionEmissionStatus::OMPDiscarded; | ||||||
17820 | } else if (DeviceKnownEmittedFns.count(FD) > 0) { | ||||||
17821 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
17822 | } | ||||||
17823 | } | ||||||
17824 | } | ||||||
17825 | } | ||||||
17826 | if (OMPES == FunctionEmissionStatus::OMPDiscarded || | ||||||
17827 | (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) | ||||||
17828 | return OMPES; | ||||||
17829 | |||||||
17830 | if (LangOpts.CUDA) { | ||||||
17831 | // When compiling for device, host functions are never emitted. Similarly, | ||||||
17832 | // when compiling for host, device and global functions are never emitted. | ||||||
17833 | // (Technically, we do emit a host-side stub for global functions, but this | ||||||
17834 | // doesn't count for our purposes here.) | ||||||
17835 | Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); | ||||||
17836 | if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) | ||||||
17837 | return FunctionEmissionStatus::CUDADiscarded; | ||||||
17838 | if (!LangOpts.CUDAIsDevice && | ||||||
17839 | (T == Sema::CFT_Device || T == Sema::CFT_Global)) | ||||||
17840 | return FunctionEmissionStatus::CUDADiscarded; | ||||||
17841 | |||||||
17842 | // Check whether this function is externally visible -- if so, it's | ||||||
17843 | // known-emitted. | ||||||
17844 | // | ||||||
17845 | // We have to check the GVA linkage of the function's *definition* -- if we | ||||||
17846 | // only have a declaration, we don't know whether or not the function will | ||||||
17847 | // be emitted, because (say) the definition could include "inline". | ||||||
17848 | FunctionDecl *Def = FD->getDefinition(); | ||||||
17849 | |||||||
17850 | if (Def && | ||||||
17851 | !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) | ||||||
17852 | && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) | ||||||
17853 | return FunctionEmissionStatus::Emitted; | ||||||
17854 | } | ||||||
17855 | |||||||
17856 | // Otherwise, the function is known-emitted if it's in our set of | ||||||
17857 | // known-emitted functions. | ||||||
17858 | return (DeviceKnownEmittedFns.count(FD) > 0) | ||||||
17859 | ? FunctionEmissionStatus::Emitted | ||||||
17860 | : FunctionEmissionStatus::Unknown; | ||||||
17861 | } | ||||||
17862 | |||||||
17863 | bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { | ||||||
17864 | // Host-side references to a __global__ function refer to the stub, so the | ||||||
17865 | // function itself is never emitted and therefore should not be marked. | ||||||
17866 | // If we have host fn calls kernel fn calls host+device, the HD function | ||||||
17867 | // does not get instantiated on the host. We model this by omitting at the | ||||||
17868 | // call to the kernel from the callgraph. This ensures that, when compiling | ||||||
17869 | // for host, only HD functions actually called from the host get marked as | ||||||
17870 | // known-emitted. | ||||||
17871 | return LangOpts.CUDA && !LangOpts.CUDAIsDevice && | ||||||
17872 | IdentifyCUDATarget(Callee) == CFT_Global; | ||||||
17873 | } |
1 | //===--- ASTLambda.h - Lambda Helper Functions --------------*- C++ -*-===// | ||||||
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 | /// \file | ||||||
10 | /// This file provides some common utility functions for processing | ||||||
11 | /// Lambda related AST Constructs. | ||||||
12 | /// | ||||||
13 | //===----------------------------------------------------------------------===// | ||||||
14 | |||||||
15 | #ifndef LLVM_CLANG_AST_ASTLAMBDA_H | ||||||
16 | #define LLVM_CLANG_AST_ASTLAMBDA_H | ||||||
17 | |||||||
18 | #include "clang/AST/DeclCXX.h" | ||||||
19 | #include "clang/AST/DeclTemplate.h" | ||||||
20 | |||||||
21 | namespace clang { | ||||||
22 | inline StringRef getLambdaStaticInvokerName() { | ||||||
23 | return "__invoke"; | ||||||
24 | } | ||||||
25 | // This function returns true if M is a specialization, a template, | ||||||
26 | // or a non-generic lambda call operator. | ||||||
27 | inline bool isLambdaCallOperator(const CXXMethodDecl *MD) { | ||||||
28 | const CXXRecordDecl *LambdaClass = MD->getParent(); | ||||||
29 | if (!LambdaClass
| ||||||
30 | return MD->getOverloadedOperator() == OO_Call; | ||||||
31 | } | ||||||
32 | |||||||
33 | inline bool isLambdaCallOperator(const DeclContext *DC) { | ||||||
34 | if (!DC
| ||||||
35 | return isLambdaCallOperator(cast<CXXMethodDecl>(DC)); | ||||||
36 | } | ||||||
37 | |||||||
38 | inline bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD) { | ||||||
39 | if (!MD) return false; | ||||||
40 | const CXXRecordDecl *LambdaClass = MD->getParent(); | ||||||
41 | if (LambdaClass && LambdaClass->isGenericLambda()) | ||||||
42 | return isLambdaCallOperator(MD) && | ||||||
43 | MD->isFunctionTemplateSpecialization(); | ||||||
44 | return false; | ||||||
45 | } | ||||||
46 | |||||||
47 | inline bool isLambdaConversionOperator(CXXConversionDecl *C) { | ||||||
48 | return C ? C->getParent()->isLambda() : false; | ||||||
49 | } | ||||||
50 | |||||||
51 | inline bool isLambdaConversionOperator(Decl *D) { | ||||||
52 | if (!D) return false; | ||||||
53 | if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) | ||||||
54 | return isLambdaConversionOperator(Conv); | ||||||
55 | if (FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(D)) | ||||||
56 | if (CXXConversionDecl *Conv = | ||||||
57 | dyn_cast_or_null<CXXConversionDecl>(F->getTemplatedDecl())) | ||||||
58 | return isLambdaConversionOperator(Conv); | ||||||
59 | return false; | ||||||
60 | } | ||||||
61 | |||||||
62 | inline bool isGenericLambdaCallOperatorSpecialization(DeclContext *DC) { | ||||||
63 | return isGenericLambdaCallOperatorSpecialization( | ||||||
64 | dyn_cast<CXXMethodDecl>(DC)); | ||||||
65 | } | ||||||
66 | |||||||
67 | inline bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization( | ||||||
68 | DeclContext *DC) { | ||||||
69 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC); | ||||||
70 | if (!MD) return false; | ||||||
71 | const CXXRecordDecl *LambdaClass = MD->getParent(); | ||||||
72 | if (LambdaClass && LambdaClass->isGenericLambda()) | ||||||
73 | return (isLambdaCallOperator(MD) || MD->isLambdaStaticInvoker()) && | ||||||
74 | MD->isFunctionTemplateSpecialization(); | ||||||
75 | return false; | ||||||
76 | } | ||||||
77 | |||||||
78 | |||||||
79 | // This returns the parent DeclContext ensuring that the correct | ||||||
80 | // parent DeclContext is returned for Lambdas | ||||||
81 | inline DeclContext *getLambdaAwareParentOfDeclContext(DeclContext *DC) { | ||||||
82 | if (isLambdaCallOperator(DC)) | ||||||
83 | return DC->getParent()->getParent(); | ||||||
84 | else | ||||||
85 | return DC->getParent(); | ||||||
86 | } | ||||||
87 | |||||||
88 | } // clang | ||||||
89 | |||||||
90 | #endif |
1 | //===- DeclCXX.h - Classes for representing C++ declarations --*- C++ -*-=====// |
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 | /// \file |
10 | /// Defines the C++ Decl subclasses, other than those for templates |
11 | /// (found in DeclTemplate.h) and friends (in DeclFriend.h). |
12 | // |
13 | //===----------------------------------------------------------------------===// |
14 | |
15 | #ifndef LLVM_CLANG_AST_DECLCXX_H |
16 | #define LLVM_CLANG_AST_DECLCXX_H |
17 | |
18 | #include "clang/AST/ASTContext.h" |
19 | #include "clang/AST/ASTUnresolvedSet.h" |
20 | #include "clang/AST/Decl.h" |
21 | #include "clang/AST/DeclBase.h" |
22 | #include "clang/AST/DeclarationName.h" |
23 | #include "clang/AST/Expr.h" |
24 | #include "clang/AST/ExternalASTSource.h" |
25 | #include "clang/AST/LambdaCapture.h" |
26 | #include "clang/AST/NestedNameSpecifier.h" |
27 | #include "clang/AST/Redeclarable.h" |
28 | #include "clang/AST/Stmt.h" |
29 | #include "clang/AST/Type.h" |
30 | #include "clang/AST/TypeLoc.h" |
31 | #include "clang/AST/UnresolvedSet.h" |
32 | #include "clang/Basic/LLVM.h" |
33 | #include "clang/Basic/Lambda.h" |
34 | #include "clang/Basic/LangOptions.h" |
35 | #include "clang/Basic/OperatorKinds.h" |
36 | #include "clang/Basic/SourceLocation.h" |
37 | #include "clang/Basic/Specifiers.h" |
38 | #include "llvm/ADT/ArrayRef.h" |
39 | #include "llvm/ADT/DenseMap.h" |
40 | #include "llvm/ADT/PointerIntPair.h" |
41 | #include "llvm/ADT/PointerUnion.h" |
42 | #include "llvm/ADT/STLExtras.h" |
43 | #include "llvm/ADT/iterator_range.h" |
44 | #include "llvm/Support/Casting.h" |
45 | #include "llvm/Support/Compiler.h" |
46 | #include "llvm/Support/PointerLikeTypeTraits.h" |
47 | #include "llvm/Support/TrailingObjects.h" |
48 | #include <cassert> |
49 | #include <cstddef> |
50 | #include <iterator> |
51 | #include <memory> |
52 | #include <vector> |
53 | |
54 | namespace clang { |
55 | |
56 | class ClassTemplateDecl; |
57 | class ConstructorUsingShadowDecl; |
58 | class CXXBasePath; |
59 | class CXXBasePaths; |
60 | class CXXConstructorDecl; |
61 | class CXXDestructorDecl; |
62 | class CXXFinalOverriderMap; |
63 | class CXXIndirectPrimaryBaseSet; |
64 | class CXXMethodDecl; |
65 | class DecompositionDecl; |
66 | class DiagnosticBuilder; |
67 | class FriendDecl; |
68 | class FunctionTemplateDecl; |
69 | class IdentifierInfo; |
70 | class MemberSpecializationInfo; |
71 | class TemplateDecl; |
72 | class TemplateParameterList; |
73 | class UsingDecl; |
74 | |
75 | /// Represents an access specifier followed by colon ':'. |
76 | /// |
77 | /// An objects of this class represents sugar for the syntactic occurrence |
78 | /// of an access specifier followed by a colon in the list of member |
79 | /// specifiers of a C++ class definition. |
80 | /// |
81 | /// Note that they do not represent other uses of access specifiers, |
82 | /// such as those occurring in a list of base specifiers. |
83 | /// Also note that this class has nothing to do with so-called |
84 | /// "access declarations" (C++98 11.3 [class.access.dcl]). |
85 | class AccessSpecDecl : public Decl { |
86 | /// The location of the ':'. |
87 | SourceLocation ColonLoc; |
88 | |
89 | AccessSpecDecl(AccessSpecifier AS, DeclContext *DC, |
90 | SourceLocation ASLoc, SourceLocation ColonLoc) |
91 | : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) { |
92 | setAccess(AS); |
93 | } |
94 | |
95 | AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {} |
96 | |
97 | virtual void anchor(); |
98 | |
99 | public: |
100 | /// The location of the access specifier. |
101 | SourceLocation getAccessSpecifierLoc() const { return getLocation(); } |
102 | |
103 | /// Sets the location of the access specifier. |
104 | void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); } |
105 | |
106 | /// The location of the colon following the access specifier. |
107 | SourceLocation getColonLoc() const { return ColonLoc; } |
108 | |
109 | /// Sets the location of the colon. |
110 | void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; } |
111 | |
112 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
113 | return SourceRange(getAccessSpecifierLoc(), getColonLoc()); |
114 | } |
115 | |
116 | static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS, |
117 | DeclContext *DC, SourceLocation ASLoc, |
118 | SourceLocation ColonLoc) { |
119 | return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc); |
120 | } |
121 | |
122 | static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
123 | |
124 | // Implement isa/cast/dyncast/etc. |
125 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
126 | static bool classofKind(Kind K) { return K == AccessSpec; } |
127 | }; |
128 | |
129 | /// Represents a base class of a C++ class. |
130 | /// |
131 | /// Each CXXBaseSpecifier represents a single, direct base class (or |
132 | /// struct) of a C++ class (or struct). It specifies the type of that |
133 | /// base class, whether it is a virtual or non-virtual base, and what |
134 | /// level of access (public, protected, private) is used for the |
135 | /// derivation. For example: |
136 | /// |
137 | /// \code |
138 | /// class A { }; |
139 | /// class B { }; |
140 | /// class C : public virtual A, protected B { }; |
141 | /// \endcode |
142 | /// |
143 | /// In this code, C will have two CXXBaseSpecifiers, one for "public |
144 | /// virtual A" and the other for "protected B". |
145 | class CXXBaseSpecifier { |
146 | /// The source code range that covers the full base |
147 | /// specifier, including the "virtual" (if present) and access |
148 | /// specifier (if present). |
149 | SourceRange Range; |
150 | |
151 | /// The source location of the ellipsis, if this is a pack |
152 | /// expansion. |
153 | SourceLocation EllipsisLoc; |
154 | |
155 | /// Whether this is a virtual base class or not. |
156 | unsigned Virtual : 1; |
157 | |
158 | /// Whether this is the base of a class (true) or of a struct (false). |
159 | /// |
160 | /// This determines the mapping from the access specifier as written in the |
161 | /// source code to the access specifier used for semantic analysis. |
162 | unsigned BaseOfClass : 1; |
163 | |
164 | /// Access specifier as written in the source code (may be AS_none). |
165 | /// |
166 | /// The actual type of data stored here is an AccessSpecifier, but we use |
167 | /// "unsigned" here to work around a VC++ bug. |
168 | unsigned Access : 2; |
169 | |
170 | /// Whether the class contains a using declaration |
171 | /// to inherit the named class's constructors. |
172 | unsigned InheritConstructors : 1; |
173 | |
174 | /// The type of the base class. |
175 | /// |
176 | /// This will be a class or struct (or a typedef of such). The source code |
177 | /// range does not include the \c virtual or the access specifier. |
178 | TypeSourceInfo *BaseTypeInfo; |
179 | |
180 | public: |
181 | CXXBaseSpecifier() = default; |
182 | CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A, |
183 | TypeSourceInfo *TInfo, SourceLocation EllipsisLoc) |
184 | : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC), |
185 | Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {} |
186 | |
187 | /// Retrieves the source range that contains the entire base specifier. |
188 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; } |
189 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); } |
190 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); } |
191 | |
192 | /// Get the location at which the base class type was written. |
193 | SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) { |
194 | return BaseTypeInfo->getTypeLoc().getBeginLoc(); |
195 | } |
196 | |
197 | /// Determines whether the base class is a virtual base class (or not). |
198 | bool isVirtual() const { return Virtual; } |
199 | |
200 | /// Determine whether this base class is a base of a class declared |
201 | /// with the 'class' keyword (vs. one declared with the 'struct' keyword). |
202 | bool isBaseOfClass() const { return BaseOfClass; } |
203 | |
204 | /// Determine whether this base specifier is a pack expansion. |
205 | bool isPackExpansion() const { return EllipsisLoc.isValid(); } |
206 | |
207 | /// Determine whether this base class's constructors get inherited. |
208 | bool getInheritConstructors() const { return InheritConstructors; } |
209 | |
210 | /// Set that this base class's constructors should be inherited. |
211 | void setInheritConstructors(bool Inherit = true) { |
212 | InheritConstructors = Inherit; |
213 | } |
214 | |
215 | /// For a pack expansion, determine the location of the ellipsis. |
216 | SourceLocation getEllipsisLoc() const { |
217 | return EllipsisLoc; |
218 | } |
219 | |
220 | /// Returns the access specifier for this base specifier. |
221 | /// |
222 | /// This is the actual base specifier as used for semantic analysis, so |
223 | /// the result can never be AS_none. To retrieve the access specifier as |
224 | /// written in the source code, use getAccessSpecifierAsWritten(). |
225 | AccessSpecifier getAccessSpecifier() const { |
226 | if ((AccessSpecifier)Access == AS_none) |
227 | return BaseOfClass? AS_private : AS_public; |
228 | else |
229 | return (AccessSpecifier)Access; |
230 | } |
231 | |
232 | /// Retrieves the access specifier as written in the source code |
233 | /// (which may mean that no access specifier was explicitly written). |
234 | /// |
235 | /// Use getAccessSpecifier() to retrieve the access specifier for use in |
236 | /// semantic analysis. |
237 | AccessSpecifier getAccessSpecifierAsWritten() const { |
238 | return (AccessSpecifier)Access; |
239 | } |
240 | |
241 | /// Retrieves the type of the base class. |
242 | /// |
243 | /// This type will always be an unqualified class type. |
244 | QualType getType() const { |
245 | return BaseTypeInfo->getType().getUnqualifiedType(); |
246 | } |
247 | |
248 | /// Retrieves the type and source location of the base class. |
249 | TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; } |
250 | }; |
251 | |
252 | /// Represents a C++ struct/union/class. |
253 | class CXXRecordDecl : public RecordDecl { |
254 | friend class ASTDeclReader; |
255 | friend class ASTDeclWriter; |
256 | friend class ASTNodeImporter; |
257 | friend class ASTReader; |
258 | friend class ASTRecordWriter; |
259 | friend class ASTWriter; |
260 | friend class DeclContext; |
261 | friend class LambdaExpr; |
262 | |
263 | friend void FunctionDecl::setPure(bool); |
264 | friend void TagDecl::startDefinition(); |
265 | |
266 | /// Values used in DefinitionData fields to represent special members. |
267 | enum SpecialMemberFlags { |
268 | SMF_DefaultConstructor = 0x1, |
269 | SMF_CopyConstructor = 0x2, |
270 | SMF_MoveConstructor = 0x4, |
271 | SMF_CopyAssignment = 0x8, |
272 | SMF_MoveAssignment = 0x10, |
273 | SMF_Destructor = 0x20, |
274 | SMF_All = 0x3f |
275 | }; |
276 | |
277 | struct DefinitionData { |
278 | #define FIELD(Name, Width, Merge) \ |
279 | unsigned Name : Width; |
280 | #include "CXXRecordDeclDefinitionBits.def" |
281 | |
282 | /// Whether this class describes a C++ lambda. |
283 | unsigned IsLambda : 1; |
284 | |
285 | /// Whether we are currently parsing base specifiers. |
286 | unsigned IsParsingBaseSpecifiers : 1; |
287 | |
288 | /// True when visible conversion functions are already computed |
289 | /// and are available. |
290 | unsigned ComputedVisibleConversions : 1; |
291 | |
292 | unsigned HasODRHash : 1; |
293 | |
294 | /// A hash of parts of the class to help in ODR checking. |
295 | unsigned ODRHash = 0; |
296 | |
297 | /// The number of base class specifiers in Bases. |
298 | unsigned NumBases = 0; |
299 | |
300 | /// The number of virtual base class specifiers in VBases. |
301 | unsigned NumVBases = 0; |
302 | |
303 | /// Base classes of this class. |
304 | /// |
305 | /// FIXME: This is wasted space for a union. |
306 | LazyCXXBaseSpecifiersPtr Bases; |
307 | |
308 | /// direct and indirect virtual base classes of this class. |
309 | LazyCXXBaseSpecifiersPtr VBases; |
310 | |
311 | /// The conversion functions of this C++ class (but not its |
312 | /// inherited conversion functions). |
313 | /// |
314 | /// Each of the entries in this overload set is a CXXConversionDecl. |
315 | LazyASTUnresolvedSet Conversions; |
316 | |
317 | /// The conversion functions of this C++ class and all those |
318 | /// inherited conversion functions that are visible in this class. |
319 | /// |
320 | /// Each of the entries in this overload set is a CXXConversionDecl or a |
321 | /// FunctionTemplateDecl. |
322 | LazyASTUnresolvedSet VisibleConversions; |
323 | |
324 | /// The declaration which defines this record. |
325 | CXXRecordDecl *Definition; |
326 | |
327 | /// The first friend declaration in this class, or null if there |
328 | /// aren't any. |
329 | /// |
330 | /// This is actually currently stored in reverse order. |
331 | LazyDeclPtr FirstFriend; |
332 | |
333 | DefinitionData(CXXRecordDecl *D); |
334 | |
335 | /// Retrieve the set of direct base classes. |
336 | CXXBaseSpecifier *getBases() const { |
337 | if (!Bases.isOffset()) |
338 | return Bases.get(nullptr); |
339 | return getBasesSlowCase(); |
340 | } |
341 | |
342 | /// Retrieve the set of virtual base classes. |
343 | CXXBaseSpecifier *getVBases() const { |
344 | if (!VBases.isOffset()) |
345 | return VBases.get(nullptr); |
346 | return getVBasesSlowCase(); |
347 | } |
348 | |
349 | ArrayRef<CXXBaseSpecifier> bases() const { |
350 | return llvm::makeArrayRef(getBases(), NumBases); |
351 | } |
352 | |
353 | ArrayRef<CXXBaseSpecifier> vbases() const { |
354 | return llvm::makeArrayRef(getVBases(), NumVBases); |
355 | } |
356 | |
357 | private: |
358 | CXXBaseSpecifier *getBasesSlowCase() const; |
359 | CXXBaseSpecifier *getVBasesSlowCase() const; |
360 | }; |
361 | |
362 | struct DefinitionData *DefinitionData; |
363 | |
364 | /// Describes a C++ closure type (generated by a lambda expression). |
365 | struct LambdaDefinitionData : public DefinitionData { |
366 | using Capture = LambdaCapture; |
367 | |
368 | /// Whether this lambda is known to be dependent, even if its |
369 | /// context isn't dependent. |
370 | /// |
371 | /// A lambda with a non-dependent context can be dependent if it occurs |
372 | /// within the default argument of a function template, because the |
373 | /// lambda will have been created with the enclosing context as its |
374 | /// declaration context, rather than function. This is an unfortunate |
375 | /// artifact of having to parse the default arguments before. |
376 | unsigned Dependent : 1; |
377 | |
378 | /// Whether this lambda is a generic lambda. |
379 | unsigned IsGenericLambda : 1; |
380 | |
381 | /// The Default Capture. |
382 | unsigned CaptureDefault : 2; |
383 | |
384 | /// The number of captures in this lambda is limited 2^NumCaptures. |
385 | unsigned NumCaptures : 15; |
386 | |
387 | /// The number of explicit captures in this lambda. |
388 | unsigned NumExplicitCaptures : 13; |
389 | |
390 | /// Has known `internal` linkage. |
391 | unsigned HasKnownInternalLinkage : 1; |
392 | |
393 | /// The number used to indicate this lambda expression for name |
394 | /// mangling in the Itanium C++ ABI. |
395 | unsigned ManglingNumber : 31; |
396 | |
397 | /// The declaration that provides context for this lambda, if the |
398 | /// actual DeclContext does not suffice. This is used for lambdas that |
399 | /// occur within default arguments of function parameters within the class |
400 | /// or within a data member initializer. |
401 | LazyDeclPtr ContextDecl; |
402 | |
403 | /// The list of captures, both explicit and implicit, for this |
404 | /// lambda. |
405 | Capture *Captures = nullptr; |
406 | |
407 | /// The type of the call method. |
408 | TypeSourceInfo *MethodTyInfo; |
409 | |
410 | LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info, bool Dependent, |
411 | bool IsGeneric, LambdaCaptureDefault CaptureDefault) |
412 | : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric), |
413 | CaptureDefault(CaptureDefault), NumCaptures(0), |
414 | NumExplicitCaptures(0), HasKnownInternalLinkage(0), ManglingNumber(0), |
415 | MethodTyInfo(Info) { |
416 | IsLambda = true; |
417 | |
418 | // C++1z [expr.prim.lambda]p4: |
419 | // This class type is not an aggregate type. |
420 | Aggregate = false; |
421 | PlainOldData = false; |
422 | } |
423 | }; |
424 | |
425 | struct DefinitionData *dataPtr() const { |
426 | // Complete the redecl chain (if necessary). |
427 | getMostRecentDecl(); |
428 | return DefinitionData; |
429 | } |
430 | |
431 | struct DefinitionData &data() const { |
432 | auto *DD = dataPtr(); |
433 | assert(DD && "queried property of class with no definition")((DD && "queried property of class with no definition" ) ? static_cast<void> (0) : __assert_fail ("DD && \"queried property of class with no definition\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 433, __PRETTY_FUNCTION__)); |
434 | return *DD; |
435 | } |
436 | |
437 | struct LambdaDefinitionData &getLambdaData() const { |
438 | // No update required: a merged definition cannot change any lambda |
439 | // properties. |
440 | auto *DD = DefinitionData; |
441 | assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")((DD && DD->IsLambda && "queried lambda property of non-lambda class" ) ? static_cast<void> (0) : __assert_fail ("DD && DD->IsLambda && \"queried lambda property of non-lambda class\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 441, __PRETTY_FUNCTION__)); |
442 | return static_cast<LambdaDefinitionData&>(*DD); |
443 | } |
444 | |
445 | /// The template or declaration that this declaration |
446 | /// describes or was instantiated from, respectively. |
447 | /// |
448 | /// For non-templates, this value will be null. For record |
449 | /// declarations that describe a class template, this will be a |
450 | /// pointer to a ClassTemplateDecl. For member |
451 | /// classes of class template specializations, this will be the |
452 | /// MemberSpecializationInfo referring to the member class that was |
453 | /// instantiated or specialized. |
454 | llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *> |
455 | TemplateOrInstantiation; |
456 | |
457 | /// Called from setBases and addedMember to notify the class that a |
458 | /// direct or virtual base class or a member of class type has been added. |
459 | void addedClassSubobject(CXXRecordDecl *Base); |
460 | |
461 | /// Notify the class that member has been added. |
462 | /// |
463 | /// This routine helps maintain information about the class based on which |
464 | /// members have been added. It will be invoked by DeclContext::addDecl() |
465 | /// whenever a member is added to this record. |
466 | void addedMember(Decl *D); |
467 | |
468 | void markedVirtualFunctionPure(); |
469 | |
470 | /// Get the head of our list of friend declarations, possibly |
471 | /// deserializing the friends from an external AST source. |
472 | FriendDecl *getFirstFriend() const; |
473 | |
474 | /// Determine whether this class has an empty base class subobject of type X |
475 | /// or of one of the types that might be at offset 0 within X (per the C++ |
476 | /// "standard layout" rules). |
477 | bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx, |
478 | const CXXRecordDecl *X); |
479 | |
480 | protected: |
481 | CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC, |
482 | SourceLocation StartLoc, SourceLocation IdLoc, |
483 | IdentifierInfo *Id, CXXRecordDecl *PrevDecl); |
484 | |
485 | public: |
486 | /// Iterator that traverses the base classes of a class. |
487 | using base_class_iterator = CXXBaseSpecifier *; |
488 | |
489 | /// Iterator that traverses the base classes of a class. |
490 | using base_class_const_iterator = const CXXBaseSpecifier *; |
491 | |
492 | CXXRecordDecl *getCanonicalDecl() override { |
493 | return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl()); |
494 | } |
495 | |
496 | const CXXRecordDecl *getCanonicalDecl() const { |
497 | return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl(); |
498 | } |
499 | |
500 | CXXRecordDecl *getPreviousDecl() { |
501 | return cast_or_null<CXXRecordDecl>( |
502 | static_cast<RecordDecl *>(this)->getPreviousDecl()); |
503 | } |
504 | |
505 | const CXXRecordDecl *getPreviousDecl() const { |
506 | return const_cast<CXXRecordDecl*>(this)->getPreviousDecl(); |
507 | } |
508 | |
509 | CXXRecordDecl *getMostRecentDecl() { |
510 | return cast<CXXRecordDecl>( |
511 | static_cast<RecordDecl *>(this)->getMostRecentDecl()); |
512 | } |
513 | |
514 | const CXXRecordDecl *getMostRecentDecl() const { |
515 | return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl(); |
516 | } |
517 | |
518 | CXXRecordDecl *getMostRecentNonInjectedDecl() { |
519 | CXXRecordDecl *Recent = |
520 | static_cast<CXXRecordDecl *>(this)->getMostRecentDecl(); |
521 | while (Recent->isInjectedClassName()) { |
522 | // FIXME: Does injected class name need to be in the redeclarations chain? |
523 | assert(Recent->getPreviousDecl())((Recent->getPreviousDecl()) ? static_cast<void> (0) : __assert_fail ("Recent->getPreviousDecl()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 523, __PRETTY_FUNCTION__)); |
524 | Recent = Recent->getPreviousDecl(); |
525 | } |
526 | return Recent; |
527 | } |
528 | |
529 | const CXXRecordDecl *getMostRecentNonInjectedDecl() const { |
530 | return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl(); |
531 | } |
532 | |
533 | CXXRecordDecl *getDefinition() const { |
534 | // We only need an update if we don't already know which |
535 | // declaration is the definition. |
536 | auto *DD = DefinitionData ? DefinitionData : dataPtr(); |
537 | return DD ? DD->Definition : nullptr; |
538 | } |
539 | |
540 | bool hasDefinition() const { return DefinitionData || dataPtr(); } |
541 | |
542 | static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
543 | SourceLocation StartLoc, SourceLocation IdLoc, |
544 | IdentifierInfo *Id, |
545 | CXXRecordDecl *PrevDecl = nullptr, |
546 | bool DelayTypeCreation = false); |
547 | static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC, |
548 | TypeSourceInfo *Info, SourceLocation Loc, |
549 | bool DependentLambda, bool IsGeneric, |
550 | LambdaCaptureDefault CaptureDefault); |
551 | static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); |
552 | |
553 | bool isDynamicClass() const { |
554 | return data().Polymorphic || data().NumVBases != 0; |
555 | } |
556 | |
557 | /// @returns true if class is dynamic or might be dynamic because the |
558 | /// definition is incomplete of dependent. |
559 | bool mayBeDynamicClass() const { |
560 | return !hasDefinition() || isDynamicClass() || hasAnyDependentBases(); |
561 | } |
562 | |
563 | /// @returns true if class is non dynamic or might be non dynamic because the |
564 | /// definition is incomplete of dependent. |
565 | bool mayBeNonDynamicClass() const { |
566 | return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases(); |
567 | } |
568 | |
569 | void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; } |
570 | |
571 | bool isParsingBaseSpecifiers() const { |
572 | return data().IsParsingBaseSpecifiers; |
573 | } |
574 | |
575 | unsigned getODRHash() const; |
576 | |
577 | /// Sets the base classes of this struct or class. |
578 | void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases); |
579 | |
580 | /// Retrieves the number of base classes of this class. |
581 | unsigned getNumBases() const { return data().NumBases; } |
582 | |
583 | using base_class_range = llvm::iterator_range<base_class_iterator>; |
584 | using base_class_const_range = |
585 | llvm::iterator_range<base_class_const_iterator>; |
586 | |
587 | base_class_range bases() { |
588 | return base_class_range(bases_begin(), bases_end()); |
589 | } |
590 | base_class_const_range bases() const { |
591 | return base_class_const_range(bases_begin(), bases_end()); |
592 | } |
593 | |
594 | base_class_iterator bases_begin() { return data().getBases(); } |
595 | base_class_const_iterator bases_begin() const { return data().getBases(); } |
596 | base_class_iterator bases_end() { return bases_begin() + data().NumBases; } |
597 | base_class_const_iterator bases_end() const { |
598 | return bases_begin() + data().NumBases; |
599 | } |
600 | |
601 | /// Retrieves the number of virtual base classes of this class. |
602 | unsigned getNumVBases() const { return data().NumVBases; } |
603 | |
604 | base_class_range vbases() { |
605 | return base_class_range(vbases_begin(), vbases_end()); |
606 | } |
607 | base_class_const_range vbases() const { |
608 | return base_class_const_range(vbases_begin(), vbases_end()); |
609 | } |
610 | |
611 | base_class_iterator vbases_begin() { return data().getVBases(); } |
612 | base_class_const_iterator vbases_begin() const { return data().getVBases(); } |
613 | base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; } |
614 | base_class_const_iterator vbases_end() const { |
615 | return vbases_begin() + data().NumVBases; |
616 | } |
617 | |
618 | /// Determine whether this class has any dependent base classes which |
619 | /// are not the current instantiation. |
620 | bool hasAnyDependentBases() const; |
621 | |
622 | /// Iterator access to method members. The method iterator visits |
623 | /// all method members of the class, including non-instance methods, |
624 | /// special methods, etc. |
625 | using method_iterator = specific_decl_iterator<CXXMethodDecl>; |
626 | using method_range = |
627 | llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>; |
628 | |
629 | method_range methods() const { |
630 | return method_range(method_begin(), method_end()); |
631 | } |
632 | |
633 | /// Method begin iterator. Iterates in the order the methods |
634 | /// were declared. |
635 | method_iterator method_begin() const { |
636 | return method_iterator(decls_begin()); |
637 | } |
638 | |
639 | /// Method past-the-end iterator. |
640 | method_iterator method_end() const { |
641 | return method_iterator(decls_end()); |
642 | } |
643 | |
644 | /// Iterator access to constructor members. |
645 | using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>; |
646 | using ctor_range = |
647 | llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>; |
648 | |
649 | ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); } |
650 | |
651 | ctor_iterator ctor_begin() const { |
652 | return ctor_iterator(decls_begin()); |
653 | } |
654 | |
655 | ctor_iterator ctor_end() const { |
656 | return ctor_iterator(decls_end()); |
657 | } |
658 | |
659 | /// An iterator over friend declarations. All of these are defined |
660 | /// in DeclFriend.h. |
661 | class friend_iterator; |
662 | using friend_range = llvm::iterator_range<friend_iterator>; |
663 | |
664 | friend_range friends() const; |
665 | friend_iterator friend_begin() const; |
666 | friend_iterator friend_end() const; |
667 | void pushFriendDecl(FriendDecl *FD); |
668 | |
669 | /// Determines whether this record has any friends. |
670 | bool hasFriends() const { |
671 | return data().FirstFriend.isValid(); |
672 | } |
673 | |
674 | /// \c true if a defaulted copy constructor for this class would be |
675 | /// deleted. |
676 | bool defaultedCopyConstructorIsDeleted() const { |
677 | assert((!needsOverloadResolutionForCopyConstructor() ||(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 679, __PRETTY_FUNCTION__)) |
678 | (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 679, __PRETTY_FUNCTION__)) |
679 | "this property has not yet been computed by Sema")(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 679, __PRETTY_FUNCTION__)); |
680 | return data().DefaultedCopyConstructorIsDeleted; |
681 | } |
682 | |
683 | /// \c true if a defaulted move constructor for this class would be |
684 | /// deleted. |
685 | bool defaultedMoveConstructorIsDeleted() const { |
686 | assert((!needsOverloadResolutionForMoveConstructor() ||(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 688, __PRETTY_FUNCTION__)) |
687 | (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 688, __PRETTY_FUNCTION__)) |
688 | "this property has not yet been computed by Sema")(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 688, __PRETTY_FUNCTION__)); |
689 | return data().DefaultedMoveConstructorIsDeleted; |
690 | } |
691 | |
692 | /// \c true if a defaulted destructor for this class would be deleted. |
693 | bool defaultedDestructorIsDeleted() const { |
694 | assert((!needsOverloadResolutionForDestructor() ||(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 696, __PRETTY_FUNCTION__)) |
695 | (data().DeclaredSpecialMembers & SMF_Destructor)) &&(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 696, __PRETTY_FUNCTION__)) |
696 | "this property has not yet been computed by Sema")(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && "this property has not yet been computed by Sema" ) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 696, __PRETTY_FUNCTION__)); |
697 | return data().DefaultedDestructorIsDeleted; |
698 | } |
699 | |
700 | /// \c true if we know for sure that this class has a single, |
701 | /// accessible, unambiguous copy constructor that is not deleted. |
702 | bool hasSimpleCopyConstructor() const { |
703 | return !hasUserDeclaredCopyConstructor() && |
704 | !data().DefaultedCopyConstructorIsDeleted; |
705 | } |
706 | |
707 | /// \c true if we know for sure that this class has a single, |
708 | /// accessible, unambiguous move constructor that is not deleted. |
709 | bool hasSimpleMoveConstructor() const { |
710 | return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() && |
711 | !data().DefaultedMoveConstructorIsDeleted; |
712 | } |
713 | |
714 | /// \c true if we know for sure that this class has a single, |
715 | /// accessible, unambiguous move assignment operator that is not deleted. |
716 | bool hasSimpleMoveAssignment() const { |
717 | return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() && |
718 | !data().DefaultedMoveAssignmentIsDeleted; |
719 | } |
720 | |
721 | /// \c true if we know for sure that this class has an accessible |
722 | /// destructor that is not deleted. |
723 | bool hasSimpleDestructor() const { |
724 | return !hasUserDeclaredDestructor() && |
725 | !data().DefaultedDestructorIsDeleted; |
726 | } |
727 | |
728 | /// Determine whether this class has any default constructors. |
729 | bool hasDefaultConstructor() const { |
730 | return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) || |
731 | needsImplicitDefaultConstructor(); |
732 | } |
733 | |
734 | /// Determine if we need to declare a default constructor for |
735 | /// this class. |
736 | /// |
737 | /// This value is used for lazy creation of default constructors. |
738 | bool needsImplicitDefaultConstructor() const { |
739 | return !data().UserDeclaredConstructor && |
740 | !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) && |
741 | (!isLambda() || lambdaIsDefaultConstructibleAndAssignable()); |
742 | } |
743 | |
744 | /// Determine whether this class has any user-declared constructors. |
745 | /// |
746 | /// When true, a default constructor will not be implicitly declared. |
747 | bool hasUserDeclaredConstructor() const { |
748 | return data().UserDeclaredConstructor; |
749 | } |
750 | |
751 | /// Whether this class has a user-provided default constructor |
752 | /// per C++11. |
753 | bool hasUserProvidedDefaultConstructor() const { |
754 | return data().UserProvidedDefaultConstructor; |
755 | } |
756 | |
757 | /// Determine whether this class has a user-declared copy constructor. |
758 | /// |
759 | /// When false, a copy constructor will be implicitly declared. |
760 | bool hasUserDeclaredCopyConstructor() const { |
761 | return data().UserDeclaredSpecialMembers & SMF_CopyConstructor; |
762 | } |
763 | |
764 | /// Determine whether this class needs an implicit copy |
765 | /// constructor to be lazily declared. |
766 | bool needsImplicitCopyConstructor() const { |
767 | return !(data().DeclaredSpecialMembers & SMF_CopyConstructor); |
768 | } |
769 | |
770 | /// Determine whether we need to eagerly declare a defaulted copy |
771 | /// constructor for this class. |
772 | bool needsOverloadResolutionForCopyConstructor() const { |
773 | // C++17 [class.copy.ctor]p6: |
774 | // If the class definition declares a move constructor or move assignment |
775 | // operator, the implicitly declared copy constructor is defined as |
776 | // deleted. |
777 | // In MSVC mode, sometimes a declared move assignment does not delete an |
778 | // implicit copy constructor, so defer this choice to Sema. |
779 | if (data().UserDeclaredSpecialMembers & |
780 | (SMF_MoveConstructor | SMF_MoveAssignment)) |
781 | return true; |
782 | return data().NeedOverloadResolutionForCopyConstructor; |
783 | } |
784 | |
785 | /// Determine whether an implicit copy constructor for this type |
786 | /// would have a parameter with a const-qualified reference type. |
787 | bool implicitCopyConstructorHasConstParam() const { |
788 | return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase && |
789 | (isAbstract() || |
790 | data().ImplicitCopyConstructorCanHaveConstParamForVBase); |
791 | } |
792 | |
793 | /// Determine whether this class has a copy constructor with |
794 | /// a parameter type which is a reference to a const-qualified type. |
795 | bool hasCopyConstructorWithConstParam() const { |
796 | return data().HasDeclaredCopyConstructorWithConstParam || |
797 | (needsImplicitCopyConstructor() && |
798 | implicitCopyConstructorHasConstParam()); |
799 | } |
800 | |
801 | /// Whether this class has a user-declared move constructor or |
802 | /// assignment operator. |
803 | /// |
804 | /// When false, a move constructor and assignment operator may be |
805 | /// implicitly declared. |
806 | bool hasUserDeclaredMoveOperation() const { |
807 | return data().UserDeclaredSpecialMembers & |
808 | (SMF_MoveConstructor | SMF_MoveAssignment); |
809 | } |
810 | |
811 | /// Determine whether this class has had a move constructor |
812 | /// declared by the user. |
813 | bool hasUserDeclaredMoveConstructor() const { |
814 | return data().UserDeclaredSpecialMembers & SMF_MoveConstructor; |
815 | } |
816 | |
817 | /// Determine whether this class has a move constructor. |
818 | bool hasMoveConstructor() const { |
819 | return (data().DeclaredSpecialMembers & SMF_MoveConstructor) || |
820 | needsImplicitMoveConstructor(); |
821 | } |
822 | |
823 | /// Set that we attempted to declare an implicit copy |
824 | /// constructor, but overload resolution failed so we deleted it. |
825 | void setImplicitCopyConstructorIsDeleted() { |
826 | assert((data().DefaultedCopyConstructorIsDeleted ||(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor ()) && "Copy constructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 828, __PRETTY_FUNCTION__)) |
827 | needsOverloadResolutionForCopyConstructor()) &&(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor ()) && "Copy constructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 828, __PRETTY_FUNCTION__)) |
828 | "Copy constructor should not be deleted")(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor ()) && "Copy constructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 828, __PRETTY_FUNCTION__)); |
829 | data().DefaultedCopyConstructorIsDeleted = true; |
830 | } |
831 | |
832 | /// Set that we attempted to declare an implicit move |
833 | /// constructor, but overload resolution failed so we deleted it. |
834 | void setImplicitMoveConstructorIsDeleted() { |
835 | assert((data().DefaultedMoveConstructorIsDeleted ||(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor ()) && "move constructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 837, __PRETTY_FUNCTION__)) |
836 | needsOverloadResolutionForMoveConstructor()) &&(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor ()) && "move constructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 837, __PRETTY_FUNCTION__)) |
837 | "move constructor should not be deleted")(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor ()) && "move constructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 837, __PRETTY_FUNCTION__)); |
838 | data().DefaultedMoveConstructorIsDeleted = true; |
839 | } |
840 | |
841 | /// Set that we attempted to declare an implicit destructor, |
842 | /// but overload resolution failed so we deleted it. |
843 | void setImplicitDestructorIsDeleted() { |
844 | assert((data().DefaultedDestructorIsDeleted ||(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor ()) && "destructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 846, __PRETTY_FUNCTION__)) |
845 | needsOverloadResolutionForDestructor()) &&(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor ()) && "destructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 846, __PRETTY_FUNCTION__)) |
846 | "destructor should not be deleted")(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor ()) && "destructor should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 846, __PRETTY_FUNCTION__)); |
847 | data().DefaultedDestructorIsDeleted = true; |
848 | } |
849 | |
850 | /// Determine whether this class should get an implicit move |
851 | /// constructor or if any existing special member function inhibits this. |
852 | bool needsImplicitMoveConstructor() const { |
853 | return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) && |
854 | !hasUserDeclaredCopyConstructor() && |
855 | !hasUserDeclaredCopyAssignment() && |
856 | !hasUserDeclaredMoveAssignment() && |
857 | !hasUserDeclaredDestructor(); |
858 | } |
859 | |
860 | /// Determine whether we need to eagerly declare a defaulted move |
861 | /// constructor for this class. |
862 | bool needsOverloadResolutionForMoveConstructor() const { |
863 | return data().NeedOverloadResolutionForMoveConstructor; |
864 | } |
865 | |
866 | /// Determine whether this class has a user-declared copy assignment |
867 | /// operator. |
868 | /// |
869 | /// When false, a copy assignment operator will be implicitly declared. |
870 | bool hasUserDeclaredCopyAssignment() const { |
871 | return data().UserDeclaredSpecialMembers & SMF_CopyAssignment; |
872 | } |
873 | |
874 | /// Determine whether this class needs an implicit copy |
875 | /// assignment operator to be lazily declared. |
876 | bool needsImplicitCopyAssignment() const { |
877 | return !(data().DeclaredSpecialMembers & SMF_CopyAssignment); |
878 | } |
879 | |
880 | /// Determine whether we need to eagerly declare a defaulted copy |
881 | /// assignment operator for this class. |
882 | bool needsOverloadResolutionForCopyAssignment() const { |
883 | return data().HasMutableFields; |
884 | } |
885 | |
886 | /// Determine whether an implicit copy assignment operator for this |
887 | /// type would have a parameter with a const-qualified reference type. |
888 | bool implicitCopyAssignmentHasConstParam() const { |
889 | return data().ImplicitCopyAssignmentHasConstParam; |
890 | } |
891 | |
892 | /// Determine whether this class has a copy assignment operator with |
893 | /// a parameter type which is a reference to a const-qualified type or is not |
894 | /// a reference. |
895 | bool hasCopyAssignmentWithConstParam() const { |
896 | return data().HasDeclaredCopyAssignmentWithConstParam || |
897 | (needsImplicitCopyAssignment() && |
898 | implicitCopyAssignmentHasConstParam()); |
899 | } |
900 | |
901 | /// Determine whether this class has had a move assignment |
902 | /// declared by the user. |
903 | bool hasUserDeclaredMoveAssignment() const { |
904 | return data().UserDeclaredSpecialMembers & SMF_MoveAssignment; |
905 | } |
906 | |
907 | /// Determine whether this class has a move assignment operator. |
908 | bool hasMoveAssignment() const { |
909 | return (data().DeclaredSpecialMembers & SMF_MoveAssignment) || |
910 | needsImplicitMoveAssignment(); |
911 | } |
912 | |
913 | /// Set that we attempted to declare an implicit move assignment |
914 | /// operator, but overload resolution failed so we deleted it. |
915 | void setImplicitMoveAssignmentIsDeleted() { |
916 | assert((data().DefaultedMoveAssignmentIsDeleted ||(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment ()) && "move assignment should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 918, __PRETTY_FUNCTION__)) |
917 | needsOverloadResolutionForMoveAssignment()) &&(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment ()) && "move assignment should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 918, __PRETTY_FUNCTION__)) |
918 | "move assignment should not be deleted")(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment ()) && "move assignment should not be deleted") ? static_cast <void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 918, __PRETTY_FUNCTION__)); |
919 | data().DefaultedMoveAssignmentIsDeleted = true; |
920 | } |
921 | |
922 | /// Determine whether this class should get an implicit move |
923 | /// assignment operator or if any existing special member function inhibits |
924 | /// this. |
925 | bool needsImplicitMoveAssignment() const { |
926 | return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) && |
927 | !hasUserDeclaredCopyConstructor() && |
928 | !hasUserDeclaredCopyAssignment() && |
929 | !hasUserDeclaredMoveConstructor() && |
930 | !hasUserDeclaredDestructor() && |
931 | (!isLambda() || lambdaIsDefaultConstructibleAndAssignable()); |
932 | } |
933 | |
934 | /// Determine whether we need to eagerly declare a move assignment |
935 | /// operator for this class. |
936 | bool needsOverloadResolutionForMoveAssignment() const { |
937 | return data().NeedOverloadResolutionForMoveAssignment; |
938 | } |
939 | |
940 | /// Determine whether this class has a user-declared destructor. |
941 | /// |
942 | /// When false, a destructor will be implicitly declared. |
943 | bool hasUserDeclaredDestructor() const { |
944 | return data().UserDeclaredSpecialMembers & SMF_Destructor; |
945 | } |
946 | |
947 | /// Determine whether this class needs an implicit destructor to |
948 | /// be lazily declared. |
949 | bool needsImplicitDestructor() const { |
950 | return !(data().DeclaredSpecialMembers & SMF_Destructor); |
951 | } |
952 | |
953 | /// Determine whether we need to eagerly declare a destructor for this |
954 | /// class. |
955 | bool needsOverloadResolutionForDestructor() const { |
956 | return data().NeedOverloadResolutionForDestructor; |
957 | } |
958 | |
959 | /// Determine whether this class describes a lambda function object. |
960 | bool isLambda() const { |
961 | // An update record can't turn a non-lambda into a lambda. |
962 | auto *DD = DefinitionData; |
963 | return DD && DD->IsLambda; |
964 | } |
965 | |
966 | /// Determine whether this class describes a generic |
967 | /// lambda function object (i.e. function call operator is |
968 | /// a template). |
969 | bool isGenericLambda() const; |
970 | |
971 | /// Determine whether this lambda should have an implicit default constructor |
972 | /// and copy and move assignment operators. |
973 | bool lambdaIsDefaultConstructibleAndAssignable() const; |
974 | |
975 | /// Retrieve the lambda call operator of the closure type |
976 | /// if this is a closure type. |
977 | CXXMethodDecl *getLambdaCallOperator() const; |
978 | |
979 | /// Retrieve the dependent lambda call operator of the closure type |
980 | /// if this is a templated closure type. |
981 | FunctionTemplateDecl *getDependentLambdaCallOperator() const; |
982 | |
983 | /// Retrieve the lambda static invoker, the address of which |
984 | /// is returned by the conversion operator, and the body of which |
985 | /// is forwarded to the lambda call operator. |
986 | CXXMethodDecl *getLambdaStaticInvoker() const; |
987 | |
988 | /// Retrieve the generic lambda's template parameter list. |
989 | /// Returns null if the class does not represent a lambda or a generic |
990 | /// lambda. |
991 | TemplateParameterList *getGenericLambdaTemplateParameterList() const; |
992 | |
993 | /// Retrieve the lambda template parameters that were specified explicitly. |
994 | ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const; |
995 | |
996 | LambdaCaptureDefault getLambdaCaptureDefault() const { |
997 | assert(isLambda())((isLambda()) ? static_cast<void> (0) : __assert_fail ( "isLambda()", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 997, __PRETTY_FUNCTION__)); |
998 | return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault); |
999 | } |
1000 | |
1001 | /// For a closure type, retrieve the mapping from captured |
1002 | /// variables and \c this to the non-static data members that store the |
1003 | /// values or references of the captures. |
1004 | /// |
1005 | /// \param Captures Will be populated with the mapping from captured |
1006 | /// variables to the corresponding fields. |
1007 | /// |
1008 | /// \param ThisCapture Will be set to the field declaration for the |
1009 | /// \c this capture. |
1010 | /// |
1011 | /// \note No entries will be added for init-captures, as they do not capture |
1012 | /// variables. |
1013 | void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures, |
1014 | FieldDecl *&ThisCapture) const; |
1015 | |
1016 | using capture_const_iterator = const LambdaCapture *; |
1017 | using capture_const_range = llvm::iterator_range<capture_const_iterator>; |
1018 | |
1019 | capture_const_range captures() const { |
1020 | return capture_const_range(captures_begin(), captures_end()); |
1021 | } |
1022 | |
1023 | capture_const_iterator captures_begin() const { |
1024 | return isLambda() ? getLambdaData().Captures : nullptr; |
1025 | } |
1026 | |
1027 | capture_const_iterator captures_end() const { |
1028 | return isLambda() ? captures_begin() + getLambdaData().NumCaptures |
1029 | : nullptr; |
1030 | } |
1031 | |
1032 | using conversion_iterator = UnresolvedSetIterator; |
1033 | |
1034 | conversion_iterator conversion_begin() const { |
1035 | return data().Conversions.get(getASTContext()).begin(); |
1036 | } |
1037 | |
1038 | conversion_iterator conversion_end() const { |
1039 | return data().Conversions.get(getASTContext()).end(); |
1040 | } |
1041 | |
1042 | /// Removes a conversion function from this class. The conversion |
1043 | /// function must currently be a member of this class. Furthermore, |
1044 | /// this class must currently be in the process of being defined. |
1045 | void removeConversion(const NamedDecl *Old); |
1046 | |
1047 | /// Get all conversion functions visible in current class, |
1048 | /// including conversion function templates. |
1049 | llvm::iterator_range<conversion_iterator> |
1050 | getVisibleConversionFunctions() const; |
1051 | |
1052 | /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]), |
1053 | /// which is a class with no user-declared constructors, no private |
1054 | /// or protected non-static data members, no base classes, and no virtual |
1055 | /// functions (C++ [dcl.init.aggr]p1). |
1056 | bool isAggregate() const { return data().Aggregate; } |
1057 | |
1058 | /// Whether this class has any in-class initializers |
1059 | /// for non-static data members (including those in anonymous unions or |
1060 | /// structs). |
1061 | bool hasInClassInitializer() const { return data().HasInClassInitializer; } |
1062 | |
1063 | /// Whether this class or any of its subobjects has any members of |
1064 | /// reference type which would make value-initialization ill-formed. |
1065 | /// |
1066 | /// Per C++03 [dcl.init]p5: |
1067 | /// - if T is a non-union class type without a user-declared constructor, |
1068 | /// then every non-static data member and base-class component of T is |
1069 | /// value-initialized [...] A program that calls for [...] |
1070 | /// value-initialization of an entity of reference type is ill-formed. |
1071 | bool hasUninitializedReferenceMember() const { |
1072 | return !isUnion() && !hasUserDeclaredConstructor() && |
1073 | data().HasUninitializedReferenceMember; |
1074 | } |
1075 | |
1076 | /// Whether this class is a POD-type (C++ [class]p4) |
1077 | /// |
1078 | /// For purposes of this function a class is POD if it is an aggregate |
1079 | /// that has no non-static non-POD data members, no reference data |
1080 | /// members, no user-defined copy assignment operator and no |
1081 | /// user-defined destructor. |
1082 | /// |
1083 | /// Note that this is the C++ TR1 definition of POD. |
1084 | bool isPOD() const { return data().PlainOldData; } |
1085 | |
1086 | /// True if this class is C-like, without C++-specific features, e.g. |
1087 | /// it contains only public fields, no bases, tag kind is not 'class', etc. |
1088 | bool isCLike() const; |
1089 | |
1090 | /// Determine whether this is an empty class in the sense of |
1091 | /// (C++11 [meta.unary.prop]). |
1092 | /// |
1093 | /// The CXXRecordDecl is a class type, but not a union type, |
1094 | /// with no non-static data members other than bit-fields of length 0, |
1095 | /// no virtual member functions, no virtual base classes, |
1096 | /// and no base class B for which is_empty<B>::value is false. |
1097 | /// |
1098 | /// \note This does NOT include a check for union-ness. |
1099 | bool isEmpty() const { return data().Empty; } |
1100 | |
1101 | bool hasPrivateFields() const { |
1102 | return data().HasPrivateFields; |
1103 | } |
1104 | |
1105 | bool hasProtectedFields() const { |
1106 | return data().HasProtectedFields; |
1107 | } |
1108 | |
1109 | /// Determine whether this class has direct non-static data members. |
1110 | bool hasDirectFields() const { |
1111 | auto &D = data(); |
1112 | return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields; |
1113 | } |
1114 | |
1115 | /// Whether this class is polymorphic (C++ [class.virtual]), |
1116 | /// which means that the class contains or inherits a virtual function. |
1117 | bool isPolymorphic() const { return data().Polymorphic; } |
1118 | |
1119 | /// Determine whether this class has a pure virtual function. |
1120 | /// |
1121 | /// The class is is abstract per (C++ [class.abstract]p2) if it declares |
1122 | /// a pure virtual function or inherits a pure virtual function that is |
1123 | /// not overridden. |
1124 | bool isAbstract() const { return data().Abstract; } |
1125 | |
1126 | /// Determine whether this class is standard-layout per |
1127 | /// C++ [class]p7. |
1128 | bool isStandardLayout() const { return data().IsStandardLayout; } |
1129 | |
1130 | /// Determine whether this class was standard-layout per |
1131 | /// C++11 [class]p7, specifically using the C++11 rules without any DRs. |
1132 | bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; } |
1133 | |
1134 | /// Determine whether this class, or any of its class subobjects, |
1135 | /// contains a mutable field. |
1136 | bool hasMutableFields() const { return data().HasMutableFields; } |
1137 | |
1138 | /// Determine whether this class has any variant members. |
1139 | bool hasVariantMembers() const { return data().HasVariantMembers; } |
1140 | |
1141 | /// Determine whether this class has a trivial default constructor |
1142 | /// (C++11 [class.ctor]p5). |
1143 | bool hasTrivialDefaultConstructor() const { |
1144 | return hasDefaultConstructor() && |
1145 | (data().HasTrivialSpecialMembers & SMF_DefaultConstructor); |
1146 | } |
1147 | |
1148 | /// Determine whether this class has a non-trivial default constructor |
1149 | /// (C++11 [class.ctor]p5). |
1150 | bool hasNonTrivialDefaultConstructor() const { |
1151 | return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) || |
1152 | (needsImplicitDefaultConstructor() && |
1153 | !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor)); |
1154 | } |
1155 | |
1156 | /// Determine whether this class has at least one constexpr constructor |
1157 | /// other than the copy or move constructors. |
1158 | bool hasConstexprNonCopyMoveConstructor() const { |
1159 | return data().HasConstexprNonCopyMoveConstructor || |
1160 | (needsImplicitDefaultConstructor() && |
1161 | defaultedDefaultConstructorIsConstexpr()); |
1162 | } |
1163 | |
1164 | /// Determine whether a defaulted default constructor for this class |
1165 | /// would be constexpr. |
1166 | bool defaultedDefaultConstructorIsConstexpr() const { |
1167 | return data().DefaultedDefaultConstructorIsConstexpr && |
1168 | (!isUnion() || hasInClassInitializer() || !hasVariantMembers() || |
1169 | getASTContext().getLangOpts().CPlusPlus2a); |
1170 | } |
1171 | |
1172 | /// Determine whether this class has a constexpr default constructor. |
1173 | bool hasConstexprDefaultConstructor() const { |
1174 | return data().HasConstexprDefaultConstructor || |
1175 | (needsImplicitDefaultConstructor() && |
1176 | defaultedDefaultConstructorIsConstexpr()); |
1177 | } |
1178 | |
1179 | /// Determine whether this class has a trivial copy constructor |
1180 | /// (C++ [class.copy]p6, C++11 [class.copy]p12) |
1181 | bool hasTrivialCopyConstructor() const { |
1182 | return data().HasTrivialSpecialMembers & SMF_CopyConstructor; |
1183 | } |
1184 | |
1185 | bool hasTrivialCopyConstructorForCall() const { |
1186 | return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor; |
1187 | } |
1188 | |
1189 | /// Determine whether this class has a non-trivial copy constructor |
1190 | /// (C++ [class.copy]p6, C++11 [class.copy]p12) |
1191 | bool hasNonTrivialCopyConstructor() const { |
1192 | return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor || |
1193 | !hasTrivialCopyConstructor(); |
1194 | } |
1195 | |
1196 | bool hasNonTrivialCopyConstructorForCall() const { |
1197 | return (data().DeclaredNonTrivialSpecialMembersForCall & |
1198 | SMF_CopyConstructor) || |
1199 | !hasTrivialCopyConstructorForCall(); |
1200 | } |
1201 | |
1202 | /// Determine whether this class has a trivial move constructor |
1203 | /// (C++11 [class.copy]p12) |
1204 | bool hasTrivialMoveConstructor() const { |
1205 | return hasMoveConstructor() && |
1206 | (data().HasTrivialSpecialMembers & SMF_MoveConstructor); |
1207 | } |
1208 | |
1209 | bool hasTrivialMoveConstructorForCall() const { |
1210 | return hasMoveConstructor() && |
1211 | (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor); |
1212 | } |
1213 | |
1214 | /// Determine whether this class has a non-trivial move constructor |
1215 | /// (C++11 [class.copy]p12) |
1216 | bool hasNonTrivialMoveConstructor() const { |
1217 | return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) || |
1218 | (needsImplicitMoveConstructor() && |
1219 | !(data().HasTrivialSpecialMembers & SMF_MoveConstructor)); |
1220 | } |
1221 | |
1222 | bool hasNonTrivialMoveConstructorForCall() const { |
1223 | return (data().DeclaredNonTrivialSpecialMembersForCall & |
1224 | SMF_MoveConstructor) || |
1225 | (needsImplicitMoveConstructor() && |
1226 | !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor)); |
1227 | } |
1228 | |
1229 | /// Determine whether this class has a trivial copy assignment operator |
1230 | /// (C++ [class.copy]p11, C++11 [class.copy]p25) |
1231 | bool hasTrivialCopyAssignment() const { |
1232 | return data().HasTrivialSpecialMembers & SMF_CopyAssignment; |
1233 | } |
1234 | |
1235 | /// Determine whether this class has a non-trivial copy assignment |
1236 | /// operator (C++ [class.copy]p11, C++11 [class.copy]p25) |
1237 | bool hasNonTrivialCopyAssignment() const { |
1238 | return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment || |
1239 | !hasTrivialCopyAssignment(); |
1240 | } |
1241 | |
1242 | /// Determine whether this class has a trivial move assignment operator |
1243 | /// (C++11 [class.copy]p25) |
1244 | bool hasTrivialMoveAssignment() const { |
1245 | return hasMoveAssignment() && |
1246 | (data().HasTrivialSpecialMembers & SMF_MoveAssignment); |
1247 | } |
1248 | |
1249 | /// Determine whether this class has a non-trivial move assignment |
1250 | /// operator (C++11 [class.copy]p25) |
1251 | bool hasNonTrivialMoveAssignment() const { |
1252 | return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) || |
1253 | (needsImplicitMoveAssignment() && |
1254 | !(data().HasTrivialSpecialMembers & SMF_MoveAssignment)); |
1255 | } |
1256 | |
1257 | /// Determine whether a defaulted default constructor for this class |
1258 | /// would be constexpr. |
1259 | bool defaultedDestructorIsConstexpr() const { |
1260 | return data().DefaultedDestructorIsConstexpr && |
1261 | getASTContext().getLangOpts().CPlusPlus2a; |
1262 | } |
1263 | |
1264 | /// Determine whether this class has a constexpr destructor. |
1265 | bool hasConstexprDestructor() const; |
1266 | |
1267 | /// Determine whether this class has a trivial destructor |
1268 | /// (C++ [class.dtor]p3) |
1269 | bool hasTrivialDestructor() const { |
1270 | return data().HasTrivialSpecialMembers & SMF_Destructor; |
1271 | } |
1272 | |
1273 | bool hasTrivialDestructorForCall() const { |
1274 | return data().HasTrivialSpecialMembersForCall & SMF_Destructor; |
1275 | } |
1276 | |
1277 | /// Determine whether this class has a non-trivial destructor |
1278 | /// (C++ [class.dtor]p3) |
1279 | bool hasNonTrivialDestructor() const { |
1280 | return !(data().HasTrivialSpecialMembers & SMF_Destructor); |
1281 | } |
1282 | |
1283 | bool hasNonTrivialDestructorForCall() const { |
1284 | return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor); |
1285 | } |
1286 | |
1287 | void setHasTrivialSpecialMemberForCall() { |
1288 | data().HasTrivialSpecialMembersForCall = |
1289 | (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor); |
1290 | } |
1291 | |
1292 | /// Determine whether declaring a const variable with this type is ok |
1293 | /// per core issue 253. |
1294 | bool allowConstDefaultInit() const { |
1295 | return !data().HasUninitializedFields || |
1296 | !(data().HasDefaultedDefaultConstructor || |
1297 | needsImplicitDefaultConstructor()); |
1298 | } |
1299 | |
1300 | /// Determine whether this class has a destructor which has no |
1301 | /// semantic effect. |
1302 | /// |
1303 | /// Any such destructor will be trivial, public, defaulted and not deleted, |
1304 | /// and will call only irrelevant destructors. |
1305 | bool hasIrrelevantDestructor() const { |
1306 | return data().HasIrrelevantDestructor; |
1307 | } |
1308 | |
1309 | /// Determine whether this class has a non-literal or/ volatile type |
1310 | /// non-static data member or base class. |
1311 | bool hasNonLiteralTypeFieldsOrBases() const { |
1312 | return data().HasNonLiteralTypeFieldsOrBases; |
1313 | } |
1314 | |
1315 | /// Determine whether this class has a using-declaration that names |
1316 | /// a user-declared base class constructor. |
1317 | bool hasInheritedConstructor() const { |
1318 | return data().HasInheritedConstructor; |
1319 | } |
1320 | |
1321 | /// Determine whether this class has a using-declaration that names |
1322 | /// a base class assignment operator. |
1323 | bool hasInheritedAssignment() const { |
1324 | return data().HasInheritedAssignment; |
1325 | } |
1326 | |
1327 | /// Determine whether this class is considered trivially copyable per |
1328 | /// (C++11 [class]p6). |
1329 | bool isTriviallyCopyable() const; |
1330 | |
1331 | /// Determine whether this class is considered trivial. |
1332 | /// |
1333 | /// C++11 [class]p6: |
1334 | /// "A trivial class is a class that has a trivial default constructor and |
1335 | /// is trivially copyable." |
1336 | bool isTrivial() const { |
1337 | return isTriviallyCopyable() && hasTrivialDefaultConstructor(); |
1338 | } |
1339 | |
1340 | /// Determine whether this class is a literal type. |
1341 | /// |
1342 | /// C++11 [basic.types]p10: |
1343 | /// A class type that has all the following properties: |
1344 | /// - it has a trivial destructor |
1345 | /// - every constructor call and full-expression in the |
1346 | /// brace-or-equal-intializers for non-static data members (if any) is |
1347 | /// a constant expression. |
1348 | /// - it is an aggregate type or has at least one constexpr constructor |
1349 | /// or constructor template that is not a copy or move constructor, and |
1350 | /// - all of its non-static data members and base classes are of literal |
1351 | /// types |
1352 | /// |
1353 | /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by |
1354 | /// treating types with trivial default constructors as literal types. |
1355 | /// |
1356 | /// Only in C++17 and beyond, are lambdas literal types. |
1357 | bool isLiteral() const { |
1358 | ASTContext &Ctx = getASTContext(); |
1359 | return (Ctx.getLangOpts().CPlusPlus2a ? hasConstexprDestructor() |
1360 | : hasTrivialDestructor()) && |
1361 | (!isLambda() || Ctx.getLangOpts().CPlusPlus17) && |
1362 | !hasNonLiteralTypeFieldsOrBases() && |
1363 | (isAggregate() || isLambda() || |
1364 | hasConstexprNonCopyMoveConstructor() || |
1365 | hasTrivialDefaultConstructor()); |
1366 | } |
1367 | |
1368 | /// If this record is an instantiation of a member class, |
1369 | /// retrieves the member class from which it was instantiated. |
1370 | /// |
1371 | /// This routine will return non-null for (non-templated) member |
1372 | /// classes of class templates. For example, given: |
1373 | /// |
1374 | /// \code |
1375 | /// template<typename T> |
1376 | /// struct X { |
1377 | /// struct A { }; |
1378 | /// }; |
1379 | /// \endcode |
1380 | /// |
1381 | /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl |
1382 | /// whose parent is the class template specialization X<int>. For |
1383 | /// this declaration, getInstantiatedFromMemberClass() will return |
1384 | /// the CXXRecordDecl X<T>::A. When a complete definition of |
1385 | /// X<int>::A is required, it will be instantiated from the |
1386 | /// declaration returned by getInstantiatedFromMemberClass(). |
1387 | CXXRecordDecl *getInstantiatedFromMemberClass() const; |
1388 | |
1389 | /// If this class is an instantiation of a member class of a |
1390 | /// class template specialization, retrieves the member specialization |
1391 | /// information. |
1392 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
1393 | |
1394 | /// Specify that this record is an instantiation of the |
1395 | /// member class \p RD. |
1396 | void setInstantiationOfMemberClass(CXXRecordDecl *RD, |
1397 | TemplateSpecializationKind TSK); |
1398 | |
1399 | /// Retrieves the class template that is described by this |
1400 | /// class declaration. |
1401 | /// |
1402 | /// Every class template is represented as a ClassTemplateDecl and a |
1403 | /// CXXRecordDecl. The former contains template properties (such as |
1404 | /// the template parameter lists) while the latter contains the |
1405 | /// actual description of the template's |
1406 | /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the |
1407 | /// CXXRecordDecl that from a ClassTemplateDecl, while |
1408 | /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from |
1409 | /// a CXXRecordDecl. |
1410 | ClassTemplateDecl *getDescribedClassTemplate() const; |
1411 | |
1412 | void setDescribedClassTemplate(ClassTemplateDecl *Template); |
1413 | |
1414 | /// Determine whether this particular class is a specialization or |
1415 | /// instantiation of a class template or member class of a class template, |
1416 | /// and how it was instantiated or specialized. |
1417 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
1418 | |
1419 | /// Set the kind of specialization or template instantiation this is. |
1420 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK); |
1421 | |
1422 | /// Retrieve the record declaration from which this record could be |
1423 | /// instantiated. Returns null if this class is not a template instantiation. |
1424 | const CXXRecordDecl *getTemplateInstantiationPattern() const; |
1425 | |
1426 | CXXRecordDecl *getTemplateInstantiationPattern() { |
1427 | return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this) |
1428 | ->getTemplateInstantiationPattern()); |
1429 | } |
1430 | |
1431 | /// Returns the destructor decl for this class. |
1432 | CXXDestructorDecl *getDestructor() const; |
1433 | |
1434 | /// Returns true if the class destructor, or any implicitly invoked |
1435 | /// destructors are marked noreturn. |
1436 | bool isAnyDestructorNoReturn() const; |
1437 | |
1438 | /// If the class is a local class [class.local], returns |
1439 | /// the enclosing function declaration. |
1440 | const FunctionDecl *isLocalClass() const { |
1441 | if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext())) |
1442 | return RD->isLocalClass(); |
1443 | |
1444 | return dyn_cast<FunctionDecl>(getDeclContext()); |
1445 | } |
1446 | |
1447 | FunctionDecl *isLocalClass() { |
1448 | return const_cast<FunctionDecl*>( |
1449 | const_cast<const CXXRecordDecl*>(this)->isLocalClass()); |
1450 | } |
1451 | |
1452 | /// Determine whether this dependent class is a current instantiation, |
1453 | /// when viewed from within the given context. |
1454 | bool isCurrentInstantiation(const DeclContext *CurContext) const; |
1455 | |
1456 | /// Determine whether this class is derived from the class \p Base. |
1457 | /// |
1458 | /// This routine only determines whether this class is derived from \p Base, |
1459 | /// but does not account for factors that may make a Derived -> Base class |
1460 | /// ill-formed, such as private/protected inheritance or multiple, ambiguous |
1461 | /// base class subobjects. |
1462 | /// |
1463 | /// \param Base the base class we are searching for. |
1464 | /// |
1465 | /// \returns true if this class is derived from Base, false otherwise. |
1466 | bool isDerivedFrom(const CXXRecordDecl *Base) const; |
1467 | |
1468 | /// Determine whether this class is derived from the type \p Base. |
1469 | /// |
1470 | /// This routine only determines whether this class is derived from \p Base, |
1471 | /// but does not account for factors that may make a Derived -> Base class |
1472 | /// ill-formed, such as private/protected inheritance or multiple, ambiguous |
1473 | /// base class subobjects. |
1474 | /// |
1475 | /// \param Base the base class we are searching for. |
1476 | /// |
1477 | /// \param Paths will contain the paths taken from the current class to the |
1478 | /// given \p Base class. |
1479 | /// |
1480 | /// \returns true if this class is derived from \p Base, false otherwise. |
1481 | /// |
1482 | /// \todo add a separate parameter to configure IsDerivedFrom, rather than |
1483 | /// tangling input and output in \p Paths |
1484 | bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const; |
1485 | |
1486 | /// Determine whether this class is virtually derived from |
1487 | /// the class \p Base. |
1488 | /// |
1489 | /// This routine only determines whether this class is virtually |
1490 | /// derived from \p Base, but does not account for factors that may |
1491 | /// make a Derived -> Base class ill-formed, such as |
1492 | /// private/protected inheritance or multiple, ambiguous base class |
1493 | /// subobjects. |
1494 | /// |
1495 | /// \param Base the base class we are searching for. |
1496 | /// |
1497 | /// \returns true if this class is virtually derived from Base, |
1498 | /// false otherwise. |
1499 | bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const; |
1500 | |
1501 | /// Determine whether this class is provably not derived from |
1502 | /// the type \p Base. |
1503 | bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const; |
1504 | |
1505 | /// Function type used by forallBases() as a callback. |
1506 | /// |
1507 | /// \param BaseDefinition the definition of the base class |
1508 | /// |
1509 | /// \returns true if this base matched the search criteria |
1510 | using ForallBasesCallback = |
1511 | llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>; |
1512 | |
1513 | /// Determines if the given callback holds for all the direct |
1514 | /// or indirect base classes of this type. |
1515 | /// |
1516 | /// The class itself does not count as a base class. This routine |
1517 | /// returns false if the class has non-computable base classes. |
1518 | /// |
1519 | /// \param BaseMatches Callback invoked for each (direct or indirect) base |
1520 | /// class of this type, or if \p AllowShortCircuit is true then until a call |
1521 | /// returns false. |
1522 | /// |
1523 | /// \param AllowShortCircuit if false, forces the callback to be called |
1524 | /// for every base class, even if a dependent or non-matching base was |
1525 | /// found. |
1526 | bool forallBases(ForallBasesCallback BaseMatches, |
1527 | bool AllowShortCircuit = true) const; |
1528 | |
1529 | /// Function type used by lookupInBases() to determine whether a |
1530 | /// specific base class subobject matches the lookup criteria. |
1531 | /// |
1532 | /// \param Specifier the base-class specifier that describes the inheritance |
1533 | /// from the base class we are trying to match. |
1534 | /// |
1535 | /// \param Path the current path, from the most-derived class down to the |
1536 | /// base named by the \p Specifier. |
1537 | /// |
1538 | /// \returns true if this base matched the search criteria, false otherwise. |
1539 | using BaseMatchesCallback = |
1540 | llvm::function_ref<bool(const CXXBaseSpecifier *Specifier, |
1541 | CXXBasePath &Path)>; |
1542 | |
1543 | /// Look for entities within the base classes of this C++ class, |
1544 | /// transitively searching all base class subobjects. |
1545 | /// |
1546 | /// This routine uses the callback function \p BaseMatches to find base |
1547 | /// classes meeting some search criteria, walking all base class subobjects |
1548 | /// and populating the given \p Paths structure with the paths through the |
1549 | /// inheritance hierarchy that resulted in a match. On a successful search, |
1550 | /// the \p Paths structure can be queried to retrieve the matching paths and |
1551 | /// to determine if there were any ambiguities. |
1552 | /// |
1553 | /// \param BaseMatches callback function used to determine whether a given |
1554 | /// base matches the user-defined search criteria. |
1555 | /// |
1556 | /// \param Paths used to record the paths from this class to its base class |
1557 | /// subobjects that match the search criteria. |
1558 | /// |
1559 | /// \param LookupInDependent can be set to true to extend the search to |
1560 | /// dependent base classes. |
1561 | /// |
1562 | /// \returns true if there exists any path from this class to a base class |
1563 | /// subobject that matches the search criteria. |
1564 | bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, |
1565 | bool LookupInDependent = false) const; |
1566 | |
1567 | /// Base-class lookup callback that determines whether the given |
1568 | /// base class specifier refers to a specific class declaration. |
1569 | /// |
1570 | /// This callback can be used with \c lookupInBases() to determine whether |
1571 | /// a given derived class has is a base class subobject of a particular type. |
1572 | /// The base record pointer should refer to the canonical CXXRecordDecl of the |
1573 | /// base class that we are searching for. |
1574 | static bool FindBaseClass(const CXXBaseSpecifier *Specifier, |
1575 | CXXBasePath &Path, const CXXRecordDecl *BaseRecord); |
1576 | |
1577 | /// Base-class lookup callback that determines whether the |
1578 | /// given base class specifier refers to a specific class |
1579 | /// declaration and describes virtual derivation. |
1580 | /// |
1581 | /// This callback can be used with \c lookupInBases() to determine |
1582 | /// whether a given derived class has is a virtual base class |
1583 | /// subobject of a particular type. The base record pointer should |
1584 | /// refer to the canonical CXXRecordDecl of the base class that we |
1585 | /// are searching for. |
1586 | static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier, |
1587 | CXXBasePath &Path, |
1588 | const CXXRecordDecl *BaseRecord); |
1589 | |
1590 | /// Base-class lookup callback that determines whether there exists |
1591 | /// a tag with the given name. |
1592 | /// |
1593 | /// This callback can be used with \c lookupInBases() to find tag members |
1594 | /// of the given name within a C++ class hierarchy. |
1595 | static bool FindTagMember(const CXXBaseSpecifier *Specifier, |
1596 | CXXBasePath &Path, DeclarationName Name); |
1597 | |
1598 | /// Base-class lookup callback that determines whether there exists |
1599 | /// a member with the given name. |
1600 | /// |
1601 | /// This callback can be used with \c lookupInBases() to find members |
1602 | /// of the given name within a C++ class hierarchy. |
1603 | static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier, |
1604 | CXXBasePath &Path, DeclarationName Name); |
1605 | |
1606 | /// Base-class lookup callback that determines whether there exists |
1607 | /// a member with the given name. |
1608 | /// |
1609 | /// This callback can be used with \c lookupInBases() to find members |
1610 | /// of the given name within a C++ class hierarchy, including dependent |
1611 | /// classes. |
1612 | static bool |
1613 | FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier, |
1614 | CXXBasePath &Path, DeclarationName Name); |
1615 | |
1616 | /// Base-class lookup callback that determines whether there exists |
1617 | /// an OpenMP declare reduction member with the given name. |
1618 | /// |
1619 | /// This callback can be used with \c lookupInBases() to find members |
1620 | /// of the given name within a C++ class hierarchy. |
1621 | static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier, |
1622 | CXXBasePath &Path, DeclarationName Name); |
1623 | |
1624 | /// Base-class lookup callback that determines whether there exists |
1625 | /// an OpenMP declare mapper member with the given name. |
1626 | /// |
1627 | /// This callback can be used with \c lookupInBases() to find members |
1628 | /// of the given name within a C++ class hierarchy. |
1629 | static bool FindOMPMapperMember(const CXXBaseSpecifier *Specifier, |
1630 | CXXBasePath &Path, DeclarationName Name); |
1631 | |
1632 | /// Base-class lookup callback that determines whether there exists |
1633 | /// a member with the given name that can be used in a nested-name-specifier. |
1634 | /// |
1635 | /// This callback can be used with \c lookupInBases() to find members of |
1636 | /// the given name within a C++ class hierarchy that can occur within |
1637 | /// nested-name-specifiers. |
1638 | static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier, |
1639 | CXXBasePath &Path, |
1640 | DeclarationName Name); |
1641 | |
1642 | /// Retrieve the final overriders for each virtual member |
1643 | /// function in the class hierarchy where this class is the |
1644 | /// most-derived class in the class hierarchy. |
1645 | void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const; |
1646 | |
1647 | /// Get the indirect primary bases for this class. |
1648 | void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const; |
1649 | |
1650 | /// Performs an imprecise lookup of a dependent name in this class. |
1651 | /// |
1652 | /// This function does not follow strict semantic rules and should be used |
1653 | /// only when lookup rules can be relaxed, e.g. indexing. |
1654 | std::vector<const NamedDecl *> |
1655 | lookupDependentName(const DeclarationName &Name, |
1656 | llvm::function_ref<bool(const NamedDecl *ND)> Filter); |
1657 | |
1658 | /// Renders and displays an inheritance diagram |
1659 | /// for this C++ class and all of its base classes (transitively) using |
1660 | /// GraphViz. |
1661 | void viewInheritance(ASTContext& Context) const; |
1662 | |
1663 | /// Calculates the access of a decl that is reached |
1664 | /// along a path. |
1665 | static AccessSpecifier MergeAccess(AccessSpecifier PathAccess, |
1666 | AccessSpecifier DeclAccess) { |
1667 | assert(DeclAccess != AS_none)((DeclAccess != AS_none) ? static_cast<void> (0) : __assert_fail ("DeclAccess != AS_none", "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 1667, __PRETTY_FUNCTION__)); |
1668 | if (DeclAccess == AS_private) return AS_none; |
1669 | return (PathAccess > DeclAccess ? PathAccess : DeclAccess); |
1670 | } |
1671 | |
1672 | /// Indicates that the declaration of a defaulted or deleted special |
1673 | /// member function is now complete. |
1674 | void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD); |
1675 | |
1676 | void setTrivialForCallFlags(CXXMethodDecl *MD); |
1677 | |
1678 | /// Indicates that the definition of this class is now complete. |
1679 | void completeDefinition() override; |
1680 | |
1681 | /// Indicates that the definition of this class is now complete, |
1682 | /// and provides a final overrider map to help determine |
1683 | /// |
1684 | /// \param FinalOverriders The final overrider map for this class, which can |
1685 | /// be provided as an optimization for abstract-class checking. If NULL, |
1686 | /// final overriders will be computed if they are needed to complete the |
1687 | /// definition. |
1688 | void completeDefinition(CXXFinalOverriderMap *FinalOverriders); |
1689 | |
1690 | /// Determine whether this class may end up being abstract, even though |
1691 | /// it is not yet known to be abstract. |
1692 | /// |
1693 | /// \returns true if this class is not known to be abstract but has any |
1694 | /// base classes that are abstract. In this case, \c completeDefinition() |
1695 | /// will need to compute final overriders to determine whether the class is |
1696 | /// actually abstract. |
1697 | bool mayBeAbstract() const; |
1698 | |
1699 | /// If this is the closure type of a lambda expression, retrieve the |
1700 | /// number to be used for name mangling in the Itanium C++ ABI. |
1701 | /// |
1702 | /// Zero indicates that this closure type has internal linkage, so the |
1703 | /// mangling number does not matter, while a non-zero value indicates which |
1704 | /// lambda expression this is in this particular context. |
1705 | unsigned getLambdaManglingNumber() const { |
1706 | assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast <void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 1706, __PRETTY_FUNCTION__)); |
1707 | return getLambdaData().ManglingNumber; |
1708 | } |
1709 | |
1710 | /// The lambda is known to has internal linkage no matter whether it has name |
1711 | /// mangling number. |
1712 | bool hasKnownLambdaInternalLinkage() const { |
1713 | assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast <void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 1713, __PRETTY_FUNCTION__)); |
1714 | return getLambdaData().HasKnownInternalLinkage; |
1715 | } |
1716 | |
1717 | /// Retrieve the declaration that provides additional context for a |
1718 | /// lambda, when the normal declaration context is not specific enough. |
1719 | /// |
1720 | /// Certain contexts (default arguments of in-class function parameters and |
1721 | /// the initializers of data members) have separate name mangling rules for |
1722 | /// lambdas within the Itanium C++ ABI. For these cases, this routine provides |
1723 | /// the declaration in which the lambda occurs, e.g., the function parameter |
1724 | /// or the non-static data member. Otherwise, it returns NULL to imply that |
1725 | /// the declaration context suffices. |
1726 | Decl *getLambdaContextDecl() const; |
1727 | |
1728 | /// Set the mangling number and context declaration for a lambda |
1729 | /// class. |
1730 | void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl, |
1731 | bool HasKnownInternalLinkage = false) { |
1732 | assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast <void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 1732, __PRETTY_FUNCTION__)); |
1733 | getLambdaData().ManglingNumber = ManglingNumber; |
1734 | getLambdaData().ContextDecl = ContextDecl; |
1735 | getLambdaData().HasKnownInternalLinkage = HasKnownInternalLinkage; |
1736 | } |
1737 | |
1738 | /// Returns the inheritance model used for this record. |
1739 | MSInheritanceModel getMSInheritanceModel() const; |
1740 | |
1741 | /// Calculate what the inheritance model would be for this class. |
1742 | MSInheritanceModel calculateInheritanceModel() const; |
1743 | |
1744 | /// In the Microsoft C++ ABI, use zero for the field offset of a null data |
1745 | /// member pointer if we can guarantee that zero is not a valid field offset, |
1746 | /// or if the member pointer has multiple fields. Polymorphic classes have a |
1747 | /// vfptr at offset zero, so we can use zero for null. If there are multiple |
1748 | /// fields, we can use zero even if it is a valid field offset because |
1749 | /// null-ness testing will check the other fields. |
1750 | bool nullFieldOffsetIsZero() const; |
1751 | |
1752 | /// Controls when vtordisps will be emitted if this record is used as a |
1753 | /// virtual base. |
1754 | MSVtorDispMode getMSVtorDispMode() const; |
1755 | |
1756 | /// Determine whether this lambda expression was known to be dependent |
1757 | /// at the time it was created, even if its context does not appear to be |
1758 | /// dependent. |
1759 | /// |
1760 | /// This flag is a workaround for an issue with parsing, where default |
1761 | /// arguments are parsed before their enclosing function declarations have |
1762 | /// been created. This means that any lambda expressions within those |
1763 | /// default arguments will have as their DeclContext the context enclosing |
1764 | /// the function declaration, which may be non-dependent even when the |
1765 | /// function declaration itself is dependent. This flag indicates when we |
1766 | /// know that the lambda is dependent despite that. |
1767 | bool isDependentLambda() const { |
1768 | return isLambda() && getLambdaData().Dependent; |
1769 | } |
1770 | |
1771 | TypeSourceInfo *getLambdaTypeInfo() const { |
1772 | return getLambdaData().MethodTyInfo; |
1773 | } |
1774 | |
1775 | // Determine whether this type is an Interface Like type for |
1776 | // __interface inheritance purposes. |
1777 | bool isInterfaceLike() const; |
1778 | |
1779 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1780 | static bool classofKind(Kind K) { |
1781 | return K >= firstCXXRecord && K <= lastCXXRecord; |
1782 | } |
1783 | }; |
1784 | |
1785 | /// Store information needed for an explicit specifier. |
1786 | /// Used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl. |
1787 | class ExplicitSpecifier { |
1788 | llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{ |
1789 | nullptr, ExplicitSpecKind::ResolvedFalse}; |
1790 | |
1791 | public: |
1792 | ExplicitSpecifier() = default; |
1793 | ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind) |
1794 | : ExplicitSpec(Expression, Kind) {} |
1795 | ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); } |
1796 | const Expr *getExpr() const { return ExplicitSpec.getPointer(); } |
1797 | Expr *getExpr() { return ExplicitSpec.getPointer(); } |
1798 | |
1799 | /// Determine if the declaration had an explicit specifier of any kind. |
1800 | bool isSpecified() const { |
1801 | return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse || |
1802 | ExplicitSpec.getPointer(); |
1803 | } |
1804 | |
1805 | /// Check for equivalence of explicit specifiers. |
1806 | /// \return true if the explicit specifier are equivalent, false otherwise. |
1807 | bool isEquivalent(const ExplicitSpecifier Other) const; |
1808 | /// Determine whether this specifier is known to correspond to an explicit |
1809 | /// declaration. Returns false if the specifier is absent or has an |
1810 | /// expression that is value-dependent or evaluates to false. |
1811 | bool isExplicit() const { |
1812 | return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue; |
1813 | } |
1814 | /// Determine if the explicit specifier is invalid. |
1815 | /// This state occurs after a substitution failures. |
1816 | bool isInvalid() const { |
1817 | return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved && |
1818 | !ExplicitSpec.getPointer(); |
1819 | } |
1820 | void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); } |
1821 | void setExpr(Expr *E) { ExplicitSpec.setPointer(E); } |
1822 | // Retrieve the explicit specifier in the given declaration, if any. |
1823 | static ExplicitSpecifier getFromDecl(FunctionDecl *Function); |
1824 | static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) { |
1825 | return getFromDecl(const_cast<FunctionDecl *>(Function)); |
1826 | } |
1827 | static ExplicitSpecifier Invalid() { |
1828 | return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved); |
1829 | } |
1830 | }; |
1831 | |
1832 | /// Represents a C++ deduction guide declaration. |
1833 | /// |
1834 | /// \code |
1835 | /// template<typename T> struct A { A(); A(T); }; |
1836 | /// A() -> A<int>; |
1837 | /// \endcode |
1838 | /// |
1839 | /// In this example, there will be an explicit deduction guide from the |
1840 | /// second line, and implicit deduction guide templates synthesized from |
1841 | /// the constructors of \c A. |
1842 | class CXXDeductionGuideDecl : public FunctionDecl { |
1843 | void anchor() override; |
1844 | |
1845 | private: |
1846 | CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1847 | ExplicitSpecifier ES, |
1848 | const DeclarationNameInfo &NameInfo, QualType T, |
1849 | TypeSourceInfo *TInfo, SourceLocation EndLocation) |
1850 | : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo, |
1851 | SC_None, false, CSK_unspecified), |
1852 | ExplicitSpec(ES) { |
1853 | if (EndLocation.isValid()) |
1854 | setRangeEnd(EndLocation); |
1855 | setIsCopyDeductionCandidate(false); |
1856 | } |
1857 | |
1858 | ExplicitSpecifier ExplicitSpec; |
1859 | void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; } |
1860 | |
1861 | public: |
1862 | friend class ASTDeclReader; |
1863 | friend class ASTDeclWriter; |
1864 | |
1865 | static CXXDeductionGuideDecl * |
1866 | Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1867 | ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, |
1868 | TypeSourceInfo *TInfo, SourceLocation EndLocation); |
1869 | |
1870 | static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1871 | |
1872 | ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; } |
1873 | const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; } |
1874 | |
1875 | /// Return true if the declartion is already resolved to be explicit. |
1876 | bool isExplicit() const { return ExplicitSpec.isExplicit(); } |
1877 | |
1878 | /// Get the template for which this guide performs deduction. |
1879 | TemplateDecl *getDeducedTemplate() const { |
1880 | return getDeclName().getCXXDeductionGuideTemplate(); |
1881 | } |
1882 | |
1883 | void setIsCopyDeductionCandidate(bool isCDC = true) { |
1884 | FunctionDeclBits.IsCopyDeductionCandidate = isCDC; |
1885 | } |
1886 | |
1887 | bool isCopyDeductionCandidate() const { |
1888 | return FunctionDeclBits.IsCopyDeductionCandidate; |
1889 | } |
1890 | |
1891 | // Implement isa/cast/dyncast/etc. |
1892 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1893 | static bool classofKind(Kind K) { return K == CXXDeductionGuide; } |
1894 | }; |
1895 | |
1896 | /// Represents a static or instance method of a struct/union/class. |
1897 | /// |
1898 | /// In the terminology of the C++ Standard, these are the (static and |
1899 | /// non-static) member functions, whether virtual or not. |
1900 | class CXXMethodDecl : public FunctionDecl { |
1901 | void anchor() override; |
1902 | |
1903 | protected: |
1904 | CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD, |
1905 | SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, |
1906 | QualType T, TypeSourceInfo *TInfo, StorageClass SC, |
1907 | bool isInline, ConstexprSpecKind ConstexprKind, |
1908 | SourceLocation EndLocation, |
1909 | Expr *TrailingRequiresClause = nullptr) |
1910 | : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline, |
1911 | ConstexprKind, TrailingRequiresClause) { |
1912 | if (EndLocation.isValid()) |
1913 | setRangeEnd(EndLocation); |
1914 | } |
1915 | |
1916 | public: |
1917 | static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD, |
1918 | SourceLocation StartLoc, |
1919 | const DeclarationNameInfo &NameInfo, QualType T, |
1920 | TypeSourceInfo *TInfo, StorageClass SC, |
1921 | bool isInline, ConstexprSpecKind ConstexprKind, |
1922 | SourceLocation EndLocation, |
1923 | Expr *TrailingRequiresClause = nullptr); |
1924 | |
1925 | static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1926 | |
1927 | bool isStatic() const; |
1928 | bool isInstance() const { return !isStatic(); } |
1929 | |
1930 | /// Returns true if the given operator is implicitly static in a record |
1931 | /// context. |
1932 | static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) { |
1933 | // [class.free]p1: |
1934 | // Any allocation function for a class T is a static member |
1935 | // (even if not explicitly declared static). |
1936 | // [class.free]p6 Any deallocation function for a class X is a static member |
1937 | // (even if not explicitly declared static). |
1938 | return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete || |
1939 | OOK == OO_Array_Delete; |
1940 | } |
1941 | |
1942 | bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); } |
1943 | bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); } |
1944 | |
1945 | bool isVirtual() const { |
1946 | CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl(); |
1947 | |
1948 | // Member function is virtual if it is marked explicitly so, or if it is |
1949 | // declared in __interface -- then it is automatically pure virtual. |
1950 | if (CD->isVirtualAsWritten() || CD->isPure()) |
1951 | return true; |
1952 | |
1953 | return CD->size_overridden_methods() != 0; |
1954 | } |
1955 | |
1956 | /// If it's possible to devirtualize a call to this method, return the called |
1957 | /// function. Otherwise, return null. |
1958 | |
1959 | /// \param Base The object on which this virtual function is called. |
1960 | /// \param IsAppleKext True if we are compiling for Apple kext. |
1961 | CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext); |
1962 | |
1963 | const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, |
1964 | bool IsAppleKext) const { |
1965 | return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod( |
1966 | Base, IsAppleKext); |
1967 | } |
1968 | |
1969 | /// Determine whether this is a usual deallocation function (C++ |
1970 | /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or |
1971 | /// delete[] operator with a particular signature. Populates \p PreventedBy |
1972 | /// with the declarations of the functions of the same kind if they were the |
1973 | /// reason for this function returning false. This is used by |
1974 | /// Sema::isUsualDeallocationFunction to reconsider the answer based on the |
1975 | /// context. |
1976 | bool isUsualDeallocationFunction( |
1977 | SmallVectorImpl<const FunctionDecl *> &PreventedBy) const; |
1978 | |
1979 | /// Determine whether this is a copy-assignment operator, regardless |
1980 | /// of whether it was declared implicitly or explicitly. |
1981 | bool isCopyAssignmentOperator() const; |
1982 | |
1983 | /// Determine whether this is a move assignment operator. |
1984 | bool isMoveAssignmentOperator() const; |
1985 | |
1986 | CXXMethodDecl *getCanonicalDecl() override { |
1987 | return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl()); |
1988 | } |
1989 | const CXXMethodDecl *getCanonicalDecl() const { |
1990 | return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl(); |
1991 | } |
1992 | |
1993 | CXXMethodDecl *getMostRecentDecl() { |
1994 | return cast<CXXMethodDecl>( |
1995 | static_cast<FunctionDecl *>(this)->getMostRecentDecl()); |
1996 | } |
1997 | const CXXMethodDecl *getMostRecentDecl() const { |
1998 | return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl(); |
1999 | } |
2000 | |
2001 | void addOverriddenMethod(const CXXMethodDecl *MD); |
2002 | |
2003 | using method_iterator = const CXXMethodDecl *const *; |
2004 | |
2005 | method_iterator begin_overridden_methods() const; |
2006 | method_iterator end_overridden_methods() const; |
2007 | unsigned size_overridden_methods() const; |
2008 | |
2009 | using overridden_method_range= ASTContext::overridden_method_range; |
2010 | |
2011 | overridden_method_range overridden_methods() const; |
2012 | |
2013 | /// Return the parent of this method declaration, which |
2014 | /// is the class in which this method is defined. |
2015 | const CXXRecordDecl *getParent() const { |
2016 | return cast<CXXRecordDecl>(FunctionDecl::getParent()); |
2017 | } |
2018 | |
2019 | /// Return the parent of this method declaration, which |
2020 | /// is the class in which this method is defined. |
2021 | CXXRecordDecl *getParent() { |
2022 | return const_cast<CXXRecordDecl *>( |
2023 | cast<CXXRecordDecl>(FunctionDecl::getParent())); |
2024 | } |
2025 | |
2026 | /// Return the type of the \c this pointer. |
2027 | /// |
2028 | /// Should only be called for instance (i.e., non-static) methods. Note |
2029 | /// that for the call operator of a lambda closure type, this returns the |
2030 | /// desugared 'this' type (a pointer to the closure type), not the captured |
2031 | /// 'this' type. |
2032 | QualType getThisType() const; |
2033 | |
2034 | /// Return the type of the object pointed by \c this. |
2035 | /// |
2036 | /// See getThisType() for usage restriction. |
2037 | QualType getThisObjectType() const; |
2038 | |
2039 | static QualType getThisType(const FunctionProtoType *FPT, |
2040 | const CXXRecordDecl *Decl); |
2041 | |
2042 | static QualType getThisObjectType(const FunctionProtoType *FPT, |
2043 | const CXXRecordDecl *Decl); |
2044 | |
2045 | Qualifiers getMethodQualifiers() const { |
2046 | return getType()->castAs<FunctionProtoType>()->getMethodQuals(); |
2047 | } |
2048 | |
2049 | /// Retrieve the ref-qualifier associated with this method. |
2050 | /// |
2051 | /// In the following example, \c f() has an lvalue ref-qualifier, \c g() |
2052 | /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier. |
2053 | /// @code |
2054 | /// struct X { |
2055 | /// void f() &; |
2056 | /// void g() &&; |
2057 | /// void h(); |
2058 | /// }; |
2059 | /// @endcode |
2060 | RefQualifierKind getRefQualifier() const { |
2061 | return getType()->castAs<FunctionProtoType>()->getRefQualifier(); |
2062 | } |
2063 | |
2064 | bool hasInlineBody() const; |
2065 | |
2066 | /// Determine whether this is a lambda closure type's static member |
2067 | /// function that is used for the result of the lambda's conversion to |
2068 | /// function pointer (for a lambda with no captures). |
2069 | /// |
2070 | /// The function itself, if used, will have a placeholder body that will be |
2071 | /// supplied by IR generation to either forward to the function call operator |
2072 | /// or clone the function call operator. |
2073 | bool isLambdaStaticInvoker() const; |
2074 | |
2075 | /// Find the method in \p RD that corresponds to this one. |
2076 | /// |
2077 | /// Find if \p RD or one of the classes it inherits from override this method. |
2078 | /// If so, return it. \p RD is assumed to be a subclass of the class defining |
2079 | /// this method (or be the class itself), unless \p MayBeBase is set to true. |
2080 | CXXMethodDecl * |
2081 | getCorrespondingMethodInClass(const CXXRecordDecl *RD, |
2082 | bool MayBeBase = false); |
2083 | |
2084 | const CXXMethodDecl * |
2085 | getCorrespondingMethodInClass(const CXXRecordDecl *RD, |
2086 | bool MayBeBase = false) const { |
2087 | return const_cast<CXXMethodDecl *>(this) |
2088 | ->getCorrespondingMethodInClass(RD, MayBeBase); |
2089 | } |
2090 | |
2091 | /// Find if \p RD declares a function that overrides this function, and if so, |
2092 | /// return it. Does not search base classes. |
2093 | CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, |
2094 | bool MayBeBase = false); |
2095 | const CXXMethodDecl * |
2096 | getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, |
2097 | bool MayBeBase = false) const { |
2098 | return const_cast<CXXMethodDecl *>(this) |
2099 | ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase); |
2100 | } |
2101 | |
2102 | // Implement isa/cast/dyncast/etc. |
2103 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2104 | static bool classofKind(Kind K) { |
2105 | return K >= firstCXXMethod && K <= lastCXXMethod; |
2106 | } |
2107 | }; |
2108 | |
2109 | /// Represents a C++ base or member initializer. |
2110 | /// |
2111 | /// This is part of a constructor initializer that |
2112 | /// initializes one non-static member variable or one base class. For |
2113 | /// example, in the following, both 'A(a)' and 'f(3.14159)' are member |
2114 | /// initializers: |
2115 | /// |
2116 | /// \code |
2117 | /// class A { }; |
2118 | /// class B : public A { |
2119 | /// float f; |
2120 | /// public: |
2121 | /// B(A& a) : A(a), f(3.14159) { } |
2122 | /// }; |
2123 | /// \endcode |
2124 | class CXXCtorInitializer final { |
2125 | /// Either the base class name/delegating constructor type (stored as |
2126 | /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field |
2127 | /// (IndirectFieldDecl*) being initialized. |
2128 | llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *> |
2129 | Initializee; |
2130 | |
2131 | /// The source location for the field name or, for a base initializer |
2132 | /// pack expansion, the location of the ellipsis. |
2133 | /// |
2134 | /// In the case of a delegating |
2135 | /// constructor, it will still include the type's source location as the |
2136 | /// Initializee points to the CXXConstructorDecl (to allow loop detection). |
2137 | SourceLocation MemberOrEllipsisLocation; |
2138 | |
2139 | /// The argument used to initialize the base or member, which may |
2140 | /// end up constructing an object (when multiple arguments are involved). |
2141 | Stmt *Init; |
2142 | |
2143 | /// Location of the left paren of the ctor-initializer. |
2144 | SourceLocation LParenLoc; |
2145 | |
2146 | /// Location of the right paren of the ctor-initializer. |
2147 | SourceLocation RParenLoc; |
2148 | |
2149 | /// If the initializee is a type, whether that type makes this |
2150 | /// a delegating initialization. |
2151 | unsigned IsDelegating : 1; |
2152 | |
2153 | /// If the initializer is a base initializer, this keeps track |
2154 | /// of whether the base is virtual or not. |
2155 | unsigned IsVirtual : 1; |
2156 | |
2157 | /// Whether or not the initializer is explicitly written |
2158 | /// in the sources. |
2159 | unsigned IsWritten : 1; |
2160 | |
2161 | /// If IsWritten is true, then this number keeps track of the textual order |
2162 | /// of this initializer in the original sources, counting from 0. |
2163 | unsigned SourceOrder : 13; |
2164 | |
2165 | public: |
2166 | /// Creates a new base-class initializer. |
2167 | explicit |
2168 | CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual, |
2169 | SourceLocation L, Expr *Init, SourceLocation R, |
2170 | SourceLocation EllipsisLoc); |
2171 | |
2172 | /// Creates a new member initializer. |
2173 | explicit |
2174 | CXXCtorInitializer(ASTContext &Context, FieldDecl *Member, |
2175 | SourceLocation MemberLoc, SourceLocation L, Expr *Init, |
2176 | SourceLocation R); |
2177 | |
2178 | /// Creates a new anonymous field initializer. |
2179 | explicit |
2180 | CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member, |
2181 | SourceLocation MemberLoc, SourceLocation L, Expr *Init, |
2182 | SourceLocation R); |
2183 | |
2184 | /// Creates a new delegating initializer. |
2185 | explicit |
2186 | CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, |
2187 | SourceLocation L, Expr *Init, SourceLocation R); |
2188 | |
2189 | /// \return Unique reproducible object identifier. |
2190 | int64_t getID(const ASTContext &Context) const; |
2191 | |
2192 | /// Determine whether this initializer is initializing a base class. |
2193 | bool isBaseInitializer() const { |
2194 | return Initializee.is<TypeSourceInfo*>() && !IsDelegating; |
2195 | } |
2196 | |
2197 | /// Determine whether this initializer is initializing a non-static |
2198 | /// data member. |
2199 | bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); } |
2200 | |
2201 | bool isAnyMemberInitializer() const { |
2202 | return isMemberInitializer() || isIndirectMemberInitializer(); |
2203 | } |
2204 | |
2205 | bool isIndirectMemberInitializer() const { |
2206 | return Initializee.is<IndirectFieldDecl*>(); |
2207 | } |
2208 | |
2209 | /// Determine whether this initializer is an implicit initializer |
2210 | /// generated for a field with an initializer defined on the member |
2211 | /// declaration. |
2212 | /// |
2213 | /// In-class member initializers (also known as "non-static data member |
2214 | /// initializations", NSDMIs) were introduced in C++11. |
2215 | bool isInClassMemberInitializer() const { |
2216 | return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass; |
2217 | } |
2218 | |
2219 | /// Determine whether this initializer is creating a delegating |
2220 | /// constructor. |
2221 | bool isDelegatingInitializer() const { |
2222 | return Initializee.is<TypeSourceInfo*>() && IsDelegating; |
2223 | } |
2224 | |
2225 | /// Determine whether this initializer is a pack expansion. |
2226 | bool isPackExpansion() const { |
2227 | return isBaseInitializer() && MemberOrEllipsisLocation.isValid(); |
2228 | } |
2229 | |
2230 | // For a pack expansion, returns the location of the ellipsis. |
2231 | SourceLocation getEllipsisLoc() const { |
2232 | assert(isPackExpansion() && "Initializer is not a pack expansion")((isPackExpansion() && "Initializer is not a pack expansion" ) ? static_cast<void> (0) : __assert_fail ("isPackExpansion() && \"Initializer is not a pack expansion\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2232, __PRETTY_FUNCTION__)); |
2233 | return MemberOrEllipsisLocation; |
2234 | } |
2235 | |
2236 | /// If this is a base class initializer, returns the type of the |
2237 | /// base class with location information. Otherwise, returns an NULL |
2238 | /// type location. |
2239 | TypeLoc getBaseClassLoc() const; |
2240 | |
2241 | /// If this is a base class initializer, returns the type of the base class. |
2242 | /// Otherwise, returns null. |
2243 | const Type *getBaseClass() const; |
2244 | |
2245 | /// Returns whether the base is virtual or not. |
2246 | bool isBaseVirtual() const { |
2247 | assert(isBaseInitializer() && "Must call this on base initializer!")((isBaseInitializer() && "Must call this on base initializer!" ) ? static_cast<void> (0) : __assert_fail ("isBaseInitializer() && \"Must call this on base initializer!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2247, __PRETTY_FUNCTION__)); |
2248 | |
2249 | return IsVirtual; |
2250 | } |
2251 | |
2252 | /// Returns the declarator information for a base class or delegating |
2253 | /// initializer. |
2254 | TypeSourceInfo *getTypeSourceInfo() const { |
2255 | return Initializee.dyn_cast<TypeSourceInfo *>(); |
2256 | } |
2257 | |
2258 | /// If this is a member initializer, returns the declaration of the |
2259 | /// non-static data member being initialized. Otherwise, returns null. |
2260 | FieldDecl *getMember() const { |
2261 | if (isMemberInitializer()) |
2262 | return Initializee.get<FieldDecl*>(); |
2263 | return nullptr; |
2264 | } |
2265 | |
2266 | FieldDecl *getAnyMember() const { |
2267 | if (isMemberInitializer()) |
2268 | return Initializee.get<FieldDecl*>(); |
2269 | if (isIndirectMemberInitializer()) |
2270 | return Initializee.get<IndirectFieldDecl*>()->getAnonField(); |
2271 | return nullptr; |
2272 | } |
2273 | |
2274 | IndirectFieldDecl *getIndirectMember() const { |
2275 | if (isIndirectMemberInitializer()) |
2276 | return Initializee.get<IndirectFieldDecl*>(); |
2277 | return nullptr; |
2278 | } |
2279 | |
2280 | SourceLocation getMemberLocation() const { |
2281 | return MemberOrEllipsisLocation; |
2282 | } |
2283 | |
2284 | /// Determine the source location of the initializer. |
2285 | SourceLocation getSourceLocation() const; |
2286 | |
2287 | /// Determine the source range covering the entire initializer. |
2288 | SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)); |
2289 | |
2290 | /// Determine whether this initializer is explicitly written |
2291 | /// in the source code. |
2292 | bool isWritten() const { return IsWritten; } |
2293 | |
2294 | /// Return the source position of the initializer, counting from 0. |
2295 | /// If the initializer was implicit, -1 is returned. |
2296 | int getSourceOrder() const { |
2297 | return IsWritten ? static_cast<int>(SourceOrder) : -1; |
2298 | } |
2299 | |
2300 | /// Set the source order of this initializer. |
2301 | /// |
2302 | /// This can only be called once for each initializer; it cannot be called |
2303 | /// on an initializer having a positive number of (implicit) array indices. |
2304 | /// |
2305 | /// This assumes that the initializer was written in the source code, and |
2306 | /// ensures that isWritten() returns true. |
2307 | void setSourceOrder(int Pos) { |
2308 | assert(!IsWritten &&((!IsWritten && "setSourceOrder() used on implicit initializer" ) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2309, __PRETTY_FUNCTION__)) |
2309 | "setSourceOrder() used on implicit initializer")((!IsWritten && "setSourceOrder() used on implicit initializer" ) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2309, __PRETTY_FUNCTION__)); |
2310 | assert(SourceOrder == 0 &&((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer" ) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2311, __PRETTY_FUNCTION__)) |
2311 | "calling twice setSourceOrder() on the same initializer")((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer" ) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2311, __PRETTY_FUNCTION__)); |
2312 | assert(Pos >= 0 &&((Pos >= 0 && "setSourceOrder() used to make an initializer implicit" ) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2313, __PRETTY_FUNCTION__)) |
2313 | "setSourceOrder() used to make an initializer implicit")((Pos >= 0 && "setSourceOrder() used to make an initializer implicit" ) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2313, __PRETTY_FUNCTION__)); |
2314 | IsWritten = true; |
2315 | SourceOrder = static_cast<unsigned>(Pos); |
2316 | } |
2317 | |
2318 | SourceLocation getLParenLoc() const { return LParenLoc; } |
2319 | SourceLocation getRParenLoc() const { return RParenLoc; } |
2320 | |
2321 | /// Get the initializer. |
2322 | Expr *getInit() const { return static_cast<Expr *>(Init); } |
2323 | }; |
2324 | |
2325 | /// Description of a constructor that was inherited from a base class. |
2326 | class InheritedConstructor { |
2327 | ConstructorUsingShadowDecl *Shadow = nullptr; |
2328 | CXXConstructorDecl *BaseCtor = nullptr; |
2329 | |
2330 | public: |
2331 | InheritedConstructor() = default; |
2332 | InheritedConstructor(ConstructorUsingShadowDecl *Shadow, |
2333 | CXXConstructorDecl *BaseCtor) |
2334 | : Shadow(Shadow), BaseCtor(BaseCtor) {} |
2335 | |
2336 | explicit operator bool() const { return Shadow; } |
2337 | |
2338 | ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; } |
2339 | CXXConstructorDecl *getConstructor() const { return BaseCtor; } |
2340 | }; |
2341 | |
2342 | /// Represents a C++ constructor within a class. |
2343 | /// |
2344 | /// For example: |
2345 | /// |
2346 | /// \code |
2347 | /// class X { |
2348 | /// public: |
2349 | /// explicit X(int); // represented by a CXXConstructorDecl. |
2350 | /// }; |
2351 | /// \endcode |
2352 | class CXXConstructorDecl final |
2353 | : public CXXMethodDecl, |
2354 | private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor, |
2355 | ExplicitSpecifier> { |
2356 | // This class stores some data in DeclContext::CXXConstructorDeclBits |
2357 | // to save some space. Use the provided accessors to access it. |
2358 | |
2359 | /// \name Support for base and member initializers. |
2360 | /// \{ |
2361 | /// The arguments used to initialize the base or member. |
2362 | LazyCXXCtorInitializersPtr CtorInitializers; |
2363 | |
2364 | CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2365 | const DeclarationNameInfo &NameInfo, QualType T, |
2366 | TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline, |
2367 | bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, |
2368 | InheritedConstructor Inherited, |
2369 | Expr *TrailingRequiresClause); |
2370 | |
2371 | void anchor() override; |
2372 | |
2373 | size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const { |
2374 | return CXXConstructorDeclBits.IsInheritingConstructor; |
2375 | } |
2376 | size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const { |
2377 | return CXXConstructorDeclBits.HasTrailingExplicitSpecifier; |
2378 | } |
2379 | |
2380 | ExplicitSpecifier getExplicitSpecifierInternal() const { |
2381 | if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier) |
2382 | return *getTrailingObjects<ExplicitSpecifier>(); |
2383 | return ExplicitSpecifier( |
2384 | nullptr, CXXConstructorDeclBits.IsSimpleExplicit |
2385 | ? ExplicitSpecKind::ResolvedTrue |
2386 | : ExplicitSpecKind::ResolvedFalse); |
2387 | } |
2388 | |
2389 | void setExplicitSpecifier(ExplicitSpecifier ES) { |
2390 | assert((!ES.getExpr() ||(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier ) && "cannot set this explicit specifier. no trail-allocated space for " "explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2393, __PRETTY_FUNCTION__)) |
2391 | CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier ) && "cannot set this explicit specifier. no trail-allocated space for " "explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2393, __PRETTY_FUNCTION__)) |
2392 | "cannot set this explicit specifier. no trail-allocated space for "(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier ) && "cannot set this explicit specifier. no trail-allocated space for " "explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2393, __PRETTY_FUNCTION__)) |
2393 | "explicit")(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier ) && "cannot set this explicit specifier. no trail-allocated space for " "explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2393, __PRETTY_FUNCTION__)); |
2394 | if (ES.getExpr()) |
2395 | *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES; |
2396 | else |
2397 | CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit(); |
2398 | } |
2399 | |
2400 | enum TraillingAllocKind { |
2401 | TAKInheritsConstructor = 1, |
2402 | TAKHasTailExplicit = 1 << 1, |
2403 | }; |
2404 | |
2405 | uint64_t getTraillingAllocKind() const { |
2406 | return numTrailingObjects(OverloadToken<InheritedConstructor>()) | |
2407 | (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1); |
2408 | } |
2409 | |
2410 | public: |
2411 | friend class ASTDeclReader; |
2412 | friend class ASTDeclWriter; |
2413 | friend TrailingObjects; |
2414 | |
2415 | static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
2416 | uint64_t AllocKind); |
2417 | static CXXConstructorDecl * |
2418 | Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2419 | const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, |
2420 | ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared, |
2421 | ConstexprSpecKind ConstexprKind, |
2422 | InheritedConstructor Inherited = InheritedConstructor(), |
2423 | Expr *TrailingRequiresClause = nullptr); |
2424 | |
2425 | ExplicitSpecifier getExplicitSpecifier() { |
2426 | return getCanonicalDecl()->getExplicitSpecifierInternal(); |
2427 | } |
2428 | const ExplicitSpecifier getExplicitSpecifier() const { |
2429 | return getCanonicalDecl()->getExplicitSpecifierInternal(); |
2430 | } |
2431 | |
2432 | /// Return true if the declartion is already resolved to be explicit. |
2433 | bool isExplicit() const { return getExplicitSpecifier().isExplicit(); } |
2434 | |
2435 | /// Iterates through the member/base initializer list. |
2436 | using init_iterator = CXXCtorInitializer **; |
2437 | |
2438 | /// Iterates through the member/base initializer list. |
2439 | using init_const_iterator = CXXCtorInitializer *const *; |
2440 | |
2441 | using init_range = llvm::iterator_range<init_iterator>; |
2442 | using init_const_range = llvm::iterator_range<init_const_iterator>; |
2443 | |
2444 | init_range inits() { return init_range(init_begin(), init_end()); } |
2445 | init_const_range inits() const { |
2446 | return init_const_range(init_begin(), init_end()); |
2447 | } |
2448 | |
2449 | /// Retrieve an iterator to the first initializer. |
2450 | init_iterator init_begin() { |
2451 | const auto *ConstThis = this; |
2452 | return const_cast<init_iterator>(ConstThis->init_begin()); |
2453 | } |
2454 | |
2455 | /// Retrieve an iterator to the first initializer. |
2456 | init_const_iterator init_begin() const; |
2457 | |
2458 | /// Retrieve an iterator past the last initializer. |
2459 | init_iterator init_end() { |
2460 | return init_begin() + getNumCtorInitializers(); |
2461 | } |
2462 | |
2463 | /// Retrieve an iterator past the last initializer. |
2464 | init_const_iterator init_end() const { |
2465 | return init_begin() + getNumCtorInitializers(); |
2466 | } |
2467 | |
2468 | using init_reverse_iterator = std::reverse_iterator<init_iterator>; |
2469 | using init_const_reverse_iterator = |
2470 | std::reverse_iterator<init_const_iterator>; |
2471 | |
2472 | init_reverse_iterator init_rbegin() { |
2473 | return init_reverse_iterator(init_end()); |
2474 | } |
2475 | init_const_reverse_iterator init_rbegin() const { |
2476 | return init_const_reverse_iterator(init_end()); |
2477 | } |
2478 | |
2479 | init_reverse_iterator init_rend() { |
2480 | return init_reverse_iterator(init_begin()); |
2481 | } |
2482 | init_const_reverse_iterator init_rend() const { |
2483 | return init_const_reverse_iterator(init_begin()); |
2484 | } |
2485 | |
2486 | /// Determine the number of arguments used to initialize the member |
2487 | /// or base. |
2488 | unsigned getNumCtorInitializers() const { |
2489 | return CXXConstructorDeclBits.NumCtorInitializers; |
2490 | } |
2491 | |
2492 | void setNumCtorInitializers(unsigned numCtorInitializers) { |
2493 | CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers; |
2494 | // This assert added because NumCtorInitializers is stored |
2495 | // in CXXConstructorDeclBits as a bitfield and its width has |
2496 | // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields. |
2497 | assert(CXXConstructorDeclBits.NumCtorInitializers ==((CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && "NumCtorInitializers overflow!") ? static_cast< void> (0) : __assert_fail ("CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && \"NumCtorInitializers overflow!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2498, __PRETTY_FUNCTION__)) |
2498 | numCtorInitializers && "NumCtorInitializers overflow!")((CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && "NumCtorInitializers overflow!") ? static_cast< void> (0) : __assert_fail ("CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && \"NumCtorInitializers overflow!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2498, __PRETTY_FUNCTION__)); |
2499 | } |
2500 | |
2501 | void setCtorInitializers(CXXCtorInitializer **Initializers) { |
2502 | CtorInitializers = Initializers; |
2503 | } |
2504 | |
2505 | /// Determine whether this constructor is a delegating constructor. |
2506 | bool isDelegatingConstructor() const { |
2507 | return (getNumCtorInitializers() == 1) && |
2508 | init_begin()[0]->isDelegatingInitializer(); |
2509 | } |
2510 | |
2511 | /// When this constructor delegates to another, retrieve the target. |
2512 | CXXConstructorDecl *getTargetConstructor() const; |
2513 | |
2514 | /// Whether this constructor is a default |
2515 | /// constructor (C++ [class.ctor]p5), which can be used to |
2516 | /// default-initialize a class of this type. |
2517 | bool isDefaultConstructor() const; |
2518 | |
2519 | /// Whether this constructor is a copy constructor (C++ [class.copy]p2, |
2520 | /// which can be used to copy the class. |
2521 | /// |
2522 | /// \p TypeQuals will be set to the qualifiers on the |
2523 | /// argument type. For example, \p TypeQuals would be set to \c |
2524 | /// Qualifiers::Const for the following copy constructor: |
2525 | /// |
2526 | /// \code |
2527 | /// class X { |
2528 | /// public: |
2529 | /// X(const X&); |
2530 | /// }; |
2531 | /// \endcode |
2532 | bool isCopyConstructor(unsigned &TypeQuals) const; |
2533 | |
2534 | /// Whether this constructor is a copy |
2535 | /// constructor (C++ [class.copy]p2, which can be used to copy the |
2536 | /// class. |
2537 | bool isCopyConstructor() const { |
2538 | unsigned TypeQuals = 0; |
2539 | return isCopyConstructor(TypeQuals); |
2540 | } |
2541 | |
2542 | /// Determine whether this constructor is a move constructor |
2543 | /// (C++11 [class.copy]p3), which can be used to move values of the class. |
2544 | /// |
2545 | /// \param TypeQuals If this constructor is a move constructor, will be set |
2546 | /// to the type qualifiers on the referent of the first parameter's type. |
2547 | bool isMoveConstructor(unsigned &TypeQuals) const; |
2548 | |
2549 | /// Determine whether this constructor is a move constructor |
2550 | /// (C++11 [class.copy]p3), which can be used to move values of the class. |
2551 | bool isMoveConstructor() const { |
2552 | unsigned TypeQuals = 0; |
2553 | return isMoveConstructor(TypeQuals); |
2554 | } |
2555 | |
2556 | /// Determine whether this is a copy or move constructor. |
2557 | /// |
2558 | /// \param TypeQuals Will be set to the type qualifiers on the reference |
2559 | /// parameter, if in fact this is a copy or move constructor. |
2560 | bool isCopyOrMoveConstructor(unsigned &TypeQuals) const; |
2561 | |
2562 | /// Determine whether this a copy or move constructor. |
2563 | bool isCopyOrMoveConstructor() const { |
2564 | unsigned Quals; |
2565 | return isCopyOrMoveConstructor(Quals); |
2566 | } |
2567 | |
2568 | /// Whether this constructor is a |
2569 | /// converting constructor (C++ [class.conv.ctor]), which can be |
2570 | /// used for user-defined conversions. |
2571 | bool isConvertingConstructor(bool AllowExplicit) const; |
2572 | |
2573 | /// Determine whether this is a member template specialization that |
2574 | /// would copy the object to itself. Such constructors are never used to copy |
2575 | /// an object. |
2576 | bool isSpecializationCopyingObject() const; |
2577 | |
2578 | /// Determine whether this is an implicit constructor synthesized to |
2579 | /// model a call to a constructor inherited from a base class. |
2580 | bool isInheritingConstructor() const { |
2581 | return CXXConstructorDeclBits.IsInheritingConstructor; |
2582 | } |
2583 | |
2584 | /// State that this is an implicit constructor synthesized to |
2585 | /// model a call to a constructor inherited from a base class. |
2586 | void setInheritingConstructor(bool isIC = true) { |
2587 | CXXConstructorDeclBits.IsInheritingConstructor = isIC; |
2588 | } |
2589 | |
2590 | /// Get the constructor that this inheriting constructor is based on. |
2591 | InheritedConstructor getInheritedConstructor() const { |
2592 | return isInheritingConstructor() ? |
2593 | *getTrailingObjects<InheritedConstructor>() : InheritedConstructor(); |
2594 | } |
2595 | |
2596 | CXXConstructorDecl *getCanonicalDecl() override { |
2597 | return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl()); |
2598 | } |
2599 | const CXXConstructorDecl *getCanonicalDecl() const { |
2600 | return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl(); |
2601 | } |
2602 | |
2603 | // Implement isa/cast/dyncast/etc. |
2604 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2605 | static bool classofKind(Kind K) { return K == CXXConstructor; } |
2606 | }; |
2607 | |
2608 | /// Represents a C++ destructor within a class. |
2609 | /// |
2610 | /// For example: |
2611 | /// |
2612 | /// \code |
2613 | /// class X { |
2614 | /// public: |
2615 | /// ~X(); // represented by a CXXDestructorDecl. |
2616 | /// }; |
2617 | /// \endcode |
2618 | class CXXDestructorDecl : public CXXMethodDecl { |
2619 | friend class ASTDeclReader; |
2620 | friend class ASTDeclWriter; |
2621 | |
2622 | // FIXME: Don't allocate storage for these except in the first declaration |
2623 | // of a virtual destructor. |
2624 | FunctionDecl *OperatorDelete = nullptr; |
2625 | Expr *OperatorDeleteThisArg = nullptr; |
2626 | |
2627 | CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2628 | const DeclarationNameInfo &NameInfo, QualType T, |
2629 | TypeSourceInfo *TInfo, bool isInline, |
2630 | bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, |
2631 | Expr *TrailingRequiresClause = nullptr) |
2632 | : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo, |
2633 | SC_None, isInline, ConstexprKind, SourceLocation(), |
2634 | TrailingRequiresClause) { |
2635 | setImplicit(isImplicitlyDeclared); |
2636 | } |
2637 | |
2638 | void anchor() override; |
2639 | |
2640 | public: |
2641 | static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD, |
2642 | SourceLocation StartLoc, |
2643 | const DeclarationNameInfo &NameInfo, |
2644 | QualType T, TypeSourceInfo *TInfo, |
2645 | bool isInline, bool isImplicitlyDeclared, |
2646 | ConstexprSpecKind ConstexprKind, |
2647 | Expr *TrailingRequiresClause = nullptr); |
2648 | static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID); |
2649 | |
2650 | void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg); |
2651 | |
2652 | const FunctionDecl *getOperatorDelete() const { |
2653 | return getCanonicalDecl()->OperatorDelete; |
2654 | } |
2655 | |
2656 | Expr *getOperatorDeleteThisArg() const { |
2657 | return getCanonicalDecl()->OperatorDeleteThisArg; |
2658 | } |
2659 | |
2660 | CXXDestructorDecl *getCanonicalDecl() override { |
2661 | return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl()); |
2662 | } |
2663 | const CXXDestructorDecl *getCanonicalDecl() const { |
2664 | return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl(); |
2665 | } |
2666 | |
2667 | // Implement isa/cast/dyncast/etc. |
2668 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2669 | static bool classofKind(Kind K) { return K == CXXDestructor; } |
2670 | }; |
2671 | |
2672 | /// Represents a C++ conversion function within a class. |
2673 | /// |
2674 | /// For example: |
2675 | /// |
2676 | /// \code |
2677 | /// class X { |
2678 | /// public: |
2679 | /// operator bool(); |
2680 | /// }; |
2681 | /// \endcode |
2682 | class CXXConversionDecl : public CXXMethodDecl { |
2683 | CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2684 | const DeclarationNameInfo &NameInfo, QualType T, |
2685 | TypeSourceInfo *TInfo, bool isInline, ExplicitSpecifier ES, |
2686 | ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, |
2687 | Expr *TrailingRequiresClause = nullptr) |
2688 | : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo, |
2689 | SC_None, isInline, ConstexprKind, EndLocation, |
2690 | TrailingRequiresClause), |
2691 | ExplicitSpec(ES) {} |
2692 | void anchor() override; |
2693 | |
2694 | ExplicitSpecifier ExplicitSpec; |
2695 | |
2696 | void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; } |
2697 | |
2698 | public: |
2699 | friend class ASTDeclReader; |
2700 | friend class ASTDeclWriter; |
2701 | |
2702 | static CXXConversionDecl * |
2703 | Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, |
2704 | const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, |
2705 | bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, |
2706 | SourceLocation EndLocation, Expr *TrailingRequiresClause = nullptr); |
2707 | static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2708 | |
2709 | ExplicitSpecifier getExplicitSpecifier() { |
2710 | return getCanonicalDecl()->ExplicitSpec; |
2711 | } |
2712 | |
2713 | const ExplicitSpecifier getExplicitSpecifier() const { |
2714 | return getCanonicalDecl()->ExplicitSpec; |
2715 | } |
2716 | |
2717 | /// Return true if the declartion is already resolved to be explicit. |
2718 | bool isExplicit() const { return getExplicitSpecifier().isExplicit(); } |
2719 | |
2720 | /// Returns the type that this conversion function is converting to. |
2721 | QualType getConversionType() const { |
2722 | return getType()->castAs<FunctionType>()->getReturnType(); |
2723 | } |
2724 | |
2725 | /// Determine whether this conversion function is a conversion from |
2726 | /// a lambda closure type to a block pointer. |
2727 | bool isLambdaToBlockPointerConversion() const; |
2728 | |
2729 | CXXConversionDecl *getCanonicalDecl() override { |
2730 | return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl()); |
2731 | } |
2732 | const CXXConversionDecl *getCanonicalDecl() const { |
2733 | return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl(); |
2734 | } |
2735 | |
2736 | // Implement isa/cast/dyncast/etc. |
2737 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2738 | static bool classofKind(Kind K) { return K == CXXConversion; } |
2739 | }; |
2740 | |
2741 | /// Represents a linkage specification. |
2742 | /// |
2743 | /// For example: |
2744 | /// \code |
2745 | /// extern "C" void foo(); |
2746 | /// \endcode |
2747 | class LinkageSpecDecl : public Decl, public DeclContext { |
2748 | virtual void anchor(); |
2749 | // This class stores some data in DeclContext::LinkageSpecDeclBits to save |
2750 | // some space. Use the provided accessors to access it. |
2751 | public: |
2752 | /// Represents the language in a linkage specification. |
2753 | /// |
2754 | /// The values are part of the serialization ABI for |
2755 | /// ASTs and cannot be changed without altering that ABI. |
2756 | enum LanguageIDs { lang_c = 1, lang_cxx = 2 }; |
2757 | |
2758 | private: |
2759 | /// The source location for the extern keyword. |
2760 | SourceLocation ExternLoc; |
2761 | |
2762 | /// The source location for the right brace (if valid). |
2763 | SourceLocation RBraceLoc; |
2764 | |
2765 | LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc, |
2766 | SourceLocation LangLoc, LanguageIDs lang, bool HasBraces); |
2767 | |
2768 | public: |
2769 | static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC, |
2770 | SourceLocation ExternLoc, |
2771 | SourceLocation LangLoc, LanguageIDs Lang, |
2772 | bool HasBraces); |
2773 | static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2774 | |
2775 | /// Return the language specified by this linkage specification. |
2776 | LanguageIDs getLanguage() const { |
2777 | return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language); |
2778 | } |
2779 | |
2780 | /// Set the language specified by this linkage specification. |
2781 | void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; } |
2782 | |
2783 | /// Determines whether this linkage specification had braces in |
2784 | /// its syntactic form. |
2785 | bool hasBraces() const { |
2786 | assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces)((!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces) ? static_cast <void> (0) : __assert_fail ("!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 2786, __PRETTY_FUNCTION__)); |
2787 | return LinkageSpecDeclBits.HasBraces; |
2788 | } |
2789 | |
2790 | SourceLocation getExternLoc() const { return ExternLoc; } |
2791 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
2792 | void setExternLoc(SourceLocation L) { ExternLoc = L; } |
2793 | void setRBraceLoc(SourceLocation L) { |
2794 | RBraceLoc = L; |
2795 | LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid(); |
2796 | } |
2797 | |
2798 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
2799 | if (hasBraces()) |
2800 | return getRBraceLoc(); |
2801 | // No braces: get the end location of the (only) declaration in context |
2802 | // (if present). |
2803 | return decls_empty() ? getLocation() : decls_begin()->getEndLoc(); |
2804 | } |
2805 | |
2806 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
2807 | return SourceRange(ExternLoc, getEndLoc()); |
2808 | } |
2809 | |
2810 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2811 | static bool classofKind(Kind K) { return K == LinkageSpec; } |
2812 | |
2813 | static DeclContext *castToDeclContext(const LinkageSpecDecl *D) { |
2814 | return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D)); |
2815 | } |
2816 | |
2817 | static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) { |
2818 | return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC)); |
2819 | } |
2820 | }; |
2821 | |
2822 | /// Represents C++ using-directive. |
2823 | /// |
2824 | /// For example: |
2825 | /// \code |
2826 | /// using namespace std; |
2827 | /// \endcode |
2828 | /// |
2829 | /// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide |
2830 | /// artificial names for all using-directives in order to store |
2831 | /// them in DeclContext effectively. |
2832 | class UsingDirectiveDecl : public NamedDecl { |
2833 | /// The location of the \c using keyword. |
2834 | SourceLocation UsingLoc; |
2835 | |
2836 | /// The location of the \c namespace keyword. |
2837 | SourceLocation NamespaceLoc; |
2838 | |
2839 | /// The nested-name-specifier that precedes the namespace. |
2840 | NestedNameSpecifierLoc QualifierLoc; |
2841 | |
2842 | /// The namespace nominated by this using-directive. |
2843 | NamedDecl *NominatedNamespace; |
2844 | |
2845 | /// Enclosing context containing both using-directive and nominated |
2846 | /// namespace. |
2847 | DeclContext *CommonAncestor; |
2848 | |
2849 | UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc, |
2850 | SourceLocation NamespcLoc, |
2851 | NestedNameSpecifierLoc QualifierLoc, |
2852 | SourceLocation IdentLoc, |
2853 | NamedDecl *Nominated, |
2854 | DeclContext *CommonAncestor) |
2855 | : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc), |
2856 | NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc), |
2857 | NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {} |
2858 | |
2859 | /// Returns special DeclarationName used by using-directives. |
2860 | /// |
2861 | /// This is only used by DeclContext for storing UsingDirectiveDecls in |
2862 | /// its lookup structure. |
2863 | static DeclarationName getName() { |
2864 | return DeclarationName::getUsingDirectiveName(); |
2865 | } |
2866 | |
2867 | void anchor() override; |
2868 | |
2869 | public: |
2870 | friend class ASTDeclReader; |
2871 | |
2872 | // Friend for getUsingDirectiveName. |
2873 | friend class DeclContext; |
2874 | |
2875 | /// Retrieve the nested-name-specifier that qualifies the |
2876 | /// name of the namespace, with source-location information. |
2877 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
2878 | |
2879 | /// Retrieve the nested-name-specifier that qualifies the |
2880 | /// name of the namespace. |
2881 | NestedNameSpecifier *getQualifier() const { |
2882 | return QualifierLoc.getNestedNameSpecifier(); |
2883 | } |
2884 | |
2885 | NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; } |
2886 | const NamedDecl *getNominatedNamespaceAsWritten() const { |
2887 | return NominatedNamespace; |
2888 | } |
2889 | |
2890 | /// Returns the namespace nominated by this using-directive. |
2891 | NamespaceDecl *getNominatedNamespace(); |
2892 | |
2893 | const NamespaceDecl *getNominatedNamespace() const { |
2894 | return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace(); |
2895 | } |
2896 | |
2897 | /// Returns the common ancestor context of this using-directive and |
2898 | /// its nominated namespace. |
2899 | DeclContext *getCommonAncestor() { return CommonAncestor; } |
2900 | const DeclContext *getCommonAncestor() const { return CommonAncestor; } |
2901 | |
2902 | /// Return the location of the \c using keyword. |
2903 | SourceLocation getUsingLoc() const { return UsingLoc; } |
2904 | |
2905 | // FIXME: Could omit 'Key' in name. |
2906 | /// Returns the location of the \c namespace keyword. |
2907 | SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; } |
2908 | |
2909 | /// Returns the location of this using declaration's identifier. |
2910 | SourceLocation getIdentLocation() const { return getLocation(); } |
2911 | |
2912 | static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC, |
2913 | SourceLocation UsingLoc, |
2914 | SourceLocation NamespaceLoc, |
2915 | NestedNameSpecifierLoc QualifierLoc, |
2916 | SourceLocation IdentLoc, |
2917 | NamedDecl *Nominated, |
2918 | DeclContext *CommonAncestor); |
2919 | static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2920 | |
2921 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
2922 | return SourceRange(UsingLoc, getLocation()); |
2923 | } |
2924 | |
2925 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2926 | static bool classofKind(Kind K) { return K == UsingDirective; } |
2927 | }; |
2928 | |
2929 | /// Represents a C++ namespace alias. |
2930 | /// |
2931 | /// For example: |
2932 | /// |
2933 | /// \code |
2934 | /// namespace Foo = Bar; |
2935 | /// \endcode |
2936 | class NamespaceAliasDecl : public NamedDecl, |
2937 | public Redeclarable<NamespaceAliasDecl> { |
2938 | friend class ASTDeclReader; |
2939 | |
2940 | /// The location of the \c namespace keyword. |
2941 | SourceLocation NamespaceLoc; |
2942 | |
2943 | /// The location of the namespace's identifier. |
2944 | /// |
2945 | /// This is accessed by TargetNameLoc. |
2946 | SourceLocation IdentLoc; |
2947 | |
2948 | /// The nested-name-specifier that precedes the namespace. |
2949 | NestedNameSpecifierLoc QualifierLoc; |
2950 | |
2951 | /// The Decl that this alias points to, either a NamespaceDecl or |
2952 | /// a NamespaceAliasDecl. |
2953 | NamedDecl *Namespace; |
2954 | |
2955 | NamespaceAliasDecl(ASTContext &C, DeclContext *DC, |
2956 | SourceLocation NamespaceLoc, SourceLocation AliasLoc, |
2957 | IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc, |
2958 | SourceLocation IdentLoc, NamedDecl *Namespace) |
2959 | : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C), |
2960 | NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc), |
2961 | QualifierLoc(QualifierLoc), Namespace(Namespace) {} |
2962 | |
2963 | void anchor() override; |
2964 | |
2965 | using redeclarable_base = Redeclarable<NamespaceAliasDecl>; |
2966 | |
2967 | NamespaceAliasDecl *getNextRedeclarationImpl() override; |
2968 | NamespaceAliasDecl *getPreviousDeclImpl() override; |
2969 | NamespaceAliasDecl *getMostRecentDeclImpl() override; |
2970 | |
2971 | public: |
2972 | static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC, |
2973 | SourceLocation NamespaceLoc, |
2974 | SourceLocation AliasLoc, |
2975 | IdentifierInfo *Alias, |
2976 | NestedNameSpecifierLoc QualifierLoc, |
2977 | SourceLocation IdentLoc, |
2978 | NamedDecl *Namespace); |
2979 | |
2980 | static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2981 | |
2982 | using redecl_range = redeclarable_base::redecl_range; |
2983 | using redecl_iterator = redeclarable_base::redecl_iterator; |
2984 | |
2985 | using redeclarable_base::redecls_begin; |
2986 | using redeclarable_base::redecls_end; |
2987 | using redeclarable_base::redecls; |
2988 | using redeclarable_base::getPreviousDecl; |
2989 | using redeclarable_base::getMostRecentDecl; |
2990 | |
2991 | NamespaceAliasDecl *getCanonicalDecl() override { |
2992 | return getFirstDecl(); |
2993 | } |
2994 | const NamespaceAliasDecl *getCanonicalDecl() const { |
2995 | return getFirstDecl(); |
2996 | } |
2997 | |
2998 | /// Retrieve the nested-name-specifier that qualifies the |
2999 | /// name of the namespace, with source-location information. |
3000 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
3001 | |
3002 | /// Retrieve the nested-name-specifier that qualifies the |
3003 | /// name of the namespace. |
3004 | NestedNameSpecifier *getQualifier() const { |
3005 | return QualifierLoc.getNestedNameSpecifier(); |
3006 | } |
3007 | |
3008 | /// Retrieve the namespace declaration aliased by this directive. |
3009 | NamespaceDecl *getNamespace() { |
3010 | if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace)) |
3011 | return AD->getNamespace(); |
3012 | |
3013 | return cast<NamespaceDecl>(Namespace); |
3014 | } |
3015 | |
3016 | const NamespaceDecl *getNamespace() const { |
3017 | return const_cast<NamespaceAliasDecl *>(this)->getNamespace(); |
3018 | } |
3019 | |
3020 | /// Returns the location of the alias name, i.e. 'foo' in |
3021 | /// "namespace foo = ns::bar;". |
3022 | SourceLocation getAliasLoc() const { return getLocation(); } |
3023 | |
3024 | /// Returns the location of the \c namespace keyword. |
3025 | SourceLocation getNamespaceLoc() const { return NamespaceLoc; } |
3026 | |
3027 | /// Returns the location of the identifier in the named namespace. |
3028 | SourceLocation getTargetNameLoc() const { return IdentLoc; } |
3029 | |
3030 | /// Retrieve the namespace that this alias refers to, which |
3031 | /// may either be a NamespaceDecl or a NamespaceAliasDecl. |
3032 | NamedDecl *getAliasedNamespace() const { return Namespace; } |
3033 | |
3034 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3035 | return SourceRange(NamespaceLoc, IdentLoc); |
3036 | } |
3037 | |
3038 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3039 | static bool classofKind(Kind K) { return K == NamespaceAlias; } |
3040 | }; |
3041 | |
3042 | /// Implicit declaration of a temporary that was materialized by |
3043 | /// a MaterializeTemporaryExpr and lifetime-extended by a declaration |
3044 | class LifetimeExtendedTemporaryDecl final |
3045 | : public Decl, |
3046 | public Mergeable<LifetimeExtendedTemporaryDecl> { |
3047 | friend class MaterializeTemporaryExpr; |
3048 | friend class ASTDeclReader; |
3049 | |
3050 | Stmt *ExprWithTemporary = nullptr; |
3051 | |
3052 | /// The declaration which lifetime-extended this reference, if any. |
3053 | /// Either a VarDecl, or (for a ctor-initializer) a FieldDecl. |
3054 | ValueDecl *ExtendingDecl = nullptr; |
3055 | unsigned ManglingNumber; |
3056 | |
3057 | mutable APValue *Value = nullptr; |
3058 | |
3059 | virtual void anchor(); |
3060 | |
3061 | LifetimeExtendedTemporaryDecl(Expr *Temp, ValueDecl *EDecl, unsigned Mangling) |
3062 | : Decl(Decl::LifetimeExtendedTemporary, EDecl->getDeclContext(), |
3063 | EDecl->getLocation()), |
3064 | ExprWithTemporary(Temp), ExtendingDecl(EDecl), |
3065 | ManglingNumber(Mangling) {} |
3066 | |
3067 | LifetimeExtendedTemporaryDecl(EmptyShell) |
3068 | : Decl(Decl::LifetimeExtendedTemporary, EmptyShell{}) {} |
3069 | |
3070 | public: |
3071 | static LifetimeExtendedTemporaryDecl *Create(Expr *Temp, ValueDecl *EDec, |
3072 | unsigned Mangling) { |
3073 | return new (EDec->getASTContext(), EDec->getDeclContext()) |
3074 | LifetimeExtendedTemporaryDecl(Temp, EDec, Mangling); |
3075 | } |
3076 | static LifetimeExtendedTemporaryDecl *CreateDeserialized(ASTContext &C, |
3077 | unsigned ID) { |
3078 | return new (C, ID) LifetimeExtendedTemporaryDecl(EmptyShell{}); |
3079 | } |
3080 | |
3081 | ValueDecl *getExtendingDecl() { return ExtendingDecl; } |
3082 | const ValueDecl *getExtendingDecl() const { return ExtendingDecl; } |
3083 | |
3084 | /// Retrieve the storage duration for the materialized temporary. |
3085 | StorageDuration getStorageDuration() const; |
3086 | |
3087 | /// Retrieve the expression to which the temporary materialization conversion |
3088 | /// was applied. This isn't necessarily the initializer of the temporary due |
3089 | /// to the C++98 delayed materialization rules, but |
3090 | /// skipRValueSubobjectAdjustments can be used to find said initializer within |
3091 | /// the subexpression. |
3092 | Expr *getTemporaryExpr() { return cast<Expr>(ExprWithTemporary); } |
3093 | const Expr *getTemporaryExpr() const { return cast<Expr>(ExprWithTemporary); } |
3094 | |
3095 | unsigned getManglingNumber() const { return ManglingNumber; } |
3096 | |
3097 | /// Get the storage for the constant value of a materialized temporary |
3098 | /// of static storage duration. |
3099 | APValue *getOrCreateValue(bool MayCreate) const; |
3100 | |
3101 | APValue *getValue() const { return Value; } |
3102 | |
3103 | // Iterators |
3104 | Stmt::child_range childrenExpr() { |
3105 | return Stmt::child_range(&ExprWithTemporary, &ExprWithTemporary + 1); |
3106 | } |
3107 | |
3108 | Stmt::const_child_range childrenExpr() const { |
3109 | return Stmt::const_child_range(&ExprWithTemporary, &ExprWithTemporary + 1); |
3110 | } |
3111 | |
3112 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3113 | static bool classofKind(Kind K) { |
3114 | return K == Decl::LifetimeExtendedTemporary; |
3115 | } |
3116 | }; |
3117 | |
3118 | /// Represents a shadow declaration introduced into a scope by a |
3119 | /// (resolved) using declaration. |
3120 | /// |
3121 | /// For example, |
3122 | /// \code |
3123 | /// namespace A { |
3124 | /// void foo(); |
3125 | /// } |
3126 | /// namespace B { |
3127 | /// using A::foo; // <- a UsingDecl |
3128 | /// // Also creates a UsingShadowDecl for A::foo() in B |
3129 | /// } |
3130 | /// \endcode |
3131 | class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> { |
3132 | friend class UsingDecl; |
3133 | |
3134 | /// The referenced declaration. |
3135 | NamedDecl *Underlying = nullptr; |
3136 | |
3137 | /// The using declaration which introduced this decl or the next using |
3138 | /// shadow declaration contained in the aforementioned using declaration. |
3139 | NamedDecl *UsingOrNextShadow = nullptr; |
3140 | |
3141 | void anchor() override; |
3142 | |
3143 | using redeclarable_base = Redeclarable<UsingShadowDecl>; |
3144 | |
3145 | UsingShadowDecl *getNextRedeclarationImpl() override { |
3146 | return getNextRedeclaration(); |
3147 | } |
3148 | |
3149 | UsingShadowDecl *getPreviousDeclImpl() override { |
3150 | return getPreviousDecl(); |
3151 | } |
3152 | |
3153 | UsingShadowDecl *getMostRecentDeclImpl() override { |
3154 | return getMostRecentDecl(); |
3155 | } |
3156 | |
3157 | protected: |
3158 | UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc, |
3159 | UsingDecl *Using, NamedDecl *Target); |
3160 | UsingShadowDecl(Kind K, ASTContext &C, EmptyShell); |
3161 | |
3162 | public: |
3163 | friend class ASTDeclReader; |
3164 | friend class ASTDeclWriter; |
3165 | |
3166 | static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC, |
3167 | SourceLocation Loc, UsingDecl *Using, |
3168 | NamedDecl *Target) { |
3169 | return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target); |
3170 | } |
3171 | |
3172 | static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3173 | |
3174 | using redecl_range = redeclarable_base::redecl_range; |
3175 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3176 | |
3177 | using redeclarable_base::redecls_begin; |
3178 | using redeclarable_base::redecls_end; |
3179 | using redeclarable_base::redecls; |
3180 | using redeclarable_base::getPreviousDecl; |
3181 | using redeclarable_base::getMostRecentDecl; |
3182 | using redeclarable_base::isFirstDecl; |
3183 | |
3184 | UsingShadowDecl *getCanonicalDecl() override { |
3185 | return getFirstDecl(); |
3186 | } |
3187 | const UsingShadowDecl *getCanonicalDecl() const { |
3188 | return getFirstDecl(); |
3189 | } |
3190 | |
3191 | /// Gets the underlying declaration which has been brought into the |
3192 | /// local scope. |
3193 | NamedDecl *getTargetDecl() const { return Underlying; } |
3194 | |
3195 | /// Sets the underlying declaration which has been brought into the |
3196 | /// local scope. |
3197 | void setTargetDecl(NamedDecl *ND) { |
3198 | assert(ND && "Target decl is null!")((ND && "Target decl is null!") ? static_cast<void > (0) : __assert_fail ("ND && \"Target decl is null!\"" , "/build/llvm-toolchain-snapshot-10~++20200110111110+a1cc19b5814/clang/include/clang/AST/DeclCXX.h" , 3198, __PRETTY_FUNCTION__)); |
3199 | Underlying = ND; |
3200 | // A UsingShadowDecl is never a friend or local extern declaration, even |
3201 | // if it is a shadow declaration for one. |
3202 | IdentifierNamespace = |
3203 | ND->getIdentifierNamespace() & |
3204 | ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern); |
3205 | } |
3206 | |
3207 | /// Gets the using declaration to which this declaration is tied. |
3208 | UsingDecl *getUsingDecl() const; |
3209 | |
3210 | /// The next using shadow declaration contained in the shadow decl |
3211 | /// chain of the using declaration which introduced this decl. |
3212 | UsingShadowDecl *getNextUsingShadowDecl() const { |
3213 | return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow); |
3214 | } |
3215 | |
3216 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3217 | static bool classofKind(Kind K) { |
3218 | return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow; |
3219 | } |
3220 | }; |
3221 | |
3222 | /// Represents a shadow constructor declaration introduced into a |
3223 | /// class by a C++11 using-declaration that names a constructor. |
3224 | /// |
3225 | /// For example: |
3226 | /// \code |
3227 | /// struct Base { Base(int); }; |
3228 | /// struct Derived { |
3229 | /// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl |
3230 | /// }; |
3231 | /// \endcode |
3232 | class ConstructorUsingShadowDecl final : public UsingShadowDecl { |
3233 | /// If this constructor using declaration inherted the constructor |
3234 | /// from an indirect base class, this is the ConstructorUsingShadowDecl |
3235 | /// in the named direct base class from which the declaration was inherited. |
3236 | ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr; |
3237 | |
3238 | /// If this constructor using declaration inherted the constructor |
3239 | /// from an indirect base class, this is the ConstructorUsingShadowDecl |
3240 | /// that will be used to construct the unique direct or virtual base class |
3241 | /// that receives the constructor arguments. |
3242 | ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr; |
3243 | |
3244 | /// \c true if the constructor ultimately named by this using shadow |
3245 | /// declaration is within a virtual base class subobject of the class that |
3246 | /// contains this declaration. |
3247 | unsigned IsVirtual : 1; |
3248 | |
3249 | ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc, |
3250 | UsingDecl *Using, NamedDecl *Target, |
3251 | bool TargetInVirtualBase) |
3252 | : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using, |
3253 | Target->getUnderlyingDecl()), |
3254 | NominatedBaseClassShadowDecl( |
3255 | dyn_cast<ConstructorUsingShadowDecl>(Target)), |
3256 | ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl), |
3257 | IsVirtual(TargetInVirtualBase) { |
3258 | // If we found a constructor that chains to a constructor for a virtual |
3259 | // base, we should directly call that virtual base constructor instead. |
3260 | // FIXME: This logic belongs in Sema. |
3261 | if (NominatedBaseClassShadowDecl && |
3262 | NominatedBaseClassShadowDecl->constructsVirtualBase()) { |
3263 | ConstructedBaseClassShadowDecl = |
3264 | NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl; |
3265 | IsVirtual = true; |
3266 | } |
3267 | } |
3268 | |
3269 | ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty) |
3270 | : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {} |
3271 | |
3272 | void anchor() override; |
3273 | |
3274 | public: |
3275 | friend class ASTDeclReader; |
3276 | friend class ASTDeclWriter; |
3277 | |
3278 | static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC, |
3279 | SourceLocation Loc, |
3280 | UsingDecl *Using, NamedDecl *Target, |
3281 | bool IsVirtual); |
3282 | static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C, |
3283 | unsigned ID); |
3284 | |
3285 | /// Returns the parent of this using shadow declaration, which |
3286 | /// is the class in which this is declared. |
3287 | //@{ |
3288 | const CXXRecordDecl *getParent() const { |
3289 | return cast<CXXRecordDecl>(getDeclContext()); |
3290 | } |
3291 | CXXRecordDecl *getParent() { |
3292 | return cast<CXXRecordDecl>(getDeclContext()); |
3293 | } |
3294 | //@} |
3295 | |
3296 | /// Get the inheriting constructor declaration for the direct base |
3297 | /// class from which this using shadow declaration was inherited, if there is |
3298 | /// one. This can be different for each redeclaration of the same shadow decl. |
3299 | ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const { |
3300 | return NominatedBaseClassShadowDecl; |
3301 | } |
3302 | |
3303 | /// Get the inheriting constructor declaration for the base class |
3304 | /// for which we don't have an explicit initializer, if there is one. |
3305 | ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const { |
3306 | return ConstructedBaseClassShadowDecl; |
3307 | } |
3308 | |
3309 | /// Get the base class that was named in the using declaration. This |
3310 | /// can be different for each redeclaration of this same shadow decl. |
3311 | CXXRecordDecl *getNominatedBaseClass() const; |
3312 | |
3313 | /// Get the base class whose constructor or constructor shadow |
3314 | /// declaration is passed the constructor arguments. |
3315 | CXXRecordDecl *getConstructedBaseClass() const { |
3316 | return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl |
3317 | ? ConstructedBaseClassShadowDecl |
3318 | : getTargetDecl()) |
3319 | ->getDeclContext()); |
3320 | } |
3321 | |
3322 | /// Returns \c true if the constructed base class is a virtual base |
3323 | /// class subobject of this declaration's class. |
3324 | bool constructsVirtualBase() const { |
3325 | return IsVirtual; |
3326 | } |
3327 | |
3328 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3329 | static bool classofKind(Kind K) { return K == ConstructorUsingShadow; } |
3330 | }; |
3331 | |
3332 | /// Represents a C++ using-declaration. |
3333 | /// |
3334 | /// For example: |
3335 | /// \code |
3336 | /// using someNameSpace::someIdentifier; |
3337 | /// \endcode |
3338 | class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> { |
3339 | /// The source location of the 'using' keyword itself. |
3340 | SourceLocation UsingLocation; |
3341 | |
3342 | /// The nested-name-specifier that precedes the name. |
3343 | NestedNameSpecifierLoc QualifierLoc; |
3344 | |
3345 | /// Provides source/type location info for the declaration name |
3346 | /// embedded in the ValueDecl base class. |
3347 | DeclarationNameLoc DNLoc; |
3348 | |
3349 | /// The first shadow declaration of the shadow decl chain associated |
3350 | /// with this using declaration. |
3351 | /// |
3352 | /// The bool member of the pair store whether this decl has the \c typename |
3353 | /// keyword. |
3354 | llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow; |
3355 | |
3356 | UsingDecl(DeclContext *DC, SourceLocation UL, |
3357 | NestedNameSpecifierLoc QualifierLoc, |
3358 | const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword) |
3359 | : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()), |
3360 | UsingLocation(UL), QualifierLoc(QualifierLoc), |
3361 | DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) { |
3362 | } |
3363 | |
3364 | void anchor() override; |
3365 | |
3366 | public: |
3367 | friend class ASTDeclReader; |
3368 | friend class ASTDeclWriter; |
3369 | |
3370 | /// Return the source location of the 'using' keyword. |
3371 | SourceLocation getUsingLoc() const { return UsingLocation; } |
3372 | |
3373 | /// Set the source location of the 'using' keyword. |
3374 | void setUsingLoc(SourceLocation L) { UsingLocation = L; } |
3375 | |
3376 | /// Retrieve the nested-name-specifier that qualifies the name, |
3377 | /// with source-location information. |
3378 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
3379 | |
3380 | /// Retrieve the nested-name-specifier that qualifies the name. |
3381 | NestedNameSpecifier *getQualifier() const { |
3382 | return QualifierLoc.getNestedNameSpecifier(); |
3383 | } |
3384 | |
3385 | DeclarationNameInfo getNameInfo() const { |
3386 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
3387 | } |
3388 | |
3389 | /// Return true if it is a C++03 access declaration (no 'using'). |
3390 | bool isAccessDeclaration() const { return UsingLocation.isInvalid(); } |
3391 | |
3392 | /// Return true if the using declaration has 'typename'. |
3393 | bool hasTypename() const { return FirstUsingShadow.getInt(); } |
3394 | |
3395 | /// Sets whether the using declaration has 'typename'. |
3396 | void setTypename(bool TN) { FirstUsingShadow.setInt(TN); } |
3397 | |
3398 | /// Iterates through the using shadow declarations associated with |
3399 | /// this using declaration. |
3400 | class shadow_iterator { |
3401 | /// The current using shadow declaration. |
3402 | UsingShadowDecl *Current = nullptr; |
3403 | |
3404 | public: |
3405 | using value_type = UsingShadowDecl *; |
3406 | using reference = UsingShadowDecl *; |
3407 | using pointer = UsingShadowDecl *; |
3408 | using iterator_category = std::forward_iterator_tag; |
3409 | using difference_type = std::ptrdiff_t; |
3410 | |
3411 | shadow_iterator() = default; |
3412 | explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {} |
3413 | |
3414 | reference operator*() const { return Current; } |
3415 | pointer operator->() const { return Current; } |
3416 | |
3417 | shadow_iterator& operator++() { |
3418 | Current = Current->getNextUsingShadowDecl(); |
3419 | return *this; |
3420 | } |
3421 | |
3422 | shadow_iterator operator++(int) { |
3423 | shadow_iterator tmp(*this); |
3424 | ++(*this); |
3425 | return tmp; |
3426 | } |
3427 | |
3428 | friend bool operator==(shadow_iterator x, shadow_iterator y) { |
3429 | return x.Current == y.Current; |
3430 | } |
3431 | friend bool operator!=(shadow_iterator x, shadow_iterator y) { |
3432 | return x.Current != y.Current; |
3433 | } |
3434 | }; |
3435 | |
3436 | using shadow_range = llvm::iterator_range<shadow_iterator>; |
3437 | |
3438 | shadow_range shadows() const { |
3439 | return shadow_range(shadow_begin(), shadow_end()); |
3440 | } |
3441 | |
3442 | shadow_iterator shadow_begin() const { |
3443 | return shadow_iterator(FirstUsingShadow.getPointer()); |
3444 | } |
3445 | |
3446 | shadow_iterator shadow_end() const { return shadow_iterator(); } |
3447 | |
3448 | /// Return the number of shadowed declarations associated with this |
3449 | /// using declaration. |
3450 | unsigned shadow_size() const { |
3451 | return std::distance(shadow_begin(), shadow_end()); |
3452 | } |
3453 | |
3454 | void addShadowDecl(UsingShadowDecl *S); |
3455 | void removeShadowDecl(UsingShadowDecl *S); |
3456 | |
3457 | static UsingDecl *Create(ASTContext &C, DeclContext *DC, |
3458 | SourceLocation UsingL, |
3459 | NestedNameSpecifierLoc QualifierLoc, |
3460 | const DeclarationNameInfo &NameInfo, |
3461 | bool HasTypenameKeyword); |
3462 | |
3463 | static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3464 | |
3465 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3466 | |
3467 | /// Retrieves the canonical declaration of this declaration. |
3468 | UsingDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3469 | const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3470 | |
3471 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3472 | static bool classofKind(Kind K) { return K == Using; } |
3473 | }; |
3474 | |
3475 | /// Represents a pack of using declarations that a single |
3476 | /// using-declarator pack-expanded into. |
3477 | /// |
3478 | /// \code |
3479 | /// template<typename ...T> struct X : T... { |
3480 | /// using T::operator()...; |
3481 | /// using T::operator T...; |
3482 | /// }; |
3483 | /// \endcode |
3484 | /// |
3485 | /// In the second case above, the UsingPackDecl will have the name |
3486 | /// 'operator T' (which contains an unexpanded pack), but the individual |
3487 | /// UsingDecls and UsingShadowDecls will have more reasonable names. |
3488 | class UsingPackDecl final |
3489 | : public NamedDecl, public Mergeable<UsingPackDecl>, |
3490 | private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> { |
3491 | /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from |
3492 | /// which this waas instantiated. |
3493 | NamedDecl *InstantiatedFrom; |
3494 | |
3495 | /// The number of using-declarations created by this pack expansion. |
3496 | unsigned NumExpansions; |
3497 | |
3498 | UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom, |
3499 | ArrayRef<NamedDecl *> UsingDecls) |
3500 | : NamedDecl(UsingPack, DC, |
3501 | InstantiatedFrom ? InstantiatedFrom->getLocation() |
3502 | : SourceLocation(), |
3503 | InstantiatedFrom ? InstantiatedFrom->getDeclName() |
3504 | : DeclarationName()), |
3505 | InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) { |
3506 | std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(), |
3507 | getTrailingObjects<NamedDecl *>()); |
3508 | } |
3509 | |
3510 | void anchor() override; |
3511 | |
3512 | public: |
3513 | friend class ASTDeclReader; |
3514 | friend class ASTDeclWriter; |
3515 | friend TrailingObjects; |
3516 | |
3517 | /// Get the using declaration from which this was instantiated. This will |
3518 | /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl |
3519 | /// that is a pack expansion. |
3520 | NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; } |
3521 | |
3522 | /// Get the set of using declarations that this pack expanded into. Note that |
3523 | /// some of these may still be unresolved. |
3524 | ArrayRef<NamedDecl *> expansions() const { |
3525 | return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions); |
3526 | } |
3527 | |
3528 | static UsingPackDecl *Create(ASTContext &C, DeclContext *DC, |
3529 | NamedDecl *InstantiatedFrom, |
3530 | ArrayRef<NamedDecl *> UsingDecls); |
3531 | |
3532 | static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
3533 | unsigned NumExpansions); |
3534 | |
3535 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3536 | return InstantiatedFrom->getSourceRange(); |
3537 | } |
3538 | |
3539 | UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3540 | const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3541 | |
3542 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3543 | static bool classofKind(Kind K) { return K == UsingPack; } |
3544 | }; |
3545 | |
3546 | /// Represents a dependent using declaration which was not marked with |
3547 | /// \c typename. |
3548 | /// |
3549 | /// Unlike non-dependent using declarations, these *only* bring through |
3550 | /// non-types; otherwise they would break two-phase lookup. |
3551 | /// |
3552 | /// \code |
3553 | /// template \<class T> class A : public Base<T> { |
3554 | /// using Base<T>::foo; |
3555 | /// }; |
3556 | /// \endcode |
3557 | class UnresolvedUsingValueDecl : public ValueDecl, |
3558 | public Mergeable<UnresolvedUsingValueDecl> { |
3559 | /// The source location of the 'using' keyword |
3560 | SourceLocation UsingLocation; |
3561 | |
3562 | /// If this is a pack expansion, the location of the '...'. |
3563 | SourceLocation EllipsisLoc; |
3564 | |
3565 | /// The nested-name-specifier that precedes the name. |
3566 | NestedNameSpecifierLoc QualifierLoc; |
3567 | |
3568 | /// Provides source/type location info for the declaration name |
3569 | /// embedded in the ValueDecl base class. |
3570 | DeclarationNameLoc DNLoc; |
3571 | |
3572 | UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty, |
3573 | SourceLocation UsingLoc, |
3574 | NestedNameSpecifierLoc QualifierLoc, |
3575 | const DeclarationNameInfo &NameInfo, |
3576 | SourceLocation EllipsisLoc) |
3577 | : ValueDecl(UnresolvedUsingValue, DC, |
3578 | NameInfo.getLoc(), NameInfo.getName(), Ty), |
3579 | UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc), |
3580 | QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {} |
3581 | |
3582 | void anchor() override; |
3583 | |
3584 | public: |
3585 | friend class ASTDeclReader; |
3586 | friend class ASTDeclWriter; |
3587 | |
3588 | /// Returns the source location of the 'using' keyword. |
3589 | SourceLocation getUsingLoc() const { return UsingLocation; } |
3590 | |
3591 | /// Set the source location of the 'using' keyword. |
3592 | void setUsingLoc(SourceLocation L) { UsingLocation = L; } |
3593 | |
3594 | /// Return true if it is a C++03 access declaration (no 'using'). |
3595 | bool isAccessDeclaration() const { return UsingLocation.isInvalid(); } |
3596 | |
3597 | /// Retrieve the nested-name-specifier that qualifies the name, |
3598 | /// with source-location information. |
3599 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
3600 | |
3601 | /// Retrieve the nested-name-specifier that qualifies the name. |
3602 | NestedNameSpecifier *getQualifier() const { |
3603 | return QualifierLoc.getNestedNameSpecifier(); |
3604 | } |
3605 | |
3606 | DeclarationNameInfo getNameInfo() const { |
3607 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
3608 | } |
3609 | |
3610 | /// Determine whether this is a pack expansion. |
3611 | bool isPackExpansion() const { |
3612 | return EllipsisLoc.isValid(); |
3613 | } |
3614 | |
3615 | /// Get the location of the ellipsis if this is a pack expansion. |
3616 | SourceLocation getEllipsisLoc() const { |
3617 | return EllipsisLoc; |
3618 | } |
3619 | |
3620 | static UnresolvedUsingValueDecl * |
3621 | Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, |
3622 | NestedNameSpecifierLoc QualifierLoc, |
3623 | const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc); |
3624 | |
3625 | static UnresolvedUsingValueDecl * |
3626 | CreateDeserialized(ASTContext &C, unsigned ID); |
3627 | |
3628 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3629 | |
3630 | /// Retrieves the canonical declaration of this declaration. |
3631 | UnresolvedUsingValueDecl *getCanonicalDecl() override { |
3632 | return getFirstDecl(); |
3633 | } |
3634 | const UnresolvedUsingValueDecl *getCanonicalDecl() const { |
3635 | return getFirstDecl(); |
3636 | } |
3637 | |
3638 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3639 | static bool classofKind(Kind K) { return K == UnresolvedUsingValue; } |
3640 | }; |
3641 | |
3642 | /// Represents a dependent using declaration which was marked with |
3643 | /// \c typename. |
3644 | /// |
3645 | /// \code |
3646 | /// template \<class T> class A : public Base<T> { |
3647 | /// using typename Base<T>::foo; |
3648 | /// }; |
3649 | /// \endcode |
3650 | /// |
3651 | /// The type associated with an unresolved using typename decl is |
3652 | /// currently always a typename type. |
3653 | class UnresolvedUsingTypenameDecl |
3654 | : public TypeDecl, |
3655 | public Mergeable<UnresolvedUsingTypenameDecl> { |
3656 | friend class ASTDeclReader; |
3657 | |
3658 | /// The source location of the 'typename' keyword |
3659 | SourceLocation TypenameLocation; |
3660 | |
3661 | /// If this is a pack expansion, the location of the '...'. |
3662 | SourceLocation EllipsisLoc; |
3663 | |
3664 | /// The nested-name-specifier that precedes the name. |
3665 | NestedNameSpecifierLoc QualifierLoc; |
3666 | |
3667 | UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc, |
3668 | SourceLocation TypenameLoc, |
3669 | NestedNameSpecifierLoc QualifierLoc, |
3670 | SourceLocation TargetNameLoc, |
3671 | IdentifierInfo *TargetName, |
3672 | SourceLocation EllipsisLoc) |
3673 | : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName, |
3674 | UsingLoc), |
3675 | TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc), |
3676 | QualifierLoc(QualifierLoc) {} |
3677 | |
3678 | void anchor() override; |
3679 | |
3680 | public: |
3681 | /// Returns the source location of the 'using' keyword. |
3682 | SourceLocation getUsingLoc() const { return getBeginLoc(); } |
3683 | |
3684 | /// Returns the source location of the 'typename' keyword. |
3685 | SourceLocation getTypenameLoc() const { return TypenameLocation; } |
3686 | |
3687 | /// Retrieve the nested-name-specifier that qualifies the name, |
3688 | /// with source-location information. |
3689 | NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } |
3690 | |
3691 | /// Retrieve the nested-name-specifier that qualifies the name. |
3692 | NestedNameSpecifier *getQualifier() const { |
3693 | return QualifierLoc.getNestedNameSpecifier(); |
3694 | } |
3695 | |
3696 | DeclarationNameInfo getNameInfo() const { |
3697 | return DeclarationNameInfo(getDeclName(), getLocation()); |
3698 | } |
3699 | |
3700 | /// Determine whether this is a pack expansion. |
3701 | bool isPackExpansion() const { |
3702 | return EllipsisLoc.isValid(); |
3703 | } |
3704 | |
3705 | /// Get the location of the ellipsis if this is a pack expansion. |
3706 | SourceLocation getEllipsisLoc() const { |
3707 | return EllipsisLoc; |
3708 | } |
3709 | |
3710 | static UnresolvedUsingTypenameDecl * |
3711 | Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc, |
3712 | SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc, |
3713 | SourceLocation TargetNameLoc, DeclarationName TargetName, |
3714 | SourceLocation EllipsisLoc); |
3715 | |
3716 | static UnresolvedUsingTypenameDecl * |
3717 | CreateDeserialized(ASTContext &C, unsigned ID); |
3718 | |
3719 | /// Retrieves the canonical declaration of this declaration. |
3720 | UnresolvedUsingTypenameDecl *getCanonicalDecl() override { |
3721 | return getFirstDecl(); |
3722 | } |
3723 | const UnresolvedUsingTypenameDecl *getCanonicalDecl() const { |
3724 | return getFirstDecl(); |
3725 | } |
3726 | |
3727 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3728 | static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; } |
3729 | }; |
3730 | |
3731 | /// Represents a C++11 static_assert declaration. |
3732 | class StaticAssertDecl : public Decl { |
3733 | llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed; |
3734 | StringLiteral *Message; |
3735 | SourceLocation RParenLoc; |
3736 | |
3737 | StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc, |
3738 | Expr *AssertExpr, StringLiteral *Message, |
3739 | SourceLocation RParenLoc, bool Failed) |
3740 | : Decl(StaticAssert, DC, StaticAssertLoc), |
3741 | AssertExprAndFailed(AssertExpr, Failed), Message(Message), |
3742 | RParenLoc(RParenLoc) {} |
3743 | |
3744 | virtual void anchor(); |
3745 | |
3746 | public: |
3747 | friend class ASTDeclReader; |
3748 | |
3749 | static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC, |
3750 | SourceLocation StaticAssertLoc, |
3751 | Expr *AssertExpr, StringLiteral *Message, |
3752 | SourceLocation RParenLoc, bool Failed); |
3753 | static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3754 | |
3755 | Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); } |
3756 | const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); } |
3757 | |
3758 | StringLiteral *getMessage() { return Message; } |
3759 | const StringLiteral *getMessage() const { return Message; } |
3760 | |
3761 | bool isFailed() const { return AssertExprAndFailed.getInt(); } |
3762 | |
3763 | SourceLocation getRParenLoc() const { return RParenLoc; } |
3764 | |
3765 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3766 | return SourceRange(getLocation(), getRParenLoc()); |
3767 | } |
3768 | |
3769 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3770 | static bool classofKind(Kind K) { return K == StaticAssert; } |
3771 | }; |
3772 | |
3773 | /// A binding in a decomposition declaration. For instance, given: |
3774 | /// |
3775 | /// int n[3]; |
3776 | /// auto &[a, b, c] = n; |
3777 | /// |
3778 | /// a, b, and c are BindingDecls, whose bindings are the expressions |
3779 | /// x[0], x[1], and x[2] respectively, where x is the implicit |
3780 | /// DecompositionDecl of type 'int (&)[3]'. |
3781 | class BindingDecl : public ValueDecl { |
3782 | /// The declaration that this binding binds to part of. |
3783 | LazyDeclPtr Decomp; |
3784 | /// The binding represented by this declaration. References to this |
3785 | /// declaration are effectively equivalent to this expression (except |
3786 | /// that it is only evaluated once at the point of declaration of the |
3787 | /// binding). |
3788 | Expr *Binding = nullptr; |
3789 | |
3790 | BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id) |
3791 | : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {} |
3792 | |
3793 | void anchor() override; |
3794 | |
3795 | public: |
3796 | friend class ASTDeclReader; |
3797 | |
3798 | static BindingDecl *Create(ASTContext &C, DeclContext *DC, |
3799 | SourceLocation IdLoc, IdentifierInfo *Id); |
3800 | static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3801 | |
3802 | /// Get the expression to which this declaration is bound. This may be null |
3803 | /// in two different cases: while parsing the initializer for the |
3804 | /// decomposition declaration, and when the initializer is type-dependent. |
3805 | Expr *getBinding() const { return Binding; } |
3806 | |
3807 | /// Get the decomposition declaration that this binding represents a |
3808 | /// decomposition of. |
3809 | ValueDecl *getDecomposedDecl() const; |
3810 | |
3811 | /// Get the variable (if any) that holds the value of evaluating the binding. |
3812 | /// Only present for user-defined bindings for tuple-like types. |
3813 | VarDecl *getHoldingVar() const; |
3814 | |
3815 | /// Set the binding for this BindingDecl, along with its declared type (which |
3816 | /// should be a possibly-cv-qualified form of the type of the binding, or a |
3817 | /// reference to such a type). |
3818 | void setBinding(QualType DeclaredType, Expr *Binding) { |
3819 | setType(DeclaredType); |
3820 | this->Binding = Binding; |
3821 | } |
3822 | |
3823 | /// Set the decomposed variable for this BindingDecl. |
3824 | void setDecomposedDecl(ValueDecl *Decomposed) { Decomp = Decomposed; } |
3825 | |
3826 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3827 | static bool classofKind(Kind K) { return K == Decl::Binding; } |
3828 | }; |
3829 | |
3830 | /// A decomposition declaration. For instance, given: |
3831 | /// |
3832 | /// int n[3]; |
3833 | /// auto &[a, b, c] = n; |
3834 | /// |
3835 | /// the second line declares a DecompositionDecl of type 'int (&)[3]', and |
3836 | /// three BindingDecls (named a, b, and c). An instance of this class is always |
3837 | /// unnamed, but behaves in almost all other respects like a VarDecl. |
3838 | class DecompositionDecl final |
3839 | : public VarDecl, |
3840 | private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> { |
3841 | /// The number of BindingDecl*s following this object. |
3842 | unsigned NumBindings; |
3843 | |
3844 | DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3845 | SourceLocation LSquareLoc, QualType T, |
3846 | TypeSourceInfo *TInfo, StorageClass SC, |
3847 | ArrayRef<BindingDecl *> Bindings) |
3848 | : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo, |
3849 | SC), |
3850 | NumBindings(Bindings.size()) { |
3851 | std::uninitialized_copy(Bindings.begin(), Bindings.end(), |
3852 | getTrailingObjects<BindingDecl *>()); |
3853 | for (auto *B : Bindings) |
3854 | B->setDecomposedDecl(this); |
3855 | } |
3856 | |
3857 | void anchor() override; |
3858 | |
3859 | public: |
3860 | friend class ASTDeclReader; |
3861 | friend TrailingObjects; |
3862 | |
3863 | static DecompositionDecl *Create(ASTContext &C, DeclContext *DC, |
3864 | SourceLocation StartLoc, |
3865 | SourceLocation LSquareLoc, |
3866 | QualType T, TypeSourceInfo *TInfo, |
3867 | StorageClass S, |
3868 | ArrayRef<BindingDecl *> Bindings); |
3869 | static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
3870 | unsigned NumBindings); |
3871 | |
3872 | ArrayRef<BindingDecl *> bindings() const { |
3873 | return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings); |
3874 | } |
3875 | |
3876 | void printName(raw_ostream &os) const override; |
3877 | |
3878 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3879 | static bool classofKind(Kind K) { return K == Decomposition; } |
3880 | }; |
3881 | |
3882 | /// An instance of this class represents the declaration of a property |
3883 | /// member. This is a Microsoft extension to C++, first introduced in |
3884 | /// Visual Studio .NET 2003 as a parallel to similar features in C# |
3885 | /// and Managed C++. |
3886 | /// |
3887 | /// A property must always be a non-static class member. |
3888 | /// |
3889 | /// A property member superficially resembles a non-static data |
3890 | /// member, except preceded by a property attribute: |
3891 | /// __declspec(property(get=GetX, put=PutX)) int x; |
3892 | /// Either (but not both) of the 'get' and 'put' names may be omitted. |
3893 | /// |
3894 | /// A reference to a property is always an lvalue. If the lvalue |
3895 | /// undergoes lvalue-to-rvalue conversion, then a getter name is |
3896 | /// required, and that member is called with no arguments. |
3897 | /// If the lvalue is assigned into, then a setter name is required, |
3898 | /// and that member is called with one argument, the value assigned. |
3899 | /// Both operations are potentially overloaded. Compound assignments |
3900 | /// are permitted, as are the increment and decrement operators. |
3901 | /// |
3902 | /// The getter and putter methods are permitted to be overloaded, |
3903 | /// although their return and parameter types are subject to certain |
3904 | /// restrictions according to the type of the property. |
3905 | /// |
3906 | /// A property declared using an incomplete array type may |
3907 | /// additionally be subscripted, adding extra parameters to the getter |
3908 | /// and putter methods. |
3909 | class MSPropertyDecl : public DeclaratorDecl { |
3910 | IdentifierInfo *GetterId, *SetterId; |
3911 | |
3912 | MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N, |
3913 | QualType T, TypeSourceInfo *TInfo, SourceLocation StartL, |
3914 | IdentifierInfo *Getter, IdentifierInfo *Setter) |
3915 | : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL), |
3916 | GetterId(Getter), SetterId(Setter) {} |
3917 | |
3918 | void anchor() override; |
3919 | public: |
3920 | friend class ASTDeclReader; |
3921 | |
3922 | static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC, |
3923 | SourceLocation L, DeclarationName N, QualType T, |
3924 | TypeSourceInfo *TInfo, SourceLocation StartL, |
3925 | IdentifierInfo *Getter, IdentifierInfo *Setter); |
3926 | static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3927 | |
3928 | static bool classof(const Decl *D) { return D->getKind() == MSProperty; } |
3929 | |
3930 | bool hasGetter() const { return GetterId != nullptr; } |
3931 | IdentifierInfo* getGetterId() const { return GetterId; } |
3932 | bool hasSetter() const { return SetterId != nullptr; } |
3933 | IdentifierInfo* getSetterId() const { return SetterId; } |
3934 | }; |
3935 | |
3936 | /// Insertion operator for diagnostics. This allows sending an AccessSpecifier |
3937 | /// into a diagnostic with <<. |
3938 | const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
3939 | AccessSpecifier AS); |
3940 | |
3941 | const PartialDiagnostic &operator<<(const PartialDiagnostic &DB, |
3942 | AccessSpecifier AS); |
3943 | |
3944 | } // namespace clang |
3945 | |
3946 | #endif // LLVM_CLANG_AST_DECLCXX_H |