File: | clang/lib/Sema/SemaDecl.cpp |
Warning: | line 13011, column 16 Called C++ object pointer is null |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
1 | //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// | ||||||
2 | // | ||||||
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. | ||||||
4 | // See https://llvm.org/LICENSE.txt for license information. | ||||||
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception | ||||||
6 | // | ||||||
7 | //===----------------------------------------------------------------------===// | ||||||
8 | // | ||||||
9 | // This file implements semantic analysis for declarations. | ||||||
10 | // | ||||||
11 | //===----------------------------------------------------------------------===// | ||||||
12 | |||||||
13 | #include "TypeLocBuilder.h" | ||||||
14 | #include "clang/AST/ASTConsumer.h" | ||||||
15 | #include "clang/AST/ASTContext.h" | ||||||
16 | #include "clang/AST/ASTLambda.h" | ||||||
17 | #include "clang/AST/CXXInheritance.h" | ||||||
18 | #include "clang/AST/CharUnits.h" | ||||||
19 | #include "clang/AST/CommentDiagnostic.h" | ||||||
20 | #include "clang/AST/DeclCXX.h" | ||||||
21 | #include "clang/AST/DeclObjC.h" | ||||||
22 | #include "clang/AST/DeclTemplate.h" | ||||||
23 | #include "clang/AST/EvaluatedExprVisitor.h" | ||||||
24 | #include "clang/AST/Expr.h" | ||||||
25 | #include "clang/AST/ExprCXX.h" | ||||||
26 | #include "clang/AST/NonTrivialTypeVisitor.h" | ||||||
27 | #include "clang/AST/StmtCXX.h" | ||||||
28 | #include "clang/Basic/Builtins.h" | ||||||
29 | #include "clang/Basic/PartialDiagnostic.h" | ||||||
30 | #include "clang/Basic/SourceManager.h" | ||||||
31 | #include "clang/Basic/TargetInfo.h" | ||||||
32 | #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex | ||||||
33 | #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. | ||||||
34 | #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex | ||||||
35 | #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() | ||||||
36 | #include "clang/Sema/CXXFieldCollector.h" | ||||||
37 | #include "clang/Sema/DeclSpec.h" | ||||||
38 | #include "clang/Sema/DelayedDiagnostic.h" | ||||||
39 | #include "clang/Sema/Initialization.h" | ||||||
40 | #include "clang/Sema/Lookup.h" | ||||||
41 | #include "clang/Sema/ParsedTemplate.h" | ||||||
42 | #include "clang/Sema/Scope.h" | ||||||
43 | #include "clang/Sema/ScopeInfo.h" | ||||||
44 | #include "clang/Sema/SemaInternal.h" | ||||||
45 | #include "clang/Sema/Template.h" | ||||||
46 | #include "llvm/ADT/SmallString.h" | ||||||
47 | #include "llvm/ADT/Triple.h" | ||||||
48 | #include <algorithm> | ||||||
49 | #include <cstring> | ||||||
50 | #include <functional> | ||||||
51 | #include <unordered_map> | ||||||
52 | |||||||
53 | using namespace clang; | ||||||
54 | using namespace sema; | ||||||
55 | |||||||
56 | Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { | ||||||
57 | if (OwnedType) { | ||||||
58 | Decl *Group[2] = { OwnedType, Ptr }; | ||||||
59 | return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); | ||||||
60 | } | ||||||
61 | |||||||
62 | return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); | ||||||
63 | } | ||||||
64 | |||||||
65 | namespace { | ||||||
66 | |||||||
67 | class TypeNameValidatorCCC final : public CorrectionCandidateCallback { | ||||||
68 | public: | ||||||
69 | TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, | ||||||
70 | bool AllowTemplates = false, | ||||||
71 | bool AllowNonTemplates = true) | ||||||
72 | : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), | ||||||
73 | AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { | ||||||
74 | WantExpressionKeywords = false; | ||||||
75 | WantCXXNamedCasts = false; | ||||||
76 | WantRemainingKeywords = false; | ||||||
77 | } | ||||||
78 | |||||||
79 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||
80 | if (NamedDecl *ND = candidate.getCorrectionDecl()) { | ||||||
81 | if (!AllowInvalidDecl && ND->isInvalidDecl()) | ||||||
82 | return false; | ||||||
83 | |||||||
84 | if (getAsTypeTemplateDecl(ND)) | ||||||
85 | return AllowTemplates; | ||||||
86 | |||||||
87 | bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); | ||||||
88 | if (!IsType) | ||||||
89 | return false; | ||||||
90 | |||||||
91 | if (AllowNonTemplates) | ||||||
92 | return true; | ||||||
93 | |||||||
94 | // An injected-class-name of a class template (specialization) is valid | ||||||
95 | // as a template or as a non-template. | ||||||
96 | if (AllowTemplates) { | ||||||
97 | auto *RD = dyn_cast<CXXRecordDecl>(ND); | ||||||
98 | if (!RD || !RD->isInjectedClassName()) | ||||||
99 | return false; | ||||||
100 | RD = cast<CXXRecordDecl>(RD->getDeclContext()); | ||||||
101 | return RD->getDescribedClassTemplate() || | ||||||
102 | isa<ClassTemplateSpecializationDecl>(RD); | ||||||
103 | } | ||||||
104 | |||||||
105 | return false; | ||||||
106 | } | ||||||
107 | |||||||
108 | return !WantClassName && candidate.isKeyword(); | ||||||
109 | } | ||||||
110 | |||||||
111 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||
112 | return std::make_unique<TypeNameValidatorCCC>(*this); | ||||||
113 | } | ||||||
114 | |||||||
115 | private: | ||||||
116 | bool AllowInvalidDecl; | ||||||
117 | bool WantClassName; | ||||||
118 | bool AllowTemplates; | ||||||
119 | bool AllowNonTemplates; | ||||||
120 | }; | ||||||
121 | |||||||
122 | } // end anonymous namespace | ||||||
123 | |||||||
124 | /// Determine whether the token kind starts a simple-type-specifier. | ||||||
125 | bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { | ||||||
126 | switch (Kind) { | ||||||
127 | // FIXME: Take into account the current language when deciding whether a | ||||||
128 | // token kind is a valid type specifier | ||||||
129 | case tok::kw_short: | ||||||
130 | case tok::kw_long: | ||||||
131 | case tok::kw___int64: | ||||||
132 | case tok::kw___int128: | ||||||
133 | case tok::kw_signed: | ||||||
134 | case tok::kw_unsigned: | ||||||
135 | case tok::kw_void: | ||||||
136 | case tok::kw_char: | ||||||
137 | case tok::kw_int: | ||||||
138 | case tok::kw_half: | ||||||
139 | case tok::kw_float: | ||||||
140 | case tok::kw_double: | ||||||
141 | case tok::kw___bf16: | ||||||
142 | case tok::kw__Float16: | ||||||
143 | case tok::kw___float128: | ||||||
144 | case tok::kw_wchar_t: | ||||||
145 | case tok::kw_bool: | ||||||
146 | case tok::kw___underlying_type: | ||||||
147 | case tok::kw___auto_type: | ||||||
148 | return true; | ||||||
149 | |||||||
150 | case tok::annot_typename: | ||||||
151 | case tok::kw_char16_t: | ||||||
152 | case tok::kw_char32_t: | ||||||
153 | case tok::kw_typeof: | ||||||
154 | case tok::annot_decltype: | ||||||
155 | case tok::kw_decltype: | ||||||
156 | return getLangOpts().CPlusPlus; | ||||||
157 | |||||||
158 | case tok::kw_char8_t: | ||||||
159 | return getLangOpts().Char8; | ||||||
160 | |||||||
161 | default: | ||||||
162 | break; | ||||||
163 | } | ||||||
164 | |||||||
165 | return false; | ||||||
166 | } | ||||||
167 | |||||||
168 | namespace { | ||||||
169 | enum class UnqualifiedTypeNameLookupResult { | ||||||
170 | NotFound, | ||||||
171 | FoundNonType, | ||||||
172 | FoundType | ||||||
173 | }; | ||||||
174 | } // end anonymous namespace | ||||||
175 | |||||||
176 | /// Tries to perform unqualified lookup of the type decls in bases for | ||||||
177 | /// dependent class. | ||||||
178 | /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a | ||||||
179 | /// type decl, \a FoundType if only type decls are found. | ||||||
180 | static UnqualifiedTypeNameLookupResult | ||||||
181 | lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, | ||||||
182 | SourceLocation NameLoc, | ||||||
183 | const CXXRecordDecl *RD) { | ||||||
184 | if (!RD->hasDefinition()) | ||||||
185 | return UnqualifiedTypeNameLookupResult::NotFound; | ||||||
186 | // Look for type decls in base classes. | ||||||
187 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||||
188 | UnqualifiedTypeNameLookupResult::NotFound; | ||||||
189 | for (const auto &Base : RD->bases()) { | ||||||
190 | const CXXRecordDecl *BaseRD = nullptr; | ||||||
191 | if (auto *BaseTT = Base.getType()->getAs<TagType>()) | ||||||
192 | BaseRD = BaseTT->getAsCXXRecordDecl(); | ||||||
193 | else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { | ||||||
194 | // Look for type decls in dependent base classes that have known primary | ||||||
195 | // templates. | ||||||
196 | if (!TST || !TST->isDependentType()) | ||||||
197 | continue; | ||||||
198 | auto *TD = TST->getTemplateName().getAsTemplateDecl(); | ||||||
199 | if (!TD) | ||||||
200 | continue; | ||||||
201 | if (auto *BasePrimaryTemplate = | ||||||
202 | dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { | ||||||
203 | if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||||
204 | BaseRD = BasePrimaryTemplate; | ||||||
205 | else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { | ||||||
206 | if (const ClassTemplatePartialSpecializationDecl *PS = | ||||||
207 | CTD->findPartialSpecialization(Base.getType())) | ||||||
208 | if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) | ||||||
209 | BaseRD = PS; | ||||||
210 | } | ||||||
211 | } | ||||||
212 | } | ||||||
213 | if (BaseRD) { | ||||||
214 | for (NamedDecl *ND : BaseRD->lookup(&II)) { | ||||||
215 | if (!isa<TypeDecl>(ND)) | ||||||
216 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||||
217 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||||
218 | } | ||||||
219 | if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { | ||||||
220 | switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { | ||||||
221 | case UnqualifiedTypeNameLookupResult::FoundNonType: | ||||||
222 | return UnqualifiedTypeNameLookupResult::FoundNonType; | ||||||
223 | case UnqualifiedTypeNameLookupResult::FoundType: | ||||||
224 | FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; | ||||||
225 | break; | ||||||
226 | case UnqualifiedTypeNameLookupResult::NotFound: | ||||||
227 | break; | ||||||
228 | } | ||||||
229 | } | ||||||
230 | } | ||||||
231 | } | ||||||
232 | |||||||
233 | return FoundTypeDecl; | ||||||
234 | } | ||||||
235 | |||||||
236 | static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, | ||||||
237 | const IdentifierInfo &II, | ||||||
238 | SourceLocation NameLoc) { | ||||||
239 | // Lookup in the parent class template context, if any. | ||||||
240 | const CXXRecordDecl *RD = nullptr; | ||||||
241 | UnqualifiedTypeNameLookupResult FoundTypeDecl = | ||||||
242 | UnqualifiedTypeNameLookupResult::NotFound; | ||||||
243 | for (DeclContext *DC = S.CurContext; | ||||||
244 | DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; | ||||||
245 | DC = DC->getParent()) { | ||||||
246 | // Look for type decls in dependent base classes that have known primary | ||||||
247 | // templates. | ||||||
248 | RD = dyn_cast<CXXRecordDecl>(DC); | ||||||
249 | if (RD && RD->getDescribedClassTemplate()) | ||||||
250 | FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); | ||||||
251 | } | ||||||
252 | if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) | ||||||
253 | return nullptr; | ||||||
254 | |||||||
255 | // We found some types in dependent base classes. Recover as if the user | ||||||
256 | // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the | ||||||
257 | // lookup during template instantiation. | ||||||
258 | S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; | ||||||
259 | |||||||
260 | ASTContext &Context = S.Context; | ||||||
261 | auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, | ||||||
262 | cast<Type>(Context.getRecordType(RD))); | ||||||
263 | QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); | ||||||
264 | |||||||
265 | CXXScopeSpec SS; | ||||||
266 | SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
267 | |||||||
268 | TypeLocBuilder Builder; | ||||||
269 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||||
270 | DepTL.setNameLoc(NameLoc); | ||||||
271 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
272 | DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||
273 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
274 | } | ||||||
275 | |||||||
276 | /// If the identifier refers to a type name within this scope, | ||||||
277 | /// return the declaration of that type. | ||||||
278 | /// | ||||||
279 | /// This routine performs ordinary name lookup of the identifier II | ||||||
280 | /// within the given scope, with optional C++ scope specifier SS, to | ||||||
281 | /// determine whether the name refers to a type. If so, returns an | ||||||
282 | /// opaque pointer (actually a QualType) corresponding to that | ||||||
283 | /// type. Otherwise, returns NULL. | ||||||
284 | ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, | ||||||
285 | Scope *S, CXXScopeSpec *SS, | ||||||
286 | bool isClassName, bool HasTrailingDot, | ||||||
287 | ParsedType ObjectTypePtr, | ||||||
288 | bool IsCtorOrDtorName, | ||||||
289 | bool WantNontrivialTypeSourceInfo, | ||||||
290 | bool IsClassTemplateDeductionContext, | ||||||
291 | IdentifierInfo **CorrectedII) { | ||||||
292 | // FIXME: Consider allowing this outside C++1z mode as an extension. | ||||||
293 | bool AllowDeducedTemplate = IsClassTemplateDeductionContext && | ||||||
294 | getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && | ||||||
295 | !isClassName && !HasTrailingDot; | ||||||
296 | |||||||
297 | // Determine where we will perform name lookup. | ||||||
298 | DeclContext *LookupCtx = nullptr; | ||||||
299 | if (ObjectTypePtr) { | ||||||
300 | QualType ObjectType = ObjectTypePtr.get(); | ||||||
301 | if (ObjectType->isRecordType()) | ||||||
302 | LookupCtx = computeDeclContext(ObjectType); | ||||||
303 | } else if (SS && SS->isNotEmpty()) { | ||||||
304 | LookupCtx = computeDeclContext(*SS, false); | ||||||
305 | |||||||
306 | if (!LookupCtx) { | ||||||
307 | if (isDependentScopeSpecifier(*SS)) { | ||||||
308 | // C++ [temp.res]p3: | ||||||
309 | // A qualified-id that refers to a type and in which the | ||||||
310 | // nested-name-specifier depends on a template-parameter (14.6.2) | ||||||
311 | // shall be prefixed by the keyword typename to indicate that the | ||||||
312 | // qualified-id denotes a type, forming an | ||||||
313 | // elaborated-type-specifier (7.1.5.3). | ||||||
314 | // | ||||||
315 | // We therefore do not perform any name lookup if the result would | ||||||
316 | // refer to a member of an unknown specialization. | ||||||
317 | if (!isClassName && !IsCtorOrDtorName) | ||||||
318 | return nullptr; | ||||||
319 | |||||||
320 | // We know from the grammar that this name refers to a type, | ||||||
321 | // so build a dependent node to describe the type. | ||||||
322 | if (WantNontrivialTypeSourceInfo) | ||||||
323 | return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); | ||||||
324 | |||||||
325 | NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); | ||||||
326 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, | ||||||
327 | II, NameLoc); | ||||||
328 | return ParsedType::make(T); | ||||||
329 | } | ||||||
330 | |||||||
331 | return nullptr; | ||||||
332 | } | ||||||
333 | |||||||
334 | if (!LookupCtx->isDependentContext() && | ||||||
335 | RequireCompleteDeclContext(*SS, LookupCtx)) | ||||||
336 | return nullptr; | ||||||
337 | } | ||||||
338 | |||||||
339 | // FIXME: LookupNestedNameSpecifierName isn't the right kind of | ||||||
340 | // lookup for class-names. | ||||||
341 | LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : | ||||||
342 | LookupOrdinaryName; | ||||||
343 | LookupResult Result(*this, &II, NameLoc, Kind); | ||||||
344 | if (LookupCtx) { | ||||||
345 | // Perform "qualified" name lookup into the declaration context we | ||||||
346 | // computed, which is either the type of the base of a member access | ||||||
347 | // expression or the declaration context associated with a prior | ||||||
348 | // nested-name-specifier. | ||||||
349 | LookupQualifiedName(Result, LookupCtx); | ||||||
350 | |||||||
351 | if (ObjectTypePtr && Result.empty()) { | ||||||
352 | // C++ [basic.lookup.classref]p3: | ||||||
353 | // If the unqualified-id is ~type-name, the type-name is looked up | ||||||
354 | // in the context of the entire postfix-expression. If the type T of | ||||||
355 | // the object expression is of a class type C, the type-name is also | ||||||
356 | // looked up in the scope of class C. At least one of the lookups shall | ||||||
357 | // find a name that refers to (possibly cv-qualified) T. | ||||||
358 | LookupName(Result, S); | ||||||
359 | } | ||||||
360 | } else { | ||||||
361 | // Perform unqualified name lookup. | ||||||
362 | LookupName(Result, S); | ||||||
363 | |||||||
364 | // For unqualified lookup in a class template in MSVC mode, look into | ||||||
365 | // dependent base classes where the primary class template is known. | ||||||
366 | if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { | ||||||
367 | if (ParsedType TypeInBase = | ||||||
368 | recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) | ||||||
369 | return TypeInBase; | ||||||
370 | } | ||||||
371 | } | ||||||
372 | |||||||
373 | NamedDecl *IIDecl = nullptr; | ||||||
374 | switch (Result.getResultKind()) { | ||||||
375 | case LookupResult::NotFound: | ||||||
376 | case LookupResult::NotFoundInCurrentInstantiation: | ||||||
377 | if (CorrectedII) { | ||||||
378 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, | ||||||
379 | AllowDeducedTemplate); | ||||||
380 | TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, | ||||||
381 | S, SS, CCC, CTK_ErrorRecovery); | ||||||
382 | IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); | ||||||
383 | TemplateTy Template; | ||||||
384 | bool MemberOfUnknownSpecialization; | ||||||
385 | UnqualifiedId TemplateName; | ||||||
386 | TemplateName.setIdentifier(NewII, NameLoc); | ||||||
387 | NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); | ||||||
388 | CXXScopeSpec NewSS, *NewSSPtr = SS; | ||||||
389 | if (SS && NNS) { | ||||||
390 | NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
391 | NewSSPtr = &NewSS; | ||||||
392 | } | ||||||
393 | if (Correction && (NNS || NewII != &II) && | ||||||
394 | // Ignore a correction to a template type as the to-be-corrected | ||||||
395 | // identifier is not a template (typo correction for template names | ||||||
396 | // is handled elsewhere). | ||||||
397 | !(getLangOpts().CPlusPlus && NewSSPtr && | ||||||
398 | isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, | ||||||
399 | Template, MemberOfUnknownSpecialization))) { | ||||||
400 | ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, | ||||||
401 | isClassName, HasTrailingDot, ObjectTypePtr, | ||||||
402 | IsCtorOrDtorName, | ||||||
403 | WantNontrivialTypeSourceInfo, | ||||||
404 | IsClassTemplateDeductionContext); | ||||||
405 | if (Ty) { | ||||||
406 | diagnoseTypo(Correction, | ||||||
407 | PDiag(diag::err_unknown_type_or_class_name_suggest) | ||||||
408 | << Result.getLookupName() << isClassName); | ||||||
409 | if (SS && NNS) | ||||||
410 | SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
411 | *CorrectedII = NewII; | ||||||
412 | return Ty; | ||||||
413 | } | ||||||
414 | } | ||||||
415 | } | ||||||
416 | // If typo correction failed or was not performed, fall through | ||||||
417 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
418 | case LookupResult::FoundOverloaded: | ||||||
419 | case LookupResult::FoundUnresolvedValue: | ||||||
420 | Result.suppressDiagnostics(); | ||||||
421 | return nullptr; | ||||||
422 | |||||||
423 | case LookupResult::Ambiguous: | ||||||
424 | // Recover from type-hiding ambiguities by hiding the type. We'll | ||||||
425 | // do the lookup again when looking for an object, and we can | ||||||
426 | // diagnose the error then. If we don't do this, then the error | ||||||
427 | // about hiding the type will be immediately followed by an error | ||||||
428 | // that only makes sense if the identifier was treated like a type. | ||||||
429 | if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { | ||||||
430 | Result.suppressDiagnostics(); | ||||||
431 | return nullptr; | ||||||
432 | } | ||||||
433 | |||||||
434 | // Look to see if we have a type anywhere in the list of results. | ||||||
435 | for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); | ||||||
436 | Res != ResEnd; ++Res) { | ||||||
437 | if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || | ||||||
438 | (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { | ||||||
439 | if (!IIDecl || | ||||||
440 | (*Res)->getLocation().getRawEncoding() < | ||||||
441 | IIDecl->getLocation().getRawEncoding()) | ||||||
442 | IIDecl = *Res; | ||||||
443 | } | ||||||
444 | } | ||||||
445 | |||||||
446 | if (!IIDecl) { | ||||||
447 | // None of the entities we found is a type, so there is no way | ||||||
448 | // to even assume that the result is a type. In this case, don't | ||||||
449 | // complain about the ambiguity. The parser will either try to | ||||||
450 | // perform this lookup again (e.g., as an object name), which | ||||||
451 | // will produce the ambiguity, or will complain that it expected | ||||||
452 | // a type name. | ||||||
453 | Result.suppressDiagnostics(); | ||||||
454 | return nullptr; | ||||||
455 | } | ||||||
456 | |||||||
457 | // We found a type within the ambiguous lookup; diagnose the | ||||||
458 | // ambiguity and then return that type. This might be the right | ||||||
459 | // answer, or it might not be, but it suppresses any attempt to | ||||||
460 | // perform the name lookup again. | ||||||
461 | break; | ||||||
462 | |||||||
463 | case LookupResult::Found: | ||||||
464 | IIDecl = Result.getFoundDecl(); | ||||||
465 | break; | ||||||
466 | } | ||||||
467 | |||||||
468 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 468, __PRETTY_FUNCTION__)); | ||||||
469 | |||||||
470 | QualType T; | ||||||
471 | if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { | ||||||
472 | // C++ [class.qual]p2: A lookup that would find the injected-class-name | ||||||
473 | // instead names the constructors of the class, except when naming a class. | ||||||
474 | // This is ill-formed when we're not actually forming a ctor or dtor name. | ||||||
475 | auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); | ||||||
476 | auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); | ||||||
477 | if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && | ||||||
478 | FoundRD->isInjectedClassName() && | ||||||
479 | declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) | ||||||
480 | Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) | ||||||
481 | << &II << /*Type*/1; | ||||||
482 | |||||||
483 | DiagnoseUseOfDecl(IIDecl, NameLoc); | ||||||
484 | |||||||
485 | T = Context.getTypeDeclType(TD); | ||||||
486 | MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); | ||||||
487 | } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { | ||||||
488 | (void)DiagnoseUseOfDecl(IDecl, NameLoc); | ||||||
489 | if (!HasTrailingDot) | ||||||
490 | T = Context.getObjCInterfaceType(IDecl); | ||||||
491 | } else if (AllowDeducedTemplate) { | ||||||
492 | if (auto *TD = getAsTypeTemplateDecl(IIDecl)) | ||||||
493 | T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), | ||||||
494 | QualType(), false); | ||||||
495 | } | ||||||
496 | |||||||
497 | if (T.isNull()) { | ||||||
498 | // If it's not plausibly a type, suppress diagnostics. | ||||||
499 | Result.suppressDiagnostics(); | ||||||
500 | return nullptr; | ||||||
501 | } | ||||||
502 | |||||||
503 | // NOTE: avoid constructing an ElaboratedType(Loc) if this is a | ||||||
504 | // constructor or destructor name (in such a case, the scope specifier | ||||||
505 | // will be attached to the enclosing Expr or Decl node). | ||||||
506 | if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && | ||||||
507 | !isa<ObjCInterfaceDecl>(IIDecl)) { | ||||||
508 | if (WantNontrivialTypeSourceInfo) { | ||||||
509 | // Construct a type with type-source information. | ||||||
510 | TypeLocBuilder Builder; | ||||||
511 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||||
512 | |||||||
513 | T = getElaboratedType(ETK_None, *SS, T); | ||||||
514 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||||
515 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
516 | ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); | ||||||
517 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
518 | } else { | ||||||
519 | T = getElaboratedType(ETK_None, *SS, T); | ||||||
520 | } | ||||||
521 | } | ||||||
522 | |||||||
523 | return ParsedType::make(T); | ||||||
524 | } | ||||||
525 | |||||||
526 | // Builds a fake NNS for the given decl context. | ||||||
527 | static NestedNameSpecifier * | ||||||
528 | synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { | ||||||
529 | for (;; DC = DC->getLookupParent()) { | ||||||
530 | DC = DC->getPrimaryContext(); | ||||||
531 | auto *ND = dyn_cast<NamespaceDecl>(DC); | ||||||
532 | if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) | ||||||
533 | return NestedNameSpecifier::Create(Context, nullptr, ND); | ||||||
534 | else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) | ||||||
535 | return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||||
536 | RD->getTypeForDecl()); | ||||||
537 | else if (isa<TranslationUnitDecl>(DC)) | ||||||
538 | return NestedNameSpecifier::GlobalSpecifier(Context); | ||||||
539 | } | ||||||
540 | llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 540); | ||||||
541 | } | ||||||
542 | |||||||
543 | /// Find the parent class with dependent bases of the innermost enclosing method | ||||||
544 | /// context. Do not look for enclosing CXXRecordDecls directly, or we will end | ||||||
545 | /// up allowing unqualified dependent type names at class-level, which MSVC | ||||||
546 | /// correctly rejects. | ||||||
547 | static const CXXRecordDecl * | ||||||
548 | findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { | ||||||
549 | for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { | ||||||
550 | DC = DC->getPrimaryContext(); | ||||||
551 | if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) | ||||||
552 | if (MD->getParent()->hasAnyDependentBases()) | ||||||
553 | return MD->getParent(); | ||||||
554 | } | ||||||
555 | return nullptr; | ||||||
556 | } | ||||||
557 | |||||||
558 | ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, | ||||||
559 | SourceLocation NameLoc, | ||||||
560 | bool IsTemplateTypeArg) { | ||||||
561 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 561, __PRETTY_FUNCTION__)); | ||||||
562 | |||||||
563 | NestedNameSpecifier *NNS = nullptr; | ||||||
564 | if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { | ||||||
565 | // If we weren't able to parse a default template argument, delay lookup | ||||||
566 | // until instantiation time by making a non-dependent DependentTypeName. We | ||||||
567 | // pretend we saw a NestedNameSpecifier referring to the current scope, and | ||||||
568 | // lookup is retried. | ||||||
569 | // FIXME: This hurts our diagnostic quality, since we get errors like "no | ||||||
570 | // type named 'Foo' in 'current_namespace'" when the user didn't write any | ||||||
571 | // name specifiers. | ||||||
572 | NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); | ||||||
573 | Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; | ||||||
574 | } else if (const CXXRecordDecl *RD = | ||||||
575 | findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { | ||||||
576 | // Build a DependentNameType that will perform lookup into RD at | ||||||
577 | // instantiation time. | ||||||
578 | NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), | ||||||
579 | RD->getTypeForDecl()); | ||||||
580 | |||||||
581 | // Diagnose that this identifier was undeclared, and retry the lookup during | ||||||
582 | // template instantiation. | ||||||
583 | Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II | ||||||
584 | << RD; | ||||||
585 | } else { | ||||||
586 | // This is not a situation that we should recover from. | ||||||
587 | return ParsedType(); | ||||||
588 | } | ||||||
589 | |||||||
590 | QualType T = Context.getDependentNameType(ETK_None, NNS, &II); | ||||||
591 | |||||||
592 | // Build type location information. We synthesized the qualifier, so we have | ||||||
593 | // to build a fake NestedNameSpecifierLoc. | ||||||
594 | NestedNameSpecifierLocBuilder NNSLocBuilder; | ||||||
595 | NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); | ||||||
596 | NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); | ||||||
597 | |||||||
598 | TypeLocBuilder Builder; | ||||||
599 | DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); | ||||||
600 | DepTL.setNameLoc(NameLoc); | ||||||
601 | DepTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
602 | DepTL.setQualifierLoc(QualifierLoc); | ||||||
603 | return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
604 | } | ||||||
605 | |||||||
606 | /// isTagName() - This method is called *for error recovery purposes only* | ||||||
607 | /// to determine if the specified name is a valid tag name ("struct foo"). If | ||||||
608 | /// so, this returns the TST for the tag corresponding to it (TST_enum, | ||||||
609 | /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose | ||||||
610 | /// cases in C where the user forgot to specify the tag. | ||||||
611 | DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { | ||||||
612 | // Do a tag name lookup in this scope. | ||||||
613 | LookupResult R(*this, &II, SourceLocation(), LookupTagName); | ||||||
614 | LookupName(R, S, false); | ||||||
615 | R.suppressDiagnostics(); | ||||||
616 | if (R.getResultKind() == LookupResult::Found) | ||||||
617 | if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { | ||||||
618 | switch (TD->getTagKind()) { | ||||||
619 | case TTK_Struct: return DeclSpec::TST_struct; | ||||||
620 | case TTK_Interface: return DeclSpec::TST_interface; | ||||||
621 | case TTK_Union: return DeclSpec::TST_union; | ||||||
622 | case TTK_Class: return DeclSpec::TST_class; | ||||||
623 | case TTK_Enum: return DeclSpec::TST_enum; | ||||||
624 | } | ||||||
625 | } | ||||||
626 | |||||||
627 | return DeclSpec::TST_unspecified; | ||||||
628 | } | ||||||
629 | |||||||
630 | /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, | ||||||
631 | /// if a CXXScopeSpec's type is equal to the type of one of the base classes | ||||||
632 | /// then downgrade the missing typename error to a warning. | ||||||
633 | /// This is needed for MSVC compatibility; Example: | ||||||
634 | /// @code | ||||||
635 | /// template<class T> class A { | ||||||
636 | /// public: | ||||||
637 | /// typedef int TYPE; | ||||||
638 | /// }; | ||||||
639 | /// template<class T> class B : public A<T> { | ||||||
640 | /// public: | ||||||
641 | /// A<T>::TYPE a; // no typename required because A<T> is a base class. | ||||||
642 | /// }; | ||||||
643 | /// @endcode | ||||||
644 | bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { | ||||||
645 | if (CurContext->isRecord()) { | ||||||
646 | if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) | ||||||
647 | return true; | ||||||
648 | |||||||
649 | const Type *Ty = SS->getScopeRep()->getAsType(); | ||||||
650 | |||||||
651 | CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); | ||||||
652 | for (const auto &Base : RD->bases()) | ||||||
653 | if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) | ||||||
654 | return true; | ||||||
655 | return S->isFunctionPrototypeScope(); | ||||||
656 | } | ||||||
657 | return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); | ||||||
658 | } | ||||||
659 | |||||||
660 | void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, | ||||||
661 | SourceLocation IILoc, | ||||||
662 | Scope *S, | ||||||
663 | CXXScopeSpec *SS, | ||||||
664 | ParsedType &SuggestedType, | ||||||
665 | bool IsTemplateName) { | ||||||
666 | // Don't report typename errors for editor placeholders. | ||||||
667 | if (II->isEditorPlaceholder()) | ||||||
668 | return; | ||||||
669 | // We don't have anything to suggest (yet). | ||||||
670 | SuggestedType = nullptr; | ||||||
671 | |||||||
672 | // There may have been a typo in the name of the type. Look up typo | ||||||
673 | // results, in case we have something that we can suggest. | ||||||
674 | TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, | ||||||
675 | /*AllowTemplates=*/IsTemplateName, | ||||||
676 | /*AllowNonTemplates=*/!IsTemplateName); | ||||||
677 | if (TypoCorrection Corrected = | ||||||
678 | CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, | ||||||
679 | CCC, CTK_ErrorRecovery)) { | ||||||
680 | // FIXME: Support error recovery for the template-name case. | ||||||
681 | bool CanRecover = !IsTemplateName; | ||||||
682 | if (Corrected.isKeyword()) { | ||||||
683 | // We corrected to a keyword. | ||||||
684 | diagnoseTypo(Corrected, | ||||||
685 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||||
686 | : diag::err_unknown_typename_suggest) | ||||||
687 | << II); | ||||||
688 | II = Corrected.getCorrectionAsIdentifierInfo(); | ||||||
689 | } else { | ||||||
690 | // We found a similarly-named type or interface; suggest that. | ||||||
691 | if (!SS || !SS->isSet()) { | ||||||
692 | diagnoseTypo(Corrected, | ||||||
693 | PDiag(IsTemplateName ? diag::err_no_template_suggest | ||||||
694 | : diag::err_unknown_typename_suggest) | ||||||
695 | << II, CanRecover); | ||||||
696 | } else if (DeclContext *DC = computeDeclContext(*SS, false)) { | ||||||
697 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||
698 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||||
699 | II->getName().equals(CorrectedStr); | ||||||
700 | diagnoseTypo(Corrected, | ||||||
701 | PDiag(IsTemplateName | ||||||
702 | ? diag::err_no_member_template_suggest | ||||||
703 | : diag::err_unknown_nested_typename_suggest) | ||||||
704 | << II << DC << DroppedSpecifier << SS->getRange(), | ||||||
705 | CanRecover); | ||||||
706 | } else { | ||||||
707 | llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 707); | ||||||
708 | } | ||||||
709 | |||||||
710 | if (!CanRecover) | ||||||
711 | return; | ||||||
712 | |||||||
713 | CXXScopeSpec tmpSS; | ||||||
714 | if (Corrected.getCorrectionSpecifier()) | ||||||
715 | tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), | ||||||
716 | SourceRange(IILoc)); | ||||||
717 | // FIXME: Support class template argument deduction here. | ||||||
718 | SuggestedType = | ||||||
719 | getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, | ||||||
720 | tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, | ||||||
721 | /*IsCtorOrDtorName=*/false, | ||||||
722 | /*WantNontrivialTypeSourceInfo=*/true); | ||||||
723 | } | ||||||
724 | return; | ||||||
725 | } | ||||||
726 | |||||||
727 | if (getLangOpts().CPlusPlus && !IsTemplateName) { | ||||||
728 | // See if II is a class template that the user forgot to pass arguments to. | ||||||
729 | UnqualifiedId Name; | ||||||
730 | Name.setIdentifier(II, IILoc); | ||||||
731 | CXXScopeSpec EmptySS; | ||||||
732 | TemplateTy TemplateResult; | ||||||
733 | bool MemberOfUnknownSpecialization; | ||||||
734 | if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, | ||||||
735 | Name, nullptr, true, TemplateResult, | ||||||
736 | MemberOfUnknownSpecialization) == TNK_Type_template) { | ||||||
737 | diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); | ||||||
738 | return; | ||||||
739 | } | ||||||
740 | } | ||||||
741 | |||||||
742 | // FIXME: Should we move the logic that tries to recover from a missing tag | ||||||
743 | // (struct, union, enum) from Parser::ParseImplicitInt here, instead? | ||||||
744 | |||||||
745 | if (!SS || (!SS->isSet() && !SS->isInvalid())) | ||||||
746 | Diag(IILoc, IsTemplateName ? diag::err_no_template | ||||||
747 | : diag::err_unknown_typename) | ||||||
748 | << II; | ||||||
749 | else if (DeclContext *DC = computeDeclContext(*SS, false)) | ||||||
750 | Diag(IILoc, IsTemplateName ? diag::err_no_member_template | ||||||
751 | : diag::err_typename_nested_not_found) | ||||||
752 | << II << DC << SS->getRange(); | ||||||
753 | else if (SS->isValid() && SS->getScopeRep()->containsErrors()) { | ||||||
754 | SuggestedType = | ||||||
755 | ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get(); | ||||||
756 | } else if (isDependentScopeSpecifier(*SS)) { | ||||||
757 | unsigned DiagID = diag::err_typename_missing; | ||||||
758 | if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) | ||||||
759 | DiagID = diag::ext_typename_missing; | ||||||
760 | |||||||
761 | Diag(SS->getRange().getBegin(), DiagID) | ||||||
762 | << SS->getScopeRep() << II->getName() | ||||||
763 | << SourceRange(SS->getRange().getBegin(), IILoc) | ||||||
764 | << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); | ||||||
765 | SuggestedType = ActOnTypenameType(S, SourceLocation(), | ||||||
766 | *SS, *II, IILoc).get(); | ||||||
767 | } else { | ||||||
768 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 769, __PRETTY_FUNCTION__)) | ||||||
769 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 769, __PRETTY_FUNCTION__)); | ||||||
770 | } | ||||||
771 | } | ||||||
772 | |||||||
773 | /// Determine whether the given result set contains either a type name | ||||||
774 | /// or | ||||||
775 | static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { | ||||||
776 | bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && | ||||||
777 | NextToken.is(tok::less); | ||||||
778 | |||||||
779 | for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { | ||||||
780 | if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) | ||||||
781 | return true; | ||||||
782 | |||||||
783 | if (CheckTemplate && isa<TemplateDecl>(*I)) | ||||||
784 | return true; | ||||||
785 | } | ||||||
786 | |||||||
787 | return false; | ||||||
788 | } | ||||||
789 | |||||||
790 | static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, | ||||||
791 | Scope *S, CXXScopeSpec &SS, | ||||||
792 | IdentifierInfo *&Name, | ||||||
793 | SourceLocation NameLoc) { | ||||||
794 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); | ||||||
795 | SemaRef.LookupParsedName(R, S, &SS); | ||||||
796 | if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { | ||||||
797 | StringRef FixItTagName; | ||||||
798 | switch (Tag->getTagKind()) { | ||||||
799 | case TTK_Class: | ||||||
800 | FixItTagName = "class "; | ||||||
801 | break; | ||||||
802 | |||||||
803 | case TTK_Enum: | ||||||
804 | FixItTagName = "enum "; | ||||||
805 | break; | ||||||
806 | |||||||
807 | case TTK_Struct: | ||||||
808 | FixItTagName = "struct "; | ||||||
809 | break; | ||||||
810 | |||||||
811 | case TTK_Interface: | ||||||
812 | FixItTagName = "__interface "; | ||||||
813 | break; | ||||||
814 | |||||||
815 | case TTK_Union: | ||||||
816 | FixItTagName = "union "; | ||||||
817 | break; | ||||||
818 | } | ||||||
819 | |||||||
820 | StringRef TagName = FixItTagName.drop_back(); | ||||||
821 | SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) | ||||||
822 | << Name << TagName << SemaRef.getLangOpts().CPlusPlus | ||||||
823 | << FixItHint::CreateInsertion(NameLoc, FixItTagName); | ||||||
824 | |||||||
825 | for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); | ||||||
826 | I != IEnd; ++I) | ||||||
827 | SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) | ||||||
828 | << Name << TagName; | ||||||
829 | |||||||
830 | // Replace lookup results with just the tag decl. | ||||||
831 | Result.clear(Sema::LookupTagName); | ||||||
832 | SemaRef.LookupParsedName(Result, S, &SS); | ||||||
833 | return true; | ||||||
834 | } | ||||||
835 | |||||||
836 | return false; | ||||||
837 | } | ||||||
838 | |||||||
839 | /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. | ||||||
840 | static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, | ||||||
841 | QualType T, SourceLocation NameLoc) { | ||||||
842 | ASTContext &Context = S.Context; | ||||||
843 | |||||||
844 | TypeLocBuilder Builder; | ||||||
845 | Builder.pushTypeSpec(T).setNameLoc(NameLoc); | ||||||
846 | |||||||
847 | T = S.getElaboratedType(ETK_None, SS, T); | ||||||
848 | ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); | ||||||
849 | ElabTL.setElaboratedKeywordLoc(SourceLocation()); | ||||||
850 | ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); | ||||||
851 | return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); | ||||||
852 | } | ||||||
853 | |||||||
854 | Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, | ||||||
855 | IdentifierInfo *&Name, | ||||||
856 | SourceLocation NameLoc, | ||||||
857 | const Token &NextToken, | ||||||
858 | CorrectionCandidateCallback *CCC) { | ||||||
859 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||||
860 | ObjCMethodDecl *CurMethod = getCurMethodDecl(); | ||||||
861 | |||||||
862 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 863, __PRETTY_FUNCTION__)) | ||||||
863 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 863, __PRETTY_FUNCTION__)); | ||||||
864 | if (getLangOpts().CPlusPlus && SS.isSet() && | ||||||
865 | isCurrentClassName(*Name, S, &SS)) { | ||||||
866 | // Per [class.qual]p2, this names the constructors of SS, not the | ||||||
867 | // injected-class-name. We don't have a classification for that. | ||||||
868 | // There's not much point caching this result, since the parser | ||||||
869 | // will reject it later. | ||||||
870 | return NameClassification::Unknown(); | ||||||
871 | } | ||||||
872 | |||||||
873 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||||
874 | LookupParsedName(Result, S, &SS, !CurMethod); | ||||||
875 | |||||||
876 | if (SS.isInvalid()) | ||||||
877 | return NameClassification::Error(); | ||||||
878 | |||||||
879 | // For unqualified lookup in a class template in MSVC mode, look into | ||||||
880 | // dependent base classes where the primary class template is known. | ||||||
881 | if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { | ||||||
882 | if (ParsedType TypeInBase = | ||||||
883 | recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) | ||||||
884 | return TypeInBase; | ||||||
885 | } | ||||||
886 | |||||||
887 | // Perform lookup for Objective-C instance variables (including automatically | ||||||
888 | // synthesized instance variables), if we're in an Objective-C method. | ||||||
889 | // FIXME: This lookup really, really needs to be folded in to the normal | ||||||
890 | // unqualified lookup mechanism. | ||||||
891 | if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { | ||||||
892 | DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); | ||||||
893 | if (Ivar.isInvalid()) | ||||||
894 | return NameClassification::Error(); | ||||||
895 | if (Ivar.isUsable()) | ||||||
896 | return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); | ||||||
897 | |||||||
898 | // We defer builtin creation until after ivar lookup inside ObjC methods. | ||||||
899 | if (Result.empty()) | ||||||
900 | LookupBuiltin(Result); | ||||||
901 | } | ||||||
902 | |||||||
903 | bool SecondTry = false; | ||||||
904 | bool IsFilteredTemplateName = false; | ||||||
905 | |||||||
906 | Corrected: | ||||||
907 | switch (Result.getResultKind()) { | ||||||
908 | case LookupResult::NotFound: | ||||||
909 | // If an unqualified-id is followed by a '(', then we have a function | ||||||
910 | // call. | ||||||
911 | if (SS.isEmpty() && NextToken.is(tok::l_paren)) { | ||||||
912 | // In C++, this is an ADL-only call. | ||||||
913 | // FIXME: Reference? | ||||||
914 | if (getLangOpts().CPlusPlus) | ||||||
915 | return NameClassification::UndeclaredNonType(); | ||||||
916 | |||||||
917 | // C90 6.3.2.2: | ||||||
918 | // If the expression that precedes the parenthesized argument list in a | ||||||
919 | // function call consists solely of an identifier, and if no | ||||||
920 | // declaration is visible for this identifier, the identifier is | ||||||
921 | // implicitly declared exactly as if, in the innermost block containing | ||||||
922 | // the function call, the declaration | ||||||
923 | // | ||||||
924 | // extern int identifier (); | ||||||
925 | // | ||||||
926 | // appeared. | ||||||
927 | // | ||||||
928 | // We also allow this in C99 as an extension. | ||||||
929 | if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) | ||||||
930 | return NameClassification::NonType(D); | ||||||
931 | } | ||||||
932 | |||||||
933 | if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) { | ||||||
934 | // In C++20 onwards, this could be an ADL-only call to a function | ||||||
935 | // template, and we're required to assume that this is a template name. | ||||||
936 | // | ||||||
937 | // FIXME: Find a way to still do typo correction in this case. | ||||||
938 | TemplateName Template = | ||||||
939 | Context.getAssumedTemplateName(NameInfo.getName()); | ||||||
940 | return NameClassification::UndeclaredTemplate(Template); | ||||||
941 | } | ||||||
942 | |||||||
943 | // In C, we first see whether there is a tag type by the same name, in | ||||||
944 | // which case it's likely that the user just forgot to write "enum", | ||||||
945 | // "struct", or "union". | ||||||
946 | if (!getLangOpts().CPlusPlus && !SecondTry && | ||||||
947 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||||
948 | break; | ||||||
949 | } | ||||||
950 | |||||||
951 | // Perform typo correction to determine if there is another name that is | ||||||
952 | // close to this name. | ||||||
953 | if (!SecondTry && CCC) { | ||||||
954 | SecondTry = true; | ||||||
955 | if (TypoCorrection Corrected = | ||||||
956 | CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, | ||||||
957 | &SS, *CCC, CTK_ErrorRecovery)) { | ||||||
958 | unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; | ||||||
959 | unsigned QualifiedDiag = diag::err_no_member_suggest; | ||||||
960 | |||||||
961 | NamedDecl *FirstDecl = Corrected.getFoundDecl(); | ||||||
962 | NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); | ||||||
963 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
964 | UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { | ||||||
965 | UnqualifiedDiag = diag::err_no_template_suggest; | ||||||
966 | QualifiedDiag = diag::err_no_member_template_suggest; | ||||||
967 | } else if (UnderlyingFirstDecl && | ||||||
968 | (isa<TypeDecl>(UnderlyingFirstDecl) || | ||||||
969 | isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || | ||||||
970 | isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { | ||||||
971 | UnqualifiedDiag = diag::err_unknown_typename_suggest; | ||||||
972 | QualifiedDiag = diag::err_unknown_nested_typename_suggest; | ||||||
973 | } | ||||||
974 | |||||||
975 | if (SS.isEmpty()) { | ||||||
976 | diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); | ||||||
977 | } else {// FIXME: is this even reachable? Test it. | ||||||
978 | std::string CorrectedStr(Corrected.getAsString(getLangOpts())); | ||||||
979 | bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && | ||||||
980 | Name->getName().equals(CorrectedStr); | ||||||
981 | diagnoseTypo(Corrected, PDiag(QualifiedDiag) | ||||||
982 | << Name << computeDeclContext(SS, false) | ||||||
983 | << DroppedSpecifier << SS.getRange()); | ||||||
984 | } | ||||||
985 | |||||||
986 | // Update the name, so that the caller has the new name. | ||||||
987 | Name = Corrected.getCorrectionAsIdentifierInfo(); | ||||||
988 | |||||||
989 | // Typo correction corrected to a keyword. | ||||||
990 | if (Corrected.isKeyword()) | ||||||
991 | return Name; | ||||||
992 | |||||||
993 | // Also update the LookupResult... | ||||||
994 | // FIXME: This should probably go away at some point | ||||||
995 | Result.clear(); | ||||||
996 | Result.setLookupName(Corrected.getCorrection()); | ||||||
997 | if (FirstDecl) | ||||||
998 | Result.addDecl(FirstDecl); | ||||||
999 | |||||||
1000 | // If we found an Objective-C instance variable, let | ||||||
1001 | // LookupInObjCMethod build the appropriate expression to | ||||||
1002 | // reference the ivar. | ||||||
1003 | // FIXME: This is a gross hack. | ||||||
1004 | if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { | ||||||
1005 | DeclResult R = | ||||||
1006 | LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); | ||||||
1007 | if (R.isInvalid()) | ||||||
1008 | return NameClassification::Error(); | ||||||
1009 | if (R.isUsable()) | ||||||
1010 | return NameClassification::NonType(Ivar); | ||||||
1011 | } | ||||||
1012 | |||||||
1013 | goto Corrected; | ||||||
1014 | } | ||||||
1015 | } | ||||||
1016 | |||||||
1017 | // We failed to correct; just fall through and let the parser deal with it. | ||||||
1018 | Result.suppressDiagnostics(); | ||||||
1019 | return NameClassification::Unknown(); | ||||||
1020 | |||||||
1021 | case LookupResult::NotFoundInCurrentInstantiation: { | ||||||
1022 | // We performed name lookup into the current instantiation, and there were | ||||||
1023 | // dependent bases, so we treat this result the same way as any other | ||||||
1024 | // dependent nested-name-specifier. | ||||||
1025 | |||||||
1026 | // C++ [temp.res]p2: | ||||||
1027 | // A name used in a template declaration or definition and that is | ||||||
1028 | // dependent on a template-parameter is assumed not to name a type | ||||||
1029 | // unless the applicable name lookup finds a type name or the name is | ||||||
1030 | // qualified by the keyword typename. | ||||||
1031 | // | ||||||
1032 | // FIXME: If the next token is '<', we might want to ask the parser to | ||||||
1033 | // perform some heroics to see if we actually have a | ||||||
1034 | // template-argument-list, which would indicate a missing 'template' | ||||||
1035 | // keyword here. | ||||||
1036 | return NameClassification::DependentNonType(); | ||||||
1037 | } | ||||||
1038 | |||||||
1039 | case LookupResult::Found: | ||||||
1040 | case LookupResult::FoundOverloaded: | ||||||
1041 | case LookupResult::FoundUnresolvedValue: | ||||||
1042 | break; | ||||||
1043 | |||||||
1044 | case LookupResult::Ambiguous: | ||||||
1045 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
1046 | hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, | ||||||
1047 | /*AllowDependent=*/false)) { | ||||||
1048 | // C++ [temp.local]p3: | ||||||
1049 | // A lookup that finds an injected-class-name (10.2) can result in an | ||||||
1050 | // ambiguity in certain cases (for example, if it is found in more than | ||||||
1051 | // one base class). If all of the injected-class-names that are found | ||||||
1052 | // refer to specializations of the same class template, and if the name | ||||||
1053 | // is followed by a template-argument-list, the reference refers to the | ||||||
1054 | // class template itself and not a specialization thereof, and is not | ||||||
1055 | // ambiguous. | ||||||
1056 | // | ||||||
1057 | // This filtering can make an ambiguous result into an unambiguous one, | ||||||
1058 | // so try again after filtering out template names. | ||||||
1059 | FilterAcceptableTemplateNames(Result); | ||||||
1060 | if (!Result.isAmbiguous()) { | ||||||
1061 | IsFilteredTemplateName = true; | ||||||
1062 | break; | ||||||
1063 | } | ||||||
1064 | } | ||||||
1065 | |||||||
1066 | // Diagnose the ambiguity and return an error. | ||||||
1067 | return NameClassification::Error(); | ||||||
1068 | } | ||||||
1069 | |||||||
1070 | if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && | ||||||
1071 | (IsFilteredTemplateName || | ||||||
1072 | hasAnyAcceptableTemplateNames( | ||||||
1073 | Result, /*AllowFunctionTemplates=*/true, | ||||||
1074 | /*AllowDependent=*/false, | ||||||
1075 | /*AllowNonTemplateFunctions*/ SS.isEmpty() && | ||||||
1076 | getLangOpts().CPlusPlus20))) { | ||||||
1077 | // C++ [temp.names]p3: | ||||||
1078 | // After name lookup (3.4) finds that a name is a template-name or that | ||||||
1079 | // an operator-function-id or a literal- operator-id refers to a set of | ||||||
1080 | // overloaded functions any member of which is a function template if | ||||||
1081 | // this is followed by a <, the < is always taken as the delimiter of a | ||||||
1082 | // template-argument-list and never as the less-than operator. | ||||||
1083 | // C++2a [temp.names]p2: | ||||||
1084 | // A name is also considered to refer to a template if it is an | ||||||
1085 | // unqualified-id followed by a < and name lookup finds either one | ||||||
1086 | // or more functions or finds nothing. | ||||||
1087 | if (!IsFilteredTemplateName) | ||||||
1088 | FilterAcceptableTemplateNames(Result); | ||||||
1089 | |||||||
1090 | bool IsFunctionTemplate; | ||||||
1091 | bool IsVarTemplate; | ||||||
1092 | TemplateName Template; | ||||||
1093 | if (Result.end() - Result.begin() > 1) { | ||||||
1094 | IsFunctionTemplate = true; | ||||||
1095 | Template = Context.getOverloadedTemplateName(Result.begin(), | ||||||
1096 | Result.end()); | ||||||
1097 | } else if (!Result.empty()) { | ||||||
1098 | auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( | ||||||
1099 | *Result.begin(), /*AllowFunctionTemplates=*/true, | ||||||
1100 | /*AllowDependent=*/false)); | ||||||
1101 | IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); | ||||||
1102 | IsVarTemplate = isa<VarTemplateDecl>(TD); | ||||||
1103 | |||||||
1104 | if (SS.isNotEmpty()) | ||||||
1105 | Template = | ||||||
1106 | Context.getQualifiedTemplateName(SS.getScopeRep(), | ||||||
1107 | /*TemplateKeyword=*/false, TD); | ||||||
1108 | else | ||||||
1109 | Template = TemplateName(TD); | ||||||
1110 | } else { | ||||||
1111 | // All results were non-template functions. This is a function template | ||||||
1112 | // name. | ||||||
1113 | IsFunctionTemplate = true; | ||||||
1114 | Template = Context.getAssumedTemplateName(NameInfo.getName()); | ||||||
1115 | } | ||||||
1116 | |||||||
1117 | if (IsFunctionTemplate) { | ||||||
1118 | // Function templates always go through overload resolution, at which | ||||||
1119 | // point we'll perform the various checks (e.g., accessibility) we need | ||||||
1120 | // to based on which function we selected. | ||||||
1121 | Result.suppressDiagnostics(); | ||||||
1122 | |||||||
1123 | return NameClassification::FunctionTemplate(Template); | ||||||
1124 | } | ||||||
1125 | |||||||
1126 | return IsVarTemplate ? NameClassification::VarTemplate(Template) | ||||||
1127 | : NameClassification::TypeTemplate(Template); | ||||||
1128 | } | ||||||
1129 | |||||||
1130 | NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); | ||||||
1131 | if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { | ||||||
1132 | DiagnoseUseOfDecl(Type, NameLoc); | ||||||
1133 | MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); | ||||||
1134 | QualType T = Context.getTypeDeclType(Type); | ||||||
1135 | if (SS.isNotEmpty()) | ||||||
1136 | return buildNestedType(*this, SS, T, NameLoc); | ||||||
1137 | return ParsedType::make(T); | ||||||
1138 | } | ||||||
1139 | |||||||
1140 | ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); | ||||||
1141 | if (!Class) { | ||||||
1142 | // FIXME: It's unfortunate that we don't have a Type node for handling this. | ||||||
1143 | if (ObjCCompatibleAliasDecl *Alias = | ||||||
1144 | dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) | ||||||
1145 | Class = Alias->getClassInterface(); | ||||||
1146 | } | ||||||
1147 | |||||||
1148 | if (Class) { | ||||||
1149 | DiagnoseUseOfDecl(Class, NameLoc); | ||||||
1150 | |||||||
1151 | if (NextToken.is(tok::period)) { | ||||||
1152 | // Interface. <something> is parsed as a property reference expression. | ||||||
1153 | // Just return "unknown" as a fall-through for now. | ||||||
1154 | Result.suppressDiagnostics(); | ||||||
1155 | return NameClassification::Unknown(); | ||||||
1156 | } | ||||||
1157 | |||||||
1158 | QualType T = Context.getObjCInterfaceType(Class); | ||||||
1159 | return ParsedType::make(T); | ||||||
1160 | } | ||||||
1161 | |||||||
1162 | if (isa<ConceptDecl>(FirstDecl)) | ||||||
1163 | return NameClassification::Concept( | ||||||
1164 | TemplateName(cast<TemplateDecl>(FirstDecl))); | ||||||
1165 | |||||||
1166 | // We can have a type template here if we're classifying a template argument. | ||||||
1167 | if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && | ||||||
1168 | !isa<VarTemplateDecl>(FirstDecl)) | ||||||
1169 | return NameClassification::TypeTemplate( | ||||||
1170 | TemplateName(cast<TemplateDecl>(FirstDecl))); | ||||||
1171 | |||||||
1172 | // Check for a tag type hidden by a non-type decl in a few cases where it | ||||||
1173 | // seems likely a type is wanted instead of the non-type that was found. | ||||||
1174 | bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); | ||||||
1175 | if ((NextToken.is(tok::identifier) || | ||||||
1176 | (NextIsOp && | ||||||
1177 | FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && | ||||||
1178 | isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { | ||||||
1179 | TypeDecl *Type = Result.getAsSingle<TypeDecl>(); | ||||||
1180 | DiagnoseUseOfDecl(Type, NameLoc); | ||||||
1181 | QualType T = Context.getTypeDeclType(Type); | ||||||
1182 | if (SS.isNotEmpty()) | ||||||
1183 | return buildNestedType(*this, SS, T, NameLoc); | ||||||
1184 | return ParsedType::make(T); | ||||||
1185 | } | ||||||
1186 | |||||||
1187 | // If we already know which single declaration is referenced, just annotate | ||||||
1188 | // that declaration directly. Defer resolving even non-overloaded class | ||||||
1189 | // member accesses, as we need to defer certain access checks until we know | ||||||
1190 | // the context. | ||||||
1191 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||||
1192 | if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember()) | ||||||
1193 | return NameClassification::NonType(Result.getRepresentativeDecl()); | ||||||
1194 | |||||||
1195 | // Otherwise, this is an overload set that we will need to resolve later. | ||||||
1196 | Result.suppressDiagnostics(); | ||||||
1197 | return NameClassification::OverloadSet(UnresolvedLookupExpr::Create( | ||||||
1198 | Context, Result.getNamingClass(), SS.getWithLocInContext(Context), | ||||||
1199 | Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(), | ||||||
1200 | Result.begin(), Result.end())); | ||||||
1201 | } | ||||||
1202 | |||||||
1203 | ExprResult | ||||||
1204 | Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, | ||||||
1205 | SourceLocation NameLoc) { | ||||||
1206 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1206, __PRETTY_FUNCTION__)); | ||||||
1207 | CXXScopeSpec SS; | ||||||
1208 | LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); | ||||||
1209 | return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); | ||||||
1210 | } | ||||||
1211 | |||||||
1212 | ExprResult | ||||||
1213 | Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, | ||||||
1214 | IdentifierInfo *Name, | ||||||
1215 | SourceLocation NameLoc, | ||||||
1216 | bool IsAddressOfOperand) { | ||||||
1217 | DeclarationNameInfo NameInfo(Name, NameLoc); | ||||||
1218 | return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), | ||||||
1219 | NameInfo, IsAddressOfOperand, | ||||||
1220 | /*TemplateArgs=*/nullptr); | ||||||
1221 | } | ||||||
1222 | |||||||
1223 | ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, | ||||||
1224 | NamedDecl *Found, | ||||||
1225 | SourceLocation NameLoc, | ||||||
1226 | const Token &NextToken) { | ||||||
1227 | if (getCurMethodDecl() && SS.isEmpty()) | ||||||
1228 | if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) | ||||||
1229 | return BuildIvarRefExpr(S, NameLoc, Ivar); | ||||||
1230 | |||||||
1231 | // Reconstruct the lookup result. | ||||||
1232 | LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); | ||||||
1233 | Result.addDecl(Found); | ||||||
1234 | Result.resolveKind(); | ||||||
1235 | |||||||
1236 | bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); | ||||||
1237 | return BuildDeclarationNameExpr(SS, Result, ADL); | ||||||
1238 | } | ||||||
1239 | |||||||
1240 | ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) { | ||||||
1241 | // For an implicit class member access, transform the result into a member | ||||||
1242 | // access expression if necessary. | ||||||
1243 | auto *ULE = cast<UnresolvedLookupExpr>(E); | ||||||
1244 | if ((*ULE->decls_begin())->isCXXClassMember()) { | ||||||
1245 | CXXScopeSpec SS; | ||||||
1246 | SS.Adopt(ULE->getQualifierLoc()); | ||||||
1247 | |||||||
1248 | // Reconstruct the lookup result. | ||||||
1249 | LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(), | ||||||
1250 | LookupOrdinaryName); | ||||||
1251 | Result.setNamingClass(ULE->getNamingClass()); | ||||||
1252 | for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I) | ||||||
1253 | Result.addDecl(*I, I.getAccess()); | ||||||
1254 | Result.resolveKind(); | ||||||
1255 | return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, | ||||||
1256 | nullptr, S); | ||||||
1257 | } | ||||||
1258 | |||||||
1259 | // Otherwise, this is already in the form we needed, and no further checks | ||||||
1260 | // are necessary. | ||||||
1261 | return ULE; | ||||||
1262 | } | ||||||
1263 | |||||||
1264 | Sema::TemplateNameKindForDiagnostics | ||||||
1265 | Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { | ||||||
1266 | auto *TD = Name.getAsTemplateDecl(); | ||||||
1267 | if (!TD) | ||||||
1268 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||||
1269 | if (isa<ClassTemplateDecl>(TD)) | ||||||
1270 | return TemplateNameKindForDiagnostics::ClassTemplate; | ||||||
1271 | if (isa<FunctionTemplateDecl>(TD)) | ||||||
1272 | return TemplateNameKindForDiagnostics::FunctionTemplate; | ||||||
1273 | if (isa<VarTemplateDecl>(TD)) | ||||||
1274 | return TemplateNameKindForDiagnostics::VarTemplate; | ||||||
1275 | if (isa<TypeAliasTemplateDecl>(TD)) | ||||||
1276 | return TemplateNameKindForDiagnostics::AliasTemplate; | ||||||
1277 | if (isa<TemplateTemplateParmDecl>(TD)) | ||||||
1278 | return TemplateNameKindForDiagnostics::TemplateTemplateParam; | ||||||
1279 | if (isa<ConceptDecl>(TD)) | ||||||
1280 | return TemplateNameKindForDiagnostics::Concept; | ||||||
1281 | return TemplateNameKindForDiagnostics::DependentTemplate; | ||||||
1282 | } | ||||||
1283 | |||||||
1284 | void Sema::PushDeclContext(Scope *S, DeclContext *DC) { | ||||||
1285 | assert(DC->getLexicalParent() == CurContext &&((DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1286, __PRETTY_FUNCTION__)) | ||||||
1286 | "The next DeclContext should be lexically contained in the current one.")((DC->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("DC->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1286, __PRETTY_FUNCTION__)); | ||||||
1287 | CurContext = DC; | ||||||
1288 | S->setEntity(DC); | ||||||
1289 | } | ||||||
1290 | |||||||
1291 | void Sema::PopDeclContext() { | ||||||
1292 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1292, __PRETTY_FUNCTION__)); | ||||||
1293 | |||||||
1294 | CurContext = CurContext->getLexicalParent(); | ||||||
1295 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1295, __PRETTY_FUNCTION__)); | ||||||
1296 | } | ||||||
1297 | |||||||
1298 | Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, | ||||||
1299 | Decl *D) { | ||||||
1300 | // Unlike PushDeclContext, the context to which we return is not necessarily | ||||||
1301 | // the containing DC of TD, because the new context will be some pre-existing | ||||||
1302 | // TagDecl definition instead of a fresh one. | ||||||
1303 | auto Result = static_cast<SkippedDefinitionContext>(CurContext); | ||||||
1304 | CurContext = cast<TagDecl>(D)->getDefinition(); | ||||||
1305 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1305, __PRETTY_FUNCTION__)); | ||||||
1306 | // Start lookups from the parent of the current context; we don't want to look | ||||||
1307 | // into the pre-existing complete definition. | ||||||
1308 | S->setEntity(CurContext->getLookupParent()); | ||||||
1309 | return Result; | ||||||
1310 | } | ||||||
1311 | |||||||
1312 | void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { | ||||||
1313 | CurContext = static_cast<decltype(CurContext)>(Context); | ||||||
1314 | } | ||||||
1315 | |||||||
1316 | /// EnterDeclaratorContext - Used when we must lookup names in the context | ||||||
1317 | /// of a declarator's nested name specifier. | ||||||
1318 | /// | ||||||
1319 | void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { | ||||||
1320 | // C++0x [basic.lookup.unqual]p13: | ||||||
1321 | // A name used in the definition of a static data member of class | ||||||
1322 | // X (after the qualified-id of the static member) is looked up as | ||||||
1323 | // if the name was used in a member function of X. | ||||||
1324 | // C++0x [basic.lookup.unqual]p14: | ||||||
1325 | // If a variable member of a namespace is defined outside of the | ||||||
1326 | // scope of its namespace then any name used in the definition of | ||||||
1327 | // the variable member (after the declarator-id) is looked up as | ||||||
1328 | // if the definition of the variable member occurred in its | ||||||
1329 | // namespace. | ||||||
1330 | // Both of these imply that we should push a scope whose context | ||||||
1331 | // is the semantic context of the declaration. We can't use | ||||||
1332 | // PushDeclContext here because that context is not necessarily | ||||||
1333 | // lexically contained in the current context. Fortunately, | ||||||
1334 | // the containing scope should have the appropriate information. | ||||||
1335 | |||||||
1336 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1336, __PRETTY_FUNCTION__)); | ||||||
1337 | |||||||
1338 | #ifndef NDEBUG | ||||||
1339 | Scope *Ancestor = S->getParent(); | ||||||
1340 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||||
1341 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1341, __PRETTY_FUNCTION__)); | ||||||
1342 | #endif | ||||||
1343 | |||||||
1344 | CurContext = DC; | ||||||
1345 | S->setEntity(DC); | ||||||
1346 | |||||||
1347 | if (S->getParent()->isTemplateParamScope()) { | ||||||
1348 | // Also set the corresponding entities for all immediately-enclosing | ||||||
1349 | // template parameter scopes. | ||||||
1350 | EnterTemplatedContext(S->getParent(), DC); | ||||||
1351 | } | ||||||
1352 | } | ||||||
1353 | |||||||
1354 | void Sema::ExitDeclaratorContext(Scope *S) { | ||||||
1355 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1355, __PRETTY_FUNCTION__)); | ||||||
1356 | |||||||
1357 | // Switch back to the lexical context. The safety of this is | ||||||
1358 | // enforced by an assert in EnterDeclaratorContext. | ||||||
1359 | Scope *Ancestor = S->getParent(); | ||||||
1360 | while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); | ||||||
1361 | CurContext = Ancestor->getEntity(); | ||||||
1362 | |||||||
1363 | // We don't need to do anything with the scope, which is going to | ||||||
1364 | // disappear. | ||||||
1365 | } | ||||||
1366 | |||||||
1367 | void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) { | ||||||
1368 | assert(S->isTemplateParamScope() &&((S->isTemplateParamScope() && "expected to be initializing a template parameter scope" ) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1369, __PRETTY_FUNCTION__)) | ||||||
1369 | "expected to be initializing a template parameter scope")((S->isTemplateParamScope() && "expected to be initializing a template parameter scope" ) ? static_cast<void> (0) : __assert_fail ("S->isTemplateParamScope() && \"expected to be initializing a template parameter scope\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1369, __PRETTY_FUNCTION__)); | ||||||
1370 | |||||||
1371 | // C++20 [temp.local]p7: | ||||||
1372 | // In the definition of a member of a class template that appears outside | ||||||
1373 | // of the class template definition, the name of a member of the class | ||||||
1374 | // template hides the name of a template-parameter of any enclosing class | ||||||
1375 | // templates (but not a template-parameter of the member if the member is a | ||||||
1376 | // class or function template). | ||||||
1377 | // C++20 [temp.local]p9: | ||||||
1378 | // In the definition of a class template or in the definition of a member | ||||||
1379 | // of such a template that appears outside of the template definition, for | ||||||
1380 | // each non-dependent base class (13.8.2.1), if the name of the base class | ||||||
1381 | // or the name of a member of the base class is the same as the name of a | ||||||
1382 | // template-parameter, the base class name or member name hides the | ||||||
1383 | // template-parameter name (6.4.10). | ||||||
1384 | // | ||||||
1385 | // This means that a template parameter scope should be searched immediately | ||||||
1386 | // after searching the DeclContext for which it is a template parameter | ||||||
1387 | // scope. For example, for | ||||||
1388 | // template<typename T> template<typename U> template<typename V> | ||||||
1389 | // void N::A<T>::B<U>::f(...) | ||||||
1390 | // we search V then B<U> (and base classes) then U then A<T> (and base | ||||||
1391 | // classes) then T then N then ::. | ||||||
1392 | unsigned ScopeDepth = getTemplateDepth(S); | ||||||
1393 | for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) { | ||||||
1394 | DeclContext *SearchDCAfterScope = DC; | ||||||
1395 | for (; DC; DC = DC->getLookupParent()) { | ||||||
1396 | if (const TemplateParameterList *TPL = | ||||||
1397 | cast<Decl>(DC)->getDescribedTemplateParams()) { | ||||||
1398 | unsigned DCDepth = TPL->getDepth() + 1; | ||||||
1399 | if (DCDepth > ScopeDepth) | ||||||
1400 | continue; | ||||||
1401 | if (ScopeDepth == DCDepth) | ||||||
1402 | SearchDCAfterScope = DC = DC->getLookupParent(); | ||||||
1403 | break; | ||||||
1404 | } | ||||||
1405 | } | ||||||
1406 | S->setLookupEntity(SearchDCAfterScope); | ||||||
1407 | } | ||||||
1408 | } | ||||||
1409 | |||||||
1410 | void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { | ||||||
1411 | // We assume that the caller has already called | ||||||
1412 | // ActOnReenterTemplateScope so getTemplatedDecl() works. | ||||||
1413 | FunctionDecl *FD = D->getAsFunction(); | ||||||
1414 | if (!FD) | ||||||
1415 | return; | ||||||
1416 | |||||||
1417 | // Same implementation as PushDeclContext, but enters the context | ||||||
1418 | // from the lexical parent, rather than the top-level class. | ||||||
1419 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1420, __PRETTY_FUNCTION__)) | ||||||
1420 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1420, __PRETTY_FUNCTION__)); | ||||||
1421 | CurContext = FD; | ||||||
1422 | S->setEntity(CurContext); | ||||||
1423 | |||||||
1424 | for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { | ||||||
1425 | ParmVarDecl *Param = FD->getParamDecl(P); | ||||||
1426 | // If the parameter has an identifier, then add it to the scope | ||||||
1427 | if (Param->getIdentifier()) { | ||||||
1428 | S->AddDecl(Param); | ||||||
1429 | IdResolver.AddDecl(Param); | ||||||
1430 | } | ||||||
1431 | } | ||||||
1432 | } | ||||||
1433 | |||||||
1434 | void Sema::ActOnExitFunctionContext() { | ||||||
1435 | // Same implementation as PopDeclContext, but returns to the lexical parent, | ||||||
1436 | // rather than the top-level class. | ||||||
1437 | assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1437, __PRETTY_FUNCTION__)); | ||||||
1438 | CurContext = CurContext->getLexicalParent(); | ||||||
1439 | assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast <void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1439, __PRETTY_FUNCTION__)); | ||||||
1440 | } | ||||||
1441 | |||||||
1442 | /// Determine whether we allow overloading of the function | ||||||
1443 | /// PrevDecl with another declaration. | ||||||
1444 | /// | ||||||
1445 | /// This routine determines whether overloading is possible, not | ||||||
1446 | /// whether some new function is actually an overload. It will return | ||||||
1447 | /// true in C++ (where we can always provide overloads) or, as an | ||||||
1448 | /// extension, in C when the previous function is already an | ||||||
1449 | /// overloaded function declaration or has the "overloadable" | ||||||
1450 | /// attribute. | ||||||
1451 | static bool AllowOverloadingOfFunction(LookupResult &Previous, | ||||||
1452 | ASTContext &Context, | ||||||
1453 | const FunctionDecl *New) { | ||||||
1454 | if (Context.getLangOpts().CPlusPlus) | ||||||
1455 | return true; | ||||||
1456 | |||||||
1457 | if (Previous.getResultKind() == LookupResult::FoundOverloaded) | ||||||
1458 | return true; | ||||||
1459 | |||||||
1460 | return Previous.getResultKind() == LookupResult::Found && | ||||||
1461 | (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || | ||||||
1462 | New->hasAttr<OverloadableAttr>()); | ||||||
1463 | } | ||||||
1464 | |||||||
1465 | /// Add this decl to the scope shadowed decl chains. | ||||||
1466 | void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { | ||||||
1467 | // Move up the scope chain until we find the nearest enclosing | ||||||
1468 | // non-transparent context. The declaration will be introduced into this | ||||||
1469 | // scope. | ||||||
1470 | while (S->getEntity() && S->getEntity()->isTransparentContext()) | ||||||
1471 | S = S->getParent(); | ||||||
1472 | |||||||
1473 | // Add scoped declarations into their context, so that they can be | ||||||
1474 | // found later. Declarations without a context won't be inserted | ||||||
1475 | // into any context. | ||||||
1476 | if (AddToContext) | ||||||
1477 | CurContext->addDecl(D); | ||||||
1478 | |||||||
1479 | // Out-of-line definitions shouldn't be pushed into scope in C++, unless they | ||||||
1480 | // are function-local declarations. | ||||||
1481 | if (getLangOpts().CPlusPlus && D->isOutOfLine() && | ||||||
1482 | !D->getDeclContext()->getRedeclContext()->Equals( | ||||||
1483 | D->getLexicalDeclContext()->getRedeclContext()) && | ||||||
1484 | !D->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||
1485 | return; | ||||||
1486 | |||||||
1487 | // Template instantiations should also not be pushed into scope. | ||||||
1488 | if (isa<FunctionDecl>(D) && | ||||||
1489 | cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) | ||||||
1490 | return; | ||||||
1491 | |||||||
1492 | // If this replaces anything in the current scope, | ||||||
1493 | IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), | ||||||
1494 | IEnd = IdResolver.end(); | ||||||
1495 | for (; I != IEnd; ++I) { | ||||||
1496 | if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { | ||||||
1497 | S->RemoveDecl(*I); | ||||||
1498 | IdResolver.RemoveDecl(*I); | ||||||
1499 | |||||||
1500 | // Should only need to replace one decl. | ||||||
1501 | break; | ||||||
1502 | } | ||||||
1503 | } | ||||||
1504 | |||||||
1505 | S->AddDecl(D); | ||||||
1506 | |||||||
1507 | if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { | ||||||
1508 | // Implicitly-generated labels may end up getting generated in an order that | ||||||
1509 | // isn't strictly lexical, which breaks name lookup. Be careful to insert | ||||||
1510 | // the label at the appropriate place in the identifier chain. | ||||||
1511 | for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { | ||||||
1512 | DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); | ||||||
1513 | if (IDC == CurContext) { | ||||||
1514 | if (!S->isDeclScope(*I)) | ||||||
1515 | continue; | ||||||
1516 | } else if (IDC->Encloses(CurContext)) | ||||||
1517 | break; | ||||||
1518 | } | ||||||
1519 | |||||||
1520 | IdResolver.InsertDeclAfter(I, D); | ||||||
1521 | } else { | ||||||
1522 | IdResolver.AddDecl(D); | ||||||
1523 | } | ||||||
1524 | } | ||||||
1525 | |||||||
1526 | bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, | ||||||
1527 | bool AllowInlineNamespace) { | ||||||
1528 | return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); | ||||||
1529 | } | ||||||
1530 | |||||||
1531 | Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { | ||||||
1532 | DeclContext *TargetDC = DC->getPrimaryContext(); | ||||||
1533 | do { | ||||||
1534 | if (DeclContext *ScopeDC = S->getEntity()) | ||||||
1535 | if (ScopeDC->getPrimaryContext() == TargetDC) | ||||||
1536 | return S; | ||||||
1537 | } while ((S = S->getParent())); | ||||||
1538 | |||||||
1539 | return nullptr; | ||||||
1540 | } | ||||||
1541 | |||||||
1542 | static bool isOutOfScopePreviousDeclaration(NamedDecl *, | ||||||
1543 | DeclContext*, | ||||||
1544 | ASTContext&); | ||||||
1545 | |||||||
1546 | /// Filters out lookup results that don't fall within the given scope | ||||||
1547 | /// as determined by isDeclInScope. | ||||||
1548 | void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, | ||||||
1549 | bool ConsiderLinkage, | ||||||
1550 | bool AllowInlineNamespace) { | ||||||
1551 | LookupResult::Filter F = R.makeFilter(); | ||||||
1552 | while (F.hasNext()) { | ||||||
1553 | NamedDecl *D = F.next(); | ||||||
1554 | |||||||
1555 | if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) | ||||||
1556 | continue; | ||||||
1557 | |||||||
1558 | if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) | ||||||
1559 | continue; | ||||||
1560 | |||||||
1561 | F.erase(); | ||||||
1562 | } | ||||||
1563 | |||||||
1564 | F.done(); | ||||||
1565 | } | ||||||
1566 | |||||||
1567 | /// We've determined that \p New is a redeclaration of \p Old. Check that they | ||||||
1568 | /// have compatible owning modules. | ||||||
1569 | bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { | ||||||
1570 | // FIXME: The Modules TS is not clear about how friend declarations are | ||||||
1571 | // to be treated. It's not meaningful to have different owning modules for | ||||||
1572 | // linkage in redeclarations of the same entity, so for now allow the | ||||||
1573 | // redeclaration and change the owning modules to match. | ||||||
1574 | if (New->getFriendObjectKind() && | ||||||
1575 | Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { | ||||||
1576 | New->setLocalOwningModule(Old->getOwningModule()); | ||||||
1577 | makeMergedDefinitionVisible(New); | ||||||
1578 | return false; | ||||||
1579 | } | ||||||
1580 | |||||||
1581 | Module *NewM = New->getOwningModule(); | ||||||
1582 | Module *OldM = Old->getOwningModule(); | ||||||
1583 | |||||||
1584 | if (NewM && NewM->Kind == Module::PrivateModuleFragment) | ||||||
1585 | NewM = NewM->Parent; | ||||||
1586 | if (OldM && OldM->Kind == Module::PrivateModuleFragment) | ||||||
1587 | OldM = OldM->Parent; | ||||||
1588 | |||||||
1589 | if (NewM == OldM) | ||||||
1590 | return false; | ||||||
1591 | |||||||
1592 | bool NewIsModuleInterface = NewM && NewM->isModulePurview(); | ||||||
1593 | bool OldIsModuleInterface = OldM && OldM->isModulePurview(); | ||||||
1594 | if (NewIsModuleInterface || OldIsModuleInterface) { | ||||||
1595 | // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: | ||||||
1596 | // if a declaration of D [...] appears in the purview of a module, all | ||||||
1597 | // other such declarations shall appear in the purview of the same module | ||||||
1598 | Diag(New->getLocation(), diag::err_mismatched_owning_module) | ||||||
1599 | << New | ||||||
1600 | << NewIsModuleInterface | ||||||
1601 | << (NewIsModuleInterface ? NewM->getFullModuleName() : "") | ||||||
1602 | << OldIsModuleInterface | ||||||
1603 | << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); | ||||||
1604 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
1605 | New->setInvalidDecl(); | ||||||
1606 | return true; | ||||||
1607 | } | ||||||
1608 | |||||||
1609 | return false; | ||||||
1610 | } | ||||||
1611 | |||||||
1612 | static bool isUsingDecl(NamedDecl *D) { | ||||||
1613 | return isa<UsingShadowDecl>(D) || | ||||||
1614 | isa<UnresolvedUsingTypenameDecl>(D) || | ||||||
1615 | isa<UnresolvedUsingValueDecl>(D); | ||||||
1616 | } | ||||||
1617 | |||||||
1618 | /// Removes using shadow declarations from the lookup results. | ||||||
1619 | static void RemoveUsingDecls(LookupResult &R) { | ||||||
1620 | LookupResult::Filter F = R.makeFilter(); | ||||||
1621 | while (F.hasNext()) | ||||||
1622 | if (isUsingDecl(F.next())) | ||||||
1623 | F.erase(); | ||||||
1624 | |||||||
1625 | F.done(); | ||||||
1626 | } | ||||||
1627 | |||||||
1628 | /// Check for this common pattern: | ||||||
1629 | /// @code | ||||||
1630 | /// class S { | ||||||
1631 | /// S(const S&); // DO NOT IMPLEMENT | ||||||
1632 | /// void operator=(const S&); // DO NOT IMPLEMENT | ||||||
1633 | /// }; | ||||||
1634 | /// @endcode | ||||||
1635 | static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { | ||||||
1636 | // FIXME: Should check for private access too but access is set after we get | ||||||
1637 | // the decl here. | ||||||
1638 | if (D->doesThisDeclarationHaveABody()) | ||||||
1639 | return false; | ||||||
1640 | |||||||
1641 | if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) | ||||||
1642 | return CD->isCopyConstructor(); | ||||||
1643 | return D->isCopyAssignmentOperator(); | ||||||
1644 | } | ||||||
1645 | |||||||
1646 | // We need this to handle | ||||||
1647 | // | ||||||
1648 | // typedef struct { | ||||||
1649 | // void *foo() { return 0; } | ||||||
1650 | // } A; | ||||||
1651 | // | ||||||
1652 | // When we see foo we don't know if after the typedef we will get 'A' or '*A' | ||||||
1653 | // for example. If 'A', foo will have external linkage. If we have '*A', | ||||||
1654 | // foo will have no linkage. Since we can't know until we get to the end | ||||||
1655 | // of the typedef, this function finds out if D might have non-external linkage. | ||||||
1656 | // Callers should verify at the end of the TU if it D has external linkage or | ||||||
1657 | // not. | ||||||
1658 | bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { | ||||||
1659 | const DeclContext *DC = D->getDeclContext(); | ||||||
1660 | while (!DC->isTranslationUnit()) { | ||||||
1661 | if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ | ||||||
1662 | if (!RD->hasNameForLinkage()) | ||||||
1663 | return true; | ||||||
1664 | } | ||||||
1665 | DC = DC->getParent(); | ||||||
1666 | } | ||||||
1667 | |||||||
1668 | return !D->isExternallyVisible(); | ||||||
1669 | } | ||||||
1670 | |||||||
1671 | // FIXME: This needs to be refactored; some other isInMainFile users want | ||||||
1672 | // these semantics. | ||||||
1673 | static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { | ||||||
1674 | if (S.TUKind != TU_Complete) | ||||||
1675 | return false; | ||||||
1676 | return S.SourceMgr.isInMainFile(Loc); | ||||||
1677 | } | ||||||
1678 | |||||||
1679 | bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { | ||||||
1680 | assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1680, __PRETTY_FUNCTION__)); | ||||||
1681 | |||||||
1682 | if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) | ||||||
1683 | return false; | ||||||
1684 | |||||||
1685 | // Ignore all entities declared within templates, and out-of-line definitions | ||||||
1686 | // of members of class templates. | ||||||
1687 | if (D->getDeclContext()->isDependentContext() || | ||||||
1688 | D->getLexicalDeclContext()->isDependentContext()) | ||||||
1689 | return false; | ||||||
1690 | |||||||
1691 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||
1692 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||||
1693 | return false; | ||||||
1694 | // A non-out-of-line declaration of a member specialization was implicitly | ||||||
1695 | // instantiated; it's the out-of-line declaration that we're interested in. | ||||||
1696 | if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||||
1697 | FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) | ||||||
1698 | return false; | ||||||
1699 | |||||||
1700 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
1701 | if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) | ||||||
1702 | return false; | ||||||
1703 | } else { | ||||||
1704 | // 'static inline' functions are defined in headers; don't warn. | ||||||
1705 | if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) | ||||||
1706 | return false; | ||||||
1707 | } | ||||||
1708 | |||||||
1709 | if (FD->doesThisDeclarationHaveABody() && | ||||||
1710 | Context.DeclMustBeEmitted(FD)) | ||||||
1711 | return false; | ||||||
1712 | } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1713 | // Constants and utility variables are defined in headers with internal | ||||||
1714 | // linkage; don't warn. (Unlike functions, there isn't a convenient marker | ||||||
1715 | // like "inline".) | ||||||
1716 | if (!isMainFileLoc(*this, VD->getLocation())) | ||||||
1717 | return false; | ||||||
1718 | |||||||
1719 | if (Context.DeclMustBeEmitted(VD)) | ||||||
1720 | return false; | ||||||
1721 | |||||||
1722 | if (VD->isStaticDataMember() && | ||||||
1723 | VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) | ||||||
1724 | return false; | ||||||
1725 | if (VD->isStaticDataMember() && | ||||||
1726 | VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && | ||||||
1727 | VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) | ||||||
1728 | return false; | ||||||
1729 | |||||||
1730 | if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) | ||||||
1731 | return false; | ||||||
1732 | } else { | ||||||
1733 | return false; | ||||||
1734 | } | ||||||
1735 | |||||||
1736 | // Only warn for unused decls internal to the translation unit. | ||||||
1737 | // FIXME: This seems like a bogus check; it suppresses -Wunused-function | ||||||
1738 | // for inline functions defined in the main source file, for instance. | ||||||
1739 | return mightHaveNonExternalLinkage(D); | ||||||
1740 | } | ||||||
1741 | |||||||
1742 | void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { | ||||||
1743 | if (!D) | ||||||
1744 | return; | ||||||
1745 | |||||||
1746 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { | ||||||
1747 | const FunctionDecl *First = FD->getFirstDecl(); | ||||||
1748 | if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||||
1749 | return; // First should already be in the vector. | ||||||
1750 | } | ||||||
1751 | |||||||
1752 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1753 | const VarDecl *First = VD->getFirstDecl(); | ||||||
1754 | if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) | ||||||
1755 | return; // First should already be in the vector. | ||||||
1756 | } | ||||||
1757 | |||||||
1758 | if (ShouldWarnIfUnusedFileScopedDecl(D)) | ||||||
1759 | UnusedFileScopedDecls.push_back(D); | ||||||
1760 | } | ||||||
1761 | |||||||
1762 | static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { | ||||||
1763 | if (D->isInvalidDecl()) | ||||||
1764 | return false; | ||||||
1765 | |||||||
1766 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) { | ||||||
1767 | // For a decomposition declaration, warn if none of the bindings are | ||||||
1768 | // referenced, instead of if the variable itself is referenced (which | ||||||
1769 | // it is, by the bindings' expressions). | ||||||
1770 | for (auto *BD : DD->bindings()) | ||||||
1771 | if (BD->isReferenced()) | ||||||
1772 | return false; | ||||||
1773 | } else if (!D->getDeclName()) { | ||||||
1774 | return false; | ||||||
1775 | } else if (D->isReferenced() || D->isUsed()) { | ||||||
1776 | return false; | ||||||
1777 | } | ||||||
1778 | |||||||
1779 | if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>()) | ||||||
1780 | return false; | ||||||
1781 | |||||||
1782 | if (isa<LabelDecl>(D)) | ||||||
1783 | return true; | ||||||
1784 | |||||||
1785 | // Except for labels, we only care about unused decls that are local to | ||||||
1786 | // functions. | ||||||
1787 | bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); | ||||||
1788 | if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) | ||||||
1789 | // For dependent types, the diagnostic is deferred. | ||||||
1790 | WithinFunction = | ||||||
1791 | WithinFunction || (R->isLocalClass() && !R->isDependentType()); | ||||||
1792 | if (!WithinFunction) | ||||||
1793 | return false; | ||||||
1794 | |||||||
1795 | if (isa<TypedefNameDecl>(D)) | ||||||
1796 | return true; | ||||||
1797 | |||||||
1798 | // White-list anything that isn't a local variable. | ||||||
1799 | if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) | ||||||
1800 | return false; | ||||||
1801 | |||||||
1802 | // Types of valid local variables should be complete, so this should succeed. | ||||||
1803 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
1804 | |||||||
1805 | // White-list anything with an __attribute__((unused)) type. | ||||||
1806 | const auto *Ty = VD->getType().getTypePtr(); | ||||||
1807 | |||||||
1808 | // Only look at the outermost level of typedef. | ||||||
1809 | if (const TypedefType *TT = Ty->getAs<TypedefType>()) { | ||||||
1810 | if (TT->getDecl()->hasAttr<UnusedAttr>()) | ||||||
1811 | return false; | ||||||
1812 | } | ||||||
1813 | |||||||
1814 | // If we failed to complete the type for some reason, or if the type is | ||||||
1815 | // dependent, don't diagnose the variable. | ||||||
1816 | if (Ty->isIncompleteType() || Ty->isDependentType()) | ||||||
1817 | return false; | ||||||
1818 | |||||||
1819 | // Look at the element type to ensure that the warning behaviour is | ||||||
1820 | // consistent for both scalars and arrays. | ||||||
1821 | Ty = Ty->getBaseElementTypeUnsafe(); | ||||||
1822 | |||||||
1823 | if (const TagType *TT = Ty->getAs<TagType>()) { | ||||||
1824 | const TagDecl *Tag = TT->getDecl(); | ||||||
1825 | if (Tag->hasAttr<UnusedAttr>()) | ||||||
1826 | return false; | ||||||
1827 | |||||||
1828 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { | ||||||
1829 | if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) | ||||||
1830 | return false; | ||||||
1831 | |||||||
1832 | if (const Expr *Init = VD->getInit()) { | ||||||
1833 | if (const ExprWithCleanups *Cleanups = | ||||||
1834 | dyn_cast<ExprWithCleanups>(Init)) | ||||||
1835 | Init = Cleanups->getSubExpr(); | ||||||
1836 | const CXXConstructExpr *Construct = | ||||||
1837 | dyn_cast<CXXConstructExpr>(Init); | ||||||
1838 | if (Construct && !Construct->isElidable()) { | ||||||
1839 | CXXConstructorDecl *CD = Construct->getConstructor(); | ||||||
1840 | if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && | ||||||
1841 | (VD->getInit()->isValueDependent() || !VD->evaluateValue())) | ||||||
1842 | return false; | ||||||
1843 | } | ||||||
1844 | |||||||
1845 | // Suppress the warning if we don't know how this is constructed, and | ||||||
1846 | // it could possibly be non-trivial constructor. | ||||||
1847 | if (Init->isTypeDependent()) | ||||||
1848 | for (const CXXConstructorDecl *Ctor : RD->ctors()) | ||||||
1849 | if (!Ctor->isTrivial()) | ||||||
1850 | return false; | ||||||
1851 | } | ||||||
1852 | } | ||||||
1853 | } | ||||||
1854 | |||||||
1855 | // TODO: __attribute__((unused)) templates? | ||||||
1856 | } | ||||||
1857 | |||||||
1858 | return true; | ||||||
1859 | } | ||||||
1860 | |||||||
1861 | static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, | ||||||
1862 | FixItHint &Hint) { | ||||||
1863 | if (isa<LabelDecl>(D)) { | ||||||
1864 | SourceLocation AfterColon = Lexer::findLocationAfterToken( | ||||||
1865 | D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), | ||||||
1866 | true); | ||||||
1867 | if (AfterColon.isInvalid()) | ||||||
1868 | return; | ||||||
1869 | Hint = FixItHint::CreateRemoval( | ||||||
1870 | CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); | ||||||
1871 | } | ||||||
1872 | } | ||||||
1873 | |||||||
1874 | void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { | ||||||
1875 | if (D->getTypeForDecl()->isDependentType()) | ||||||
1876 | return; | ||||||
1877 | |||||||
1878 | for (auto *TmpD : D->decls()) { | ||||||
1879 | if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) | ||||||
1880 | DiagnoseUnusedDecl(T); | ||||||
1881 | else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) | ||||||
1882 | DiagnoseUnusedNestedTypedefs(R); | ||||||
1883 | } | ||||||
1884 | } | ||||||
1885 | |||||||
1886 | /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used | ||||||
1887 | /// unless they are marked attr(unused). | ||||||
1888 | void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { | ||||||
1889 | if (!ShouldDiagnoseUnusedDecl(D)) | ||||||
1890 | return; | ||||||
1891 | |||||||
1892 | if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { | ||||||
1893 | // typedefs can be referenced later on, so the diagnostics are emitted | ||||||
1894 | // at end-of-translation-unit. | ||||||
1895 | UnusedLocalTypedefNameCandidates.insert(TD); | ||||||
1896 | return; | ||||||
1897 | } | ||||||
1898 | |||||||
1899 | FixItHint Hint; | ||||||
1900 | GenerateFixForUnusedDecl(D, Context, Hint); | ||||||
1901 | |||||||
1902 | unsigned DiagID; | ||||||
1903 | if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) | ||||||
1904 | DiagID = diag::warn_unused_exception_param; | ||||||
1905 | else if (isa<LabelDecl>(D)) | ||||||
1906 | DiagID = diag::warn_unused_label; | ||||||
1907 | else | ||||||
1908 | DiagID = diag::warn_unused_variable; | ||||||
1909 | |||||||
1910 | Diag(D->getLocation(), DiagID) << D << Hint; | ||||||
1911 | } | ||||||
1912 | |||||||
1913 | static void CheckPoppedLabel(LabelDecl *L, Sema &S) { | ||||||
1914 | // Verify that we have no forward references left. If so, there was a goto | ||||||
1915 | // or address of a label taken, but no definition of it. Label fwd | ||||||
1916 | // definitions are indicated with a null substmt which is also not a resolved | ||||||
1917 | // MS inline assembly label name. | ||||||
1918 | bool Diagnose = false; | ||||||
1919 | if (L->isMSAsmLabel()) | ||||||
1920 | Diagnose = !L->isResolvedMSAsmLabel(); | ||||||
1921 | else | ||||||
1922 | Diagnose = L->getStmt() == nullptr; | ||||||
1923 | if (Diagnose) | ||||||
1924 | S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L; | ||||||
1925 | } | ||||||
1926 | |||||||
1927 | void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { | ||||||
1928 | S->mergeNRVOIntoParent(); | ||||||
1929 | |||||||
1930 | if (S->decl_empty()) return; | ||||||
1931 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1932, __PRETTY_FUNCTION__)) | ||||||
1932 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1932, __PRETTY_FUNCTION__)); | ||||||
1933 | |||||||
1934 | for (auto *TmpD : S->decls()) { | ||||||
1935 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1935, __PRETTY_FUNCTION__)); | ||||||
1936 | |||||||
1937 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 1937, __PRETTY_FUNCTION__)); | ||||||
1938 | NamedDecl *D = cast<NamedDecl>(TmpD); | ||||||
1939 | |||||||
1940 | // Diagnose unused variables in this scope. | ||||||
1941 | if (!S->hasUnrecoverableErrorOccurred()) { | ||||||
1942 | DiagnoseUnusedDecl(D); | ||||||
1943 | if (const auto *RD = dyn_cast<RecordDecl>(D)) | ||||||
1944 | DiagnoseUnusedNestedTypedefs(RD); | ||||||
1945 | } | ||||||
1946 | |||||||
1947 | if (!D->getDeclName()) continue; | ||||||
1948 | |||||||
1949 | // If this was a forward reference to a label, verify it was defined. | ||||||
1950 | if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) | ||||||
1951 | CheckPoppedLabel(LD, *this); | ||||||
1952 | |||||||
1953 | // Remove this name from our lexical scope, and warn on it if we haven't | ||||||
1954 | // already. | ||||||
1955 | IdResolver.RemoveDecl(D); | ||||||
1956 | auto ShadowI = ShadowingDecls.find(D); | ||||||
1957 | if (ShadowI != ShadowingDecls.end()) { | ||||||
1958 | if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { | ||||||
1959 | Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) | ||||||
1960 | << D << FD << FD->getParent(); | ||||||
1961 | Diag(FD->getLocation(), diag::note_previous_declaration); | ||||||
1962 | } | ||||||
1963 | ShadowingDecls.erase(ShadowI); | ||||||
1964 | } | ||||||
1965 | } | ||||||
1966 | } | ||||||
1967 | |||||||
1968 | /// Look for an Objective-C class in the translation unit. | ||||||
1969 | /// | ||||||
1970 | /// \param Id The name of the Objective-C class we're looking for. If | ||||||
1971 | /// typo-correction fixes this name, the Id will be updated | ||||||
1972 | /// to the fixed name. | ||||||
1973 | /// | ||||||
1974 | /// \param IdLoc The location of the name in the translation unit. | ||||||
1975 | /// | ||||||
1976 | /// \param DoTypoCorrection If true, this routine will attempt typo correction | ||||||
1977 | /// if there is no class with the given name. | ||||||
1978 | /// | ||||||
1979 | /// \returns The declaration of the named Objective-C class, or NULL if the | ||||||
1980 | /// class could not be found. | ||||||
1981 | ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, | ||||||
1982 | SourceLocation IdLoc, | ||||||
1983 | bool DoTypoCorrection) { | ||||||
1984 | // The third "scope" argument is 0 since we aren't enabling lazy built-in | ||||||
1985 | // creation from this context. | ||||||
1986 | NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); | ||||||
1987 | |||||||
1988 | if (!IDecl && DoTypoCorrection) { | ||||||
1989 | // Perform typo correction at the given location, but only if we | ||||||
1990 | // find an Objective-C class name. | ||||||
1991 | DeclFilterCCC<ObjCInterfaceDecl> CCC{}; | ||||||
1992 | if (TypoCorrection C = | ||||||
1993 | CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, | ||||||
1994 | TUScope, nullptr, CCC, CTK_ErrorRecovery)) { | ||||||
1995 | diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); | ||||||
1996 | IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); | ||||||
1997 | Id = IDecl->getIdentifier(); | ||||||
1998 | } | ||||||
1999 | } | ||||||
2000 | ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); | ||||||
2001 | // This routine must always return a class definition, if any. | ||||||
2002 | if (Def && Def->getDefinition()) | ||||||
2003 | Def = Def->getDefinition(); | ||||||
2004 | return Def; | ||||||
2005 | } | ||||||
2006 | |||||||
2007 | /// getNonFieldDeclScope - Retrieves the innermost scope, starting | ||||||
2008 | /// from S, where a non-field would be declared. This routine copes | ||||||
2009 | /// with the difference between C and C++ scoping rules in structs and | ||||||
2010 | /// unions. For example, the following code is well-formed in C but | ||||||
2011 | /// ill-formed in C++: | ||||||
2012 | /// @code | ||||||
2013 | /// struct S6 { | ||||||
2014 | /// enum { BAR } e; | ||||||
2015 | /// }; | ||||||
2016 | /// | ||||||
2017 | /// void test_S6() { | ||||||
2018 | /// struct S6 a; | ||||||
2019 | /// a.e = BAR; | ||||||
2020 | /// } | ||||||
2021 | /// @endcode | ||||||
2022 | /// For the declaration of BAR, this routine will return a different | ||||||
2023 | /// scope. The scope S will be the scope of the unnamed enumeration | ||||||
2024 | /// within S6. In C++, this routine will return the scope associated | ||||||
2025 | /// with S6, because the enumeration's scope is a transparent | ||||||
2026 | /// context but structures can contain non-field names. In C, this | ||||||
2027 | /// routine will return the translation unit scope, since the | ||||||
2028 | /// enumeration's scope is a transparent context and structures cannot | ||||||
2029 | /// contain non-field names. | ||||||
2030 | Scope *Sema::getNonFieldDeclScope(Scope *S) { | ||||||
2031 | while (((S->getFlags() & Scope::DeclScope) == 0) || | ||||||
2032 | (S->getEntity() && S->getEntity()->isTransparentContext()) || | ||||||
2033 | (S->isClassScope() && !getLangOpts().CPlusPlus)) | ||||||
2034 | S = S->getParent(); | ||||||
2035 | return S; | ||||||
2036 | } | ||||||
2037 | |||||||
2038 | static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, | ||||||
2039 | ASTContext::GetBuiltinTypeError Error) { | ||||||
2040 | switch (Error) { | ||||||
2041 | case ASTContext::GE_None: | ||||||
2042 | return ""; | ||||||
2043 | case ASTContext::GE_Missing_type: | ||||||
2044 | return BuiltinInfo.getHeaderName(ID); | ||||||
2045 | case ASTContext::GE_Missing_stdio: | ||||||
2046 | return "stdio.h"; | ||||||
2047 | case ASTContext::GE_Missing_setjmp: | ||||||
2048 | return "setjmp.h"; | ||||||
2049 | case ASTContext::GE_Missing_ucontext: | ||||||
2050 | return "ucontext.h"; | ||||||
2051 | } | ||||||
2052 | llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 2052); | ||||||
2053 | } | ||||||
2054 | |||||||
2055 | FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type, | ||||||
2056 | unsigned ID, SourceLocation Loc) { | ||||||
2057 | DeclContext *Parent = Context.getTranslationUnitDecl(); | ||||||
2058 | |||||||
2059 | if (getLangOpts().CPlusPlus) { | ||||||
2060 | LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create( | ||||||
2061 | Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false); | ||||||
2062 | CLinkageDecl->setImplicit(); | ||||||
2063 | Parent->addDecl(CLinkageDecl); | ||||||
2064 | Parent = CLinkageDecl; | ||||||
2065 | } | ||||||
2066 | |||||||
2067 | FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type, | ||||||
2068 | /*TInfo=*/nullptr, SC_Extern, false, | ||||||
2069 | Type->isFunctionProtoType()); | ||||||
2070 | New->setImplicit(); | ||||||
2071 | New->addAttr(BuiltinAttr::CreateImplicit(Context, ID)); | ||||||
2072 | |||||||
2073 | // Create Decl objects for each parameter, adding them to the | ||||||
2074 | // FunctionDecl. | ||||||
2075 | if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) { | ||||||
2076 | SmallVector<ParmVarDecl *, 16> Params; | ||||||
2077 | for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { | ||||||
2078 | ParmVarDecl *parm = ParmVarDecl::Create( | ||||||
2079 | Context, New, SourceLocation(), SourceLocation(), nullptr, | ||||||
2080 | FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr); | ||||||
2081 | parm->setScopeInfo(0, i); | ||||||
2082 | Params.push_back(parm); | ||||||
2083 | } | ||||||
2084 | New->setParams(Params); | ||||||
2085 | } | ||||||
2086 | |||||||
2087 | AddKnownFunctionAttributes(New); | ||||||
2088 | return New; | ||||||
2089 | } | ||||||
2090 | |||||||
2091 | /// LazilyCreateBuiltin - The specified Builtin-ID was first used at | ||||||
2092 | /// file scope. lazily create a decl for it. ForRedeclaration is true | ||||||
2093 | /// if we're creating this built-in in anticipation of redeclaring the | ||||||
2094 | /// built-in. | ||||||
2095 | NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, | ||||||
2096 | Scope *S, bool ForRedeclaration, | ||||||
2097 | SourceLocation Loc) { | ||||||
2098 | LookupNecessaryTypesForBuiltin(S, ID); | ||||||
2099 | |||||||
2100 | ASTContext::GetBuiltinTypeError Error; | ||||||
2101 | QualType R = Context.GetBuiltinType(ID, Error); | ||||||
2102 | if (Error) { | ||||||
2103 | if (!ForRedeclaration) | ||||||
2104 | return nullptr; | ||||||
2105 | |||||||
2106 | // If we have a builtin without an associated type we should not emit a | ||||||
2107 | // warning when we were not able to find a type for it. | ||||||
2108 | if (Error == ASTContext::GE_Missing_type) | ||||||
2109 | return nullptr; | ||||||
2110 | |||||||
2111 | // If we could not find a type for setjmp it is because the jmp_buf type was | ||||||
2112 | // not defined prior to the setjmp declaration. | ||||||
2113 | if (Error == ASTContext::GE_Missing_setjmp) { | ||||||
2114 | Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) | ||||||
2115 | << Context.BuiltinInfo.getName(ID); | ||||||
2116 | return nullptr; | ||||||
2117 | } | ||||||
2118 | |||||||
2119 | // Generally, we emit a warning that the declaration requires the | ||||||
2120 | // appropriate header. | ||||||
2121 | Diag(Loc, diag::warn_implicit_decl_requires_sysheader) | ||||||
2122 | << getHeaderName(Context.BuiltinInfo, ID, Error) | ||||||
2123 | << Context.BuiltinInfo.getName(ID); | ||||||
2124 | return nullptr; | ||||||
2125 | } | ||||||
2126 | |||||||
2127 | if (!ForRedeclaration && | ||||||
2128 | (Context.BuiltinInfo.isPredefinedLibFunction(ID) || | ||||||
2129 | Context.BuiltinInfo.isHeaderDependentFunction(ID))) { | ||||||
2130 | Diag(Loc, diag::ext_implicit_lib_function_decl) | ||||||
2131 | << Context.BuiltinInfo.getName(ID) << R; | ||||||
2132 | if (Context.BuiltinInfo.getHeaderName(ID) && | ||||||
2133 | !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) | ||||||
2134 | Diag(Loc, diag::note_include_header_or_declare) | ||||||
2135 | << Context.BuiltinInfo.getHeaderName(ID) | ||||||
2136 | << Context.BuiltinInfo.getName(ID); | ||||||
2137 | } | ||||||
2138 | |||||||
2139 | if (R.isNull()) | ||||||
2140 | return nullptr; | ||||||
2141 | |||||||
2142 | FunctionDecl *New = CreateBuiltin(II, R, ID, Loc); | ||||||
2143 | RegisterLocallyScopedExternCDecl(New, S); | ||||||
2144 | |||||||
2145 | // TUScope is the translation-unit scope to insert this function into. | ||||||
2146 | // FIXME: This is hideous. We need to teach PushOnScopeChains to | ||||||
2147 | // relate Scopes to DeclContexts, and probably eliminate CurContext | ||||||
2148 | // entirely, but we're not there yet. | ||||||
2149 | DeclContext *SavedContext = CurContext; | ||||||
2150 | CurContext = New->getDeclContext(); | ||||||
2151 | PushOnScopeChains(New, TUScope); | ||||||
2152 | CurContext = SavedContext; | ||||||
2153 | return New; | ||||||
2154 | } | ||||||
2155 | |||||||
2156 | /// Typedef declarations don't have linkage, but they still denote the same | ||||||
2157 | /// entity if their types are the same. | ||||||
2158 | /// FIXME: This is notionally doing the same thing as ASTReaderDecl's | ||||||
2159 | /// isSameEntity. | ||||||
2160 | static void filterNonConflictingPreviousTypedefDecls(Sema &S, | ||||||
2161 | TypedefNameDecl *Decl, | ||||||
2162 | LookupResult &Previous) { | ||||||
2163 | // This is only interesting when modules are enabled. | ||||||
2164 | if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) | ||||||
2165 | return; | ||||||
2166 | |||||||
2167 | // Empty sets are uninteresting. | ||||||
2168 | if (Previous.empty()) | ||||||
2169 | return; | ||||||
2170 | |||||||
2171 | LookupResult::Filter Filter = Previous.makeFilter(); | ||||||
2172 | while (Filter.hasNext()) { | ||||||
2173 | NamedDecl *Old = Filter.next(); | ||||||
2174 | |||||||
2175 | // Non-hidden declarations are never ignored. | ||||||
2176 | if (S.isVisible(Old)) | ||||||
2177 | continue; | ||||||
2178 | |||||||
2179 | // Declarations of the same entity are not ignored, even if they have | ||||||
2180 | // different linkages. | ||||||
2181 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2182 | if (S.Context.hasSameType(OldTD->getUnderlyingType(), | ||||||
2183 | Decl->getUnderlyingType())) | ||||||
2184 | continue; | ||||||
2185 | |||||||
2186 | // If both declarations give a tag declaration a typedef name for linkage | ||||||
2187 | // purposes, then they declare the same entity. | ||||||
2188 | if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && | ||||||
2189 | Decl->getAnonDeclWithTypedefName()) | ||||||
2190 | continue; | ||||||
2191 | } | ||||||
2192 | |||||||
2193 | Filter.erase(); | ||||||
2194 | } | ||||||
2195 | |||||||
2196 | Filter.done(); | ||||||
2197 | } | ||||||
2198 | |||||||
2199 | bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { | ||||||
2200 | QualType OldType; | ||||||
2201 | if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) | ||||||
2202 | OldType = OldTypedef->getUnderlyingType(); | ||||||
2203 | else | ||||||
2204 | OldType = Context.getTypeDeclType(Old); | ||||||
2205 | QualType NewType = New->getUnderlyingType(); | ||||||
2206 | |||||||
2207 | if (NewType->isVariablyModifiedType()) { | ||||||
2208 | // Must not redefine a typedef with a variably-modified type. | ||||||
2209 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||||
2210 | Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) | ||||||
2211 | << Kind << NewType; | ||||||
2212 | if (Old->getLocation().isValid()) | ||||||
2213 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2214 | New->setInvalidDecl(); | ||||||
2215 | return true; | ||||||
2216 | } | ||||||
2217 | |||||||
2218 | if (OldType != NewType && | ||||||
2219 | !OldType->isDependentType() && | ||||||
2220 | !NewType->isDependentType() && | ||||||
2221 | !Context.hasSameType(OldType, NewType)) { | ||||||
2222 | int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; | ||||||
2223 | Diag(New->getLocation(), diag::err_redefinition_different_typedef) | ||||||
2224 | << Kind << NewType << OldType; | ||||||
2225 | if (Old->getLocation().isValid()) | ||||||
2226 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2227 | New->setInvalidDecl(); | ||||||
2228 | return true; | ||||||
2229 | } | ||||||
2230 | return false; | ||||||
2231 | } | ||||||
2232 | |||||||
2233 | /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the | ||||||
2234 | /// same name and scope as a previous declaration 'Old'. Figure out | ||||||
2235 | /// how to resolve this situation, merging decls or emitting | ||||||
2236 | /// diagnostics as appropriate. If there was an error, set New to be invalid. | ||||||
2237 | /// | ||||||
2238 | void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, | ||||||
2239 | LookupResult &OldDecls) { | ||||||
2240 | // If the new decl is known invalid already, don't bother doing any | ||||||
2241 | // merging checks. | ||||||
2242 | if (New->isInvalidDecl()) return; | ||||||
2243 | |||||||
2244 | // Allow multiple definitions for ObjC built-in typedefs. | ||||||
2245 | // FIXME: Verify the underlying types are equivalent! | ||||||
2246 | if (getLangOpts().ObjC) { | ||||||
2247 | const IdentifierInfo *TypeID = New->getIdentifier(); | ||||||
2248 | switch (TypeID->getLength()) { | ||||||
2249 | default: break; | ||||||
2250 | case 2: | ||||||
2251 | { | ||||||
2252 | if (!TypeID->isStr("id")) | ||||||
2253 | break; | ||||||
2254 | QualType T = New->getUnderlyingType(); | ||||||
2255 | if (!T->isPointerType()) | ||||||
2256 | break; | ||||||
2257 | if (!T->isVoidPointerType()) { | ||||||
2258 | QualType PT = T->castAs<PointerType>()->getPointeeType(); | ||||||
2259 | if (!PT->isStructureType()) | ||||||
2260 | break; | ||||||
2261 | } | ||||||
2262 | Context.setObjCIdRedefinitionType(T); | ||||||
2263 | // Install the built-in type for 'id', ignoring the current definition. | ||||||
2264 | New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); | ||||||
2265 | return; | ||||||
2266 | } | ||||||
2267 | case 5: | ||||||
2268 | if (!TypeID->isStr("Class")) | ||||||
2269 | break; | ||||||
2270 | Context.setObjCClassRedefinitionType(New->getUnderlyingType()); | ||||||
2271 | // Install the built-in type for 'Class', ignoring the current definition. | ||||||
2272 | New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); | ||||||
2273 | return; | ||||||
2274 | case 3: | ||||||
2275 | if (!TypeID->isStr("SEL")) | ||||||
2276 | break; | ||||||
2277 | Context.setObjCSelRedefinitionType(New->getUnderlyingType()); | ||||||
2278 | // Install the built-in type for 'SEL', ignoring the current definition. | ||||||
2279 | New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); | ||||||
2280 | return; | ||||||
2281 | } | ||||||
2282 | // Fall through - the typedef name was not a builtin type. | ||||||
2283 | } | ||||||
2284 | |||||||
2285 | // Verify the old decl was also a type. | ||||||
2286 | TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); | ||||||
2287 | if (!Old) { | ||||||
2288 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
2289 | << New->getDeclName(); | ||||||
2290 | |||||||
2291 | NamedDecl *OldD = OldDecls.getRepresentativeDecl(); | ||||||
2292 | if (OldD->getLocation().isValid()) | ||||||
2293 | notePreviousDefinition(OldD, New->getLocation()); | ||||||
2294 | |||||||
2295 | return New->setInvalidDecl(); | ||||||
2296 | } | ||||||
2297 | |||||||
2298 | // If the old declaration is invalid, just give up here. | ||||||
2299 | if (Old->isInvalidDecl()) | ||||||
2300 | return New->setInvalidDecl(); | ||||||
2301 | |||||||
2302 | if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2303 | auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); | ||||||
2304 | auto *NewTag = New->getAnonDeclWithTypedefName(); | ||||||
2305 | NamedDecl *Hidden = nullptr; | ||||||
2306 | if (OldTag && NewTag && | ||||||
2307 | OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && | ||||||
2308 | !hasVisibleDefinition(OldTag, &Hidden)) { | ||||||
2309 | // There is a definition of this tag, but it is not visible. Use it | ||||||
2310 | // instead of our tag. | ||||||
2311 | New->setTypeForDecl(OldTD->getTypeForDecl()); | ||||||
2312 | if (OldTD->isModed()) | ||||||
2313 | New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), | ||||||
2314 | OldTD->getUnderlyingType()); | ||||||
2315 | else | ||||||
2316 | New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); | ||||||
2317 | |||||||
2318 | // Make the old tag definition visible. | ||||||
2319 | makeMergedDefinitionVisible(Hidden); | ||||||
2320 | |||||||
2321 | // If this was an unscoped enumeration, yank all of its enumerators | ||||||
2322 | // out of the scope. | ||||||
2323 | if (isa<EnumDecl>(NewTag)) { | ||||||
2324 | Scope *EnumScope = getNonFieldDeclScope(S); | ||||||
2325 | for (auto *D : NewTag->decls()) { | ||||||
2326 | auto *ED = cast<EnumConstantDecl>(D); | ||||||
2327 | assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0 ) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 2327, __PRETTY_FUNCTION__)); | ||||||
2328 | EnumScope->RemoveDecl(ED); | ||||||
2329 | IdResolver.RemoveDecl(ED); | ||||||
2330 | ED->getLexicalDeclContext()->removeDecl(ED); | ||||||
2331 | } | ||||||
2332 | } | ||||||
2333 | } | ||||||
2334 | } | ||||||
2335 | |||||||
2336 | // If the typedef types are not identical, reject them in all languages and | ||||||
2337 | // with any extensions enabled. | ||||||
2338 | if (isIncompatibleTypedef(Old, New)) | ||||||
2339 | return; | ||||||
2340 | |||||||
2341 | // The types match. Link up the redeclaration chain and merge attributes if | ||||||
2342 | // the old declaration was a typedef. | ||||||
2343 | if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { | ||||||
2344 | New->setPreviousDecl(Typedef); | ||||||
2345 | mergeDeclAttributes(New, Old); | ||||||
2346 | } | ||||||
2347 | |||||||
2348 | if (getLangOpts().MicrosoftExt) | ||||||
2349 | return; | ||||||
2350 | |||||||
2351 | if (getLangOpts().CPlusPlus) { | ||||||
2352 | // C++ [dcl.typedef]p2: | ||||||
2353 | // In a given non-class scope, a typedef specifier can be used to | ||||||
2354 | // redefine the name of any type declared in that scope to refer | ||||||
2355 | // to the type to which it already refers. | ||||||
2356 | if (!isa<CXXRecordDecl>(CurContext)) | ||||||
2357 | return; | ||||||
2358 | |||||||
2359 | // C++0x [dcl.typedef]p4: | ||||||
2360 | // In a given class scope, a typedef specifier can be used to redefine | ||||||
2361 | // any class-name declared in that scope that is not also a typedef-name | ||||||
2362 | // to refer to the type to which it already refers. | ||||||
2363 | // | ||||||
2364 | // This wording came in via DR424, which was a correction to the | ||||||
2365 | // wording in DR56, which accidentally banned code like: | ||||||
2366 | // | ||||||
2367 | // struct S { | ||||||
2368 | // typedef struct A { } A; | ||||||
2369 | // }; | ||||||
2370 | // | ||||||
2371 | // in the C++03 standard. We implement the C++0x semantics, which | ||||||
2372 | // allow the above but disallow | ||||||
2373 | // | ||||||
2374 | // struct S { | ||||||
2375 | // typedef int I; | ||||||
2376 | // typedef int I; | ||||||
2377 | // }; | ||||||
2378 | // | ||||||
2379 | // since that was the intent of DR56. | ||||||
2380 | if (!isa<TypedefNameDecl>(Old)) | ||||||
2381 | return; | ||||||
2382 | |||||||
2383 | Diag(New->getLocation(), diag::err_redefinition) | ||||||
2384 | << New->getDeclName(); | ||||||
2385 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2386 | return New->setInvalidDecl(); | ||||||
2387 | } | ||||||
2388 | |||||||
2389 | // Modules always permit redefinition of typedefs, as does C11. | ||||||
2390 | if (getLangOpts().Modules || getLangOpts().C11) | ||||||
2391 | return; | ||||||
2392 | |||||||
2393 | // If we have a redefinition of a typedef in C, emit a warning. This warning | ||||||
2394 | // is normally mapped to an error, but can be controlled with | ||||||
2395 | // -Wtypedef-redefinition. If either the original or the redefinition is | ||||||
2396 | // in a system header, don't emit this for compatibility with GCC. | ||||||
2397 | if (getDiagnostics().getSuppressSystemWarnings() && | ||||||
2398 | // Some standard types are defined implicitly in Clang (e.g. OpenCL). | ||||||
2399 | (Old->isImplicit() || | ||||||
2400 | Context.getSourceManager().isInSystemHeader(Old->getLocation()) || | ||||||
2401 | Context.getSourceManager().isInSystemHeader(New->getLocation()))) | ||||||
2402 | return; | ||||||
2403 | |||||||
2404 | Diag(New->getLocation(), diag::ext_redefinition_of_typedef) | ||||||
2405 | << New->getDeclName(); | ||||||
2406 | notePreviousDefinition(Old, New->getLocation()); | ||||||
2407 | } | ||||||
2408 | |||||||
2409 | /// DeclhasAttr - returns true if decl Declaration already has the target | ||||||
2410 | /// attribute. | ||||||
2411 | static bool DeclHasAttr(const Decl *D, const Attr *A) { | ||||||
2412 | const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); | ||||||
2413 | const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); | ||||||
2414 | for (const auto *i : D->attrs()) | ||||||
2415 | if (i->getKind() == A->getKind()) { | ||||||
2416 | if (Ann) { | ||||||
2417 | if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) | ||||||
2418 | return true; | ||||||
2419 | continue; | ||||||
2420 | } | ||||||
2421 | // FIXME: Don't hardcode this check | ||||||
2422 | if (OA && isa<OwnershipAttr>(i)) | ||||||
2423 | return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); | ||||||
2424 | return true; | ||||||
2425 | } | ||||||
2426 | |||||||
2427 | return false; | ||||||
2428 | } | ||||||
2429 | |||||||
2430 | static bool isAttributeTargetADefinition(Decl *D) { | ||||||
2431 | if (VarDecl *VD = dyn_cast<VarDecl>(D)) | ||||||
2432 | return VD->isThisDeclarationADefinition(); | ||||||
2433 | if (TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||||
2434 | return TD->isCompleteDefinition() || TD->isBeingDefined(); | ||||||
2435 | return true; | ||||||
2436 | } | ||||||
2437 | |||||||
2438 | /// Merge alignment attributes from \p Old to \p New, taking into account the | ||||||
2439 | /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. | ||||||
2440 | /// | ||||||
2441 | /// \return \c true if any attributes were added to \p New. | ||||||
2442 | static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { | ||||||
2443 | // Look for alignas attributes on Old, and pick out whichever attribute | ||||||
2444 | // specifies the strictest alignment requirement. | ||||||
2445 | AlignedAttr *OldAlignasAttr = nullptr; | ||||||
2446 | AlignedAttr *OldStrictestAlignAttr = nullptr; | ||||||
2447 | unsigned OldAlign = 0; | ||||||
2448 | for (auto *I : Old->specific_attrs<AlignedAttr>()) { | ||||||
2449 | // FIXME: We have no way of representing inherited dependent alignments | ||||||
2450 | // in a case like: | ||||||
2451 | // template<int A, int B> struct alignas(A) X; | ||||||
2452 | // template<int A, int B> struct alignas(B) X {}; | ||||||
2453 | // For now, we just ignore any alignas attributes which are not on the | ||||||
2454 | // definition in such a case. | ||||||
2455 | if (I->isAlignmentDependent()) | ||||||
2456 | return false; | ||||||
2457 | |||||||
2458 | if (I->isAlignas()) | ||||||
2459 | OldAlignasAttr = I; | ||||||
2460 | |||||||
2461 | unsigned Align = I->getAlignment(S.Context); | ||||||
2462 | if (Align > OldAlign) { | ||||||
2463 | OldAlign = Align; | ||||||
2464 | OldStrictestAlignAttr = I; | ||||||
2465 | } | ||||||
2466 | } | ||||||
2467 | |||||||
2468 | // Look for alignas attributes on New. | ||||||
2469 | AlignedAttr *NewAlignasAttr = nullptr; | ||||||
2470 | unsigned NewAlign = 0; | ||||||
2471 | for (auto *I : New->specific_attrs<AlignedAttr>()) { | ||||||
2472 | if (I->isAlignmentDependent()) | ||||||
2473 | return false; | ||||||
2474 | |||||||
2475 | if (I->isAlignas()) | ||||||
2476 | NewAlignasAttr = I; | ||||||
2477 | |||||||
2478 | unsigned Align = I->getAlignment(S.Context); | ||||||
2479 | if (Align > NewAlign) | ||||||
2480 | NewAlign = Align; | ||||||
2481 | } | ||||||
2482 | |||||||
2483 | if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { | ||||||
2484 | // Both declarations have 'alignas' attributes. We require them to match. | ||||||
2485 | // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but | ||||||
2486 | // fall short. (If two declarations both have alignas, they must both match | ||||||
2487 | // every definition, and so must match each other if there is a definition.) | ||||||
2488 | |||||||
2489 | // If either declaration only contains 'alignas(0)' specifiers, then it | ||||||
2490 | // specifies the natural alignment for the type. | ||||||
2491 | if (OldAlign == 0 || NewAlign == 0) { | ||||||
2492 | QualType Ty; | ||||||
2493 | if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) | ||||||
2494 | Ty = VD->getType(); | ||||||
2495 | else | ||||||
2496 | Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); | ||||||
2497 | |||||||
2498 | if (OldAlign == 0) | ||||||
2499 | OldAlign = S.Context.getTypeAlign(Ty); | ||||||
2500 | if (NewAlign == 0) | ||||||
2501 | NewAlign = S.Context.getTypeAlign(Ty); | ||||||
2502 | } | ||||||
2503 | |||||||
2504 | if (OldAlign != NewAlign) { | ||||||
2505 | S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) | ||||||
2506 | << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() | ||||||
2507 | << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); | ||||||
2508 | S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); | ||||||
2509 | } | ||||||
2510 | } | ||||||
2511 | |||||||
2512 | if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { | ||||||
2513 | // C++11 [dcl.align]p6: | ||||||
2514 | // if any declaration of an entity has an alignment-specifier, | ||||||
2515 | // every defining declaration of that entity shall specify an | ||||||
2516 | // equivalent alignment. | ||||||
2517 | // C11 6.7.5/7: | ||||||
2518 | // If the definition of an object does not have an alignment | ||||||
2519 | // specifier, any other declaration of that object shall also | ||||||
2520 | // have no alignment specifier. | ||||||
2521 | S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) | ||||||
2522 | << OldAlignasAttr; | ||||||
2523 | S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) | ||||||
2524 | << OldAlignasAttr; | ||||||
2525 | } | ||||||
2526 | |||||||
2527 | bool AnyAdded = false; | ||||||
2528 | |||||||
2529 | // Ensure we have an attribute representing the strictest alignment. | ||||||
2530 | if (OldAlign > NewAlign) { | ||||||
2531 | AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); | ||||||
2532 | Clone->setInherited(true); | ||||||
2533 | New->addAttr(Clone); | ||||||
2534 | AnyAdded = true; | ||||||
2535 | } | ||||||
2536 | |||||||
2537 | // Ensure we have an alignas attribute if the old declaration had one. | ||||||
2538 | if (OldAlignasAttr && !NewAlignasAttr && | ||||||
2539 | !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { | ||||||
2540 | AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); | ||||||
2541 | Clone->setInherited(true); | ||||||
2542 | New->addAttr(Clone); | ||||||
2543 | AnyAdded = true; | ||||||
2544 | } | ||||||
2545 | |||||||
2546 | return AnyAdded; | ||||||
2547 | } | ||||||
2548 | |||||||
2549 | static bool mergeDeclAttribute(Sema &S, NamedDecl *D, | ||||||
2550 | const InheritableAttr *Attr, | ||||||
2551 | Sema::AvailabilityMergeKind AMK) { | ||||||
2552 | // This function copies an attribute Attr from a previous declaration to the | ||||||
2553 | // new declaration D if the new declaration doesn't itself have that attribute | ||||||
2554 | // yet or if that attribute allows duplicates. | ||||||
2555 | // If you're adding a new attribute that requires logic different from | ||||||
2556 | // "use explicit attribute on decl if present, else use attribute from | ||||||
2557 | // previous decl", for example if the attribute needs to be consistent | ||||||
2558 | // between redeclarations, you need to call a custom merge function here. | ||||||
2559 | InheritableAttr *NewAttr = nullptr; | ||||||
2560 | if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) | ||||||
2561 | NewAttr = S.mergeAvailabilityAttr( | ||||||
2562 | D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), | ||||||
2563 | AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), | ||||||
2564 | AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, | ||||||
2565 | AA->getPriority()); | ||||||
2566 | else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) | ||||||
2567 | NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||||
2568 | else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) | ||||||
2569 | NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); | ||||||
2570 | else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) | ||||||
2571 | NewAttr = S.mergeDLLImportAttr(D, *ImportA); | ||||||
2572 | else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) | ||||||
2573 | NewAttr = S.mergeDLLExportAttr(D, *ExportA); | ||||||
2574 | else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) | ||||||
2575 | NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), | ||||||
2576 | FA->getFirstArg()); | ||||||
2577 | else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) | ||||||
2578 | NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); | ||||||
2579 | else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) | ||||||
2580 | NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); | ||||||
2581 | else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) | ||||||
2582 | NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), | ||||||
2583 | IA->getInheritanceModel()); | ||||||
2584 | else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) | ||||||
2585 | NewAttr = S.mergeAlwaysInlineAttr(D, *AA, | ||||||
2586 | &S.Context.Idents.get(AA->getSpelling())); | ||||||
2587 | else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && | ||||||
2588 | (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || | ||||||
2589 | isa<CUDAGlobalAttr>(Attr))) { | ||||||
2590 | // CUDA target attributes are part of function signature for | ||||||
2591 | // overloading purposes and must not be merged. | ||||||
2592 | return false; | ||||||
2593 | } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) | ||||||
2594 | NewAttr = S.mergeMinSizeAttr(D, *MA); | ||||||
2595 | else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr)) | ||||||
2596 | NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName()); | ||||||
2597 | else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) | ||||||
2598 | NewAttr = S.mergeOptimizeNoneAttr(D, *OA); | ||||||
2599 | else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) | ||||||
2600 | NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); | ||||||
2601 | else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) | ||||||
2602 | NewAttr = S.mergeCommonAttr(D, *CommonA); | ||||||
2603 | else if (isa<AlignedAttr>(Attr)) | ||||||
2604 | // AlignedAttrs are handled separately, because we need to handle all | ||||||
2605 | // such attributes on a declaration at the same time. | ||||||
2606 | NewAttr = nullptr; | ||||||
2607 | else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && | ||||||
2608 | (AMK == Sema::AMK_Override || | ||||||
2609 | AMK == Sema::AMK_ProtocolImplementation)) | ||||||
2610 | NewAttr = nullptr; | ||||||
2611 | else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) | ||||||
2612 | NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl()); | ||||||
2613 | else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) | ||||||
2614 | NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); | ||||||
2615 | else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) | ||||||
2616 | NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); | ||||||
2617 | else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr)) | ||||||
2618 | NewAttr = S.mergeImportModuleAttr(D, *IMA); | ||||||
2619 | else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr)) | ||||||
2620 | NewAttr = S.mergeImportNameAttr(D, *INA); | ||||||
2621 | else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) | ||||||
2622 | NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); | ||||||
2623 | |||||||
2624 | if (NewAttr) { | ||||||
2625 | NewAttr->setInherited(true); | ||||||
2626 | D->addAttr(NewAttr); | ||||||
2627 | if (isa<MSInheritanceAttr>(NewAttr)) | ||||||
2628 | S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); | ||||||
2629 | return true; | ||||||
2630 | } | ||||||
2631 | |||||||
2632 | return false; | ||||||
2633 | } | ||||||
2634 | |||||||
2635 | static const NamedDecl *getDefinition(const Decl *D) { | ||||||
2636 | if (const TagDecl *TD = dyn_cast<TagDecl>(D)) | ||||||
2637 | return TD->getDefinition(); | ||||||
2638 | if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { | ||||||
2639 | const VarDecl *Def = VD->getDefinition(); | ||||||
2640 | if (Def) | ||||||
2641 | return Def; | ||||||
2642 | return VD->getActingDefinition(); | ||||||
2643 | } | ||||||
2644 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) | ||||||
2645 | return FD->getDefinition(); | ||||||
2646 | return nullptr; | ||||||
2647 | } | ||||||
2648 | |||||||
2649 | static bool hasAttribute(const Decl *D, attr::Kind Kind) { | ||||||
2650 | for (const auto *Attribute : D->attrs()) | ||||||
2651 | if (Attribute->getKind() == Kind) | ||||||
2652 | return true; | ||||||
2653 | return false; | ||||||
2654 | } | ||||||
2655 | |||||||
2656 | /// checkNewAttributesAfterDef - If we already have a definition, check that | ||||||
2657 | /// there are no new attributes in this declaration. | ||||||
2658 | static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { | ||||||
2659 | if (!New->hasAttrs()) | ||||||
2660 | return; | ||||||
2661 | |||||||
2662 | const NamedDecl *Def = getDefinition(Old); | ||||||
2663 | if (!Def || Def == New) | ||||||
2664 | return; | ||||||
2665 | |||||||
2666 | AttrVec &NewAttributes = New->getAttrs(); | ||||||
2667 | for (unsigned I = 0, E = NewAttributes.size(); I != E;) { | ||||||
2668 | const Attr *NewAttribute = NewAttributes[I]; | ||||||
2669 | |||||||
2670 | if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { | ||||||
2671 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { | ||||||
2672 | Sema::SkipBodyInfo SkipBody; | ||||||
2673 | S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); | ||||||
2674 | |||||||
2675 | // If we're skipping this definition, drop the "alias" attribute. | ||||||
2676 | if (SkipBody.ShouldSkip) { | ||||||
2677 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2678 | --E; | ||||||
2679 | continue; | ||||||
2680 | } | ||||||
2681 | } else { | ||||||
2682 | VarDecl *VD = cast<VarDecl>(New); | ||||||
2683 | unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == | ||||||
2684 | VarDecl::TentativeDefinition | ||||||
2685 | ? diag::err_alias_after_tentative | ||||||
2686 | : diag::err_redefinition; | ||||||
2687 | S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); | ||||||
2688 | if (Diag == diag::err_redefinition) | ||||||
2689 | S.notePreviousDefinition(Def, VD->getLocation()); | ||||||
2690 | else | ||||||
2691 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
2692 | VD->setInvalidDecl(); | ||||||
2693 | } | ||||||
2694 | ++I; | ||||||
2695 | continue; | ||||||
2696 | } | ||||||
2697 | |||||||
2698 | if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { | ||||||
2699 | // Tentative definitions are only interesting for the alias check above. | ||||||
2700 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { | ||||||
2701 | ++I; | ||||||
2702 | continue; | ||||||
2703 | } | ||||||
2704 | } | ||||||
2705 | |||||||
2706 | if (hasAttribute(Def, NewAttribute->getKind())) { | ||||||
2707 | ++I; | ||||||
2708 | continue; // regular attr merging will take care of validating this. | ||||||
2709 | } | ||||||
2710 | |||||||
2711 | if (isa<C11NoReturnAttr>(NewAttribute)) { | ||||||
2712 | // C's _Noreturn is allowed to be added to a function after it is defined. | ||||||
2713 | ++I; | ||||||
2714 | continue; | ||||||
2715 | } else if (isa<UuidAttr>(NewAttribute)) { | ||||||
2716 | // msvc will allow a subsequent definition to add an uuid to a class | ||||||
2717 | ++I; | ||||||
2718 | continue; | ||||||
2719 | } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { | ||||||
2720 | if (AA->isAlignas()) { | ||||||
2721 | // C++11 [dcl.align]p6: | ||||||
2722 | // if any declaration of an entity has an alignment-specifier, | ||||||
2723 | // every defining declaration of that entity shall specify an | ||||||
2724 | // equivalent alignment. | ||||||
2725 | // C11 6.7.5/7: | ||||||
2726 | // If the definition of an object does not have an alignment | ||||||
2727 | // specifier, any other declaration of that object shall also | ||||||
2728 | // have no alignment specifier. | ||||||
2729 | S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) | ||||||
2730 | << AA; | ||||||
2731 | S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) | ||||||
2732 | << AA; | ||||||
2733 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2734 | --E; | ||||||
2735 | continue; | ||||||
2736 | } | ||||||
2737 | } else if (isa<LoaderUninitializedAttr>(NewAttribute)) { | ||||||
2738 | // If there is a C definition followed by a redeclaration with this | ||||||
2739 | // attribute then there are two different definitions. In C++, prefer the | ||||||
2740 | // standard diagnostics. | ||||||
2741 | if (!S.getLangOpts().CPlusPlus) { | ||||||
2742 | S.Diag(NewAttribute->getLocation(), | ||||||
2743 | diag::err_loader_uninitialized_redeclaration); | ||||||
2744 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
2745 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2746 | --E; | ||||||
2747 | continue; | ||||||
2748 | } | ||||||
2749 | } else if (isa<SelectAnyAttr>(NewAttribute) && | ||||||
2750 | cast<VarDecl>(New)->isInline() && | ||||||
2751 | !cast<VarDecl>(New)->isInlineSpecified()) { | ||||||
2752 | // Don't warn about applying selectany to implicitly inline variables. | ||||||
2753 | // Older compilers and language modes would require the use of selectany | ||||||
2754 | // to make such variables inline, and it would have no effect if we | ||||||
2755 | // honored it. | ||||||
2756 | ++I; | ||||||
2757 | continue; | ||||||
2758 | } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) { | ||||||
2759 | // We allow to add OMP[Begin]DeclareVariantAttr to be added to | ||||||
2760 | // declarations after defintions. | ||||||
2761 | ++I; | ||||||
2762 | continue; | ||||||
2763 | } | ||||||
2764 | |||||||
2765 | S.Diag(NewAttribute->getLocation(), | ||||||
2766 | diag::warn_attribute_precede_definition); | ||||||
2767 | S.Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
2768 | NewAttributes.erase(NewAttributes.begin() + I); | ||||||
2769 | --E; | ||||||
2770 | } | ||||||
2771 | } | ||||||
2772 | |||||||
2773 | static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, | ||||||
2774 | const ConstInitAttr *CIAttr, | ||||||
2775 | bool AttrBeforeInit) { | ||||||
2776 | SourceLocation InsertLoc = InitDecl->getInnerLocStart(); | ||||||
2777 | |||||||
2778 | // Figure out a good way to write this specifier on the old declaration. | ||||||
2779 | // FIXME: We should just use the spelling of CIAttr, but we don't preserve | ||||||
2780 | // enough of the attribute list spelling information to extract that without | ||||||
2781 | // heroics. | ||||||
2782 | std::string SuitableSpelling; | ||||||
2783 | if (S.getLangOpts().CPlusPlus20) | ||||||
2784 | SuitableSpelling = std::string( | ||||||
2785 | S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); | ||||||
2786 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||||
2787 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( | ||||||
2788 | InsertLoc, {tok::l_square, tok::l_square, | ||||||
2789 | S.PP.getIdentifierInfo("clang"), tok::coloncolon, | ||||||
2790 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||||
2791 | tok::r_square, tok::r_square})); | ||||||
2792 | if (SuitableSpelling.empty()) | ||||||
2793 | SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( | ||||||
2794 | InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, | ||||||
2795 | S.PP.getIdentifierInfo("require_constant_initialization"), | ||||||
2796 | tok::r_paren, tok::r_paren})); | ||||||
2797 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20) | ||||||
2798 | SuitableSpelling = "constinit"; | ||||||
2799 | if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) | ||||||
2800 | SuitableSpelling = "[[clang::require_constant_initialization]]"; | ||||||
2801 | if (SuitableSpelling.empty()) | ||||||
2802 | SuitableSpelling = "__attribute__((require_constant_initialization))"; | ||||||
2803 | SuitableSpelling += " "; | ||||||
2804 | |||||||
2805 | if (AttrBeforeInit) { | ||||||
2806 | // extern constinit int a; | ||||||
2807 | // int a = 0; // error (missing 'constinit'), accepted as extension | ||||||
2808 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 2808, __PRETTY_FUNCTION__)); | ||||||
2809 | S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) | ||||||
2810 | << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||||
2811 | S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); | ||||||
2812 | } else { | ||||||
2813 | // int a = 0; | ||||||
2814 | // constinit extern int a; // error (missing 'constinit') | ||||||
2815 | S.Diag(CIAttr->getLocation(), | ||||||
2816 | CIAttr->isConstinit() ? diag::err_constinit_added_too_late | ||||||
2817 | : diag::warn_require_const_init_added_too_late) | ||||||
2818 | << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); | ||||||
2819 | S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) | ||||||
2820 | << CIAttr->isConstinit() | ||||||
2821 | << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); | ||||||
2822 | } | ||||||
2823 | } | ||||||
2824 | |||||||
2825 | /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. | ||||||
2826 | void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, | ||||||
2827 | AvailabilityMergeKind AMK) { | ||||||
2828 | if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { | ||||||
2829 | UsedAttr *NewAttr = OldAttr->clone(Context); | ||||||
2830 | NewAttr->setInherited(true); | ||||||
2831 | New->addAttr(NewAttr); | ||||||
2832 | } | ||||||
2833 | |||||||
2834 | if (!Old->hasAttrs() && !New->hasAttrs()) | ||||||
2835 | return; | ||||||
2836 | |||||||
2837 | // [dcl.constinit]p1: | ||||||
2838 | // If the [constinit] specifier is applied to any declaration of a | ||||||
2839 | // variable, it shall be applied to the initializing declaration. | ||||||
2840 | const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); | ||||||
2841 | const auto *NewConstInit = New->getAttr<ConstInitAttr>(); | ||||||
2842 | if (bool(OldConstInit) != bool(NewConstInit)) { | ||||||
2843 | const auto *OldVD = cast<VarDecl>(Old); | ||||||
2844 | auto *NewVD = cast<VarDecl>(New); | ||||||
2845 | |||||||
2846 | // Find the initializing declaration. Note that we might not have linked | ||||||
2847 | // the new declaration into the redeclaration chain yet. | ||||||
2848 | const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); | ||||||
2849 | if (!InitDecl && | ||||||
2850 | (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) | ||||||
2851 | InitDecl = NewVD; | ||||||
2852 | |||||||
2853 | if (InitDecl == NewVD) { | ||||||
2854 | // This is the initializing declaration. If it would inherit 'constinit', | ||||||
2855 | // that's ill-formed. (Note that we do not apply this to the attribute | ||||||
2856 | // form). | ||||||
2857 | if (OldConstInit && OldConstInit->isConstinit()) | ||||||
2858 | diagnoseMissingConstinit(*this, NewVD, OldConstInit, | ||||||
2859 | /*AttrBeforeInit=*/true); | ||||||
2860 | } else if (NewConstInit) { | ||||||
2861 | // This is the first time we've been told that this declaration should | ||||||
2862 | // have a constant initializer. If we already saw the initializing | ||||||
2863 | // declaration, this is too late. | ||||||
2864 | if (InitDecl && InitDecl != NewVD) { | ||||||
2865 | diagnoseMissingConstinit(*this, InitDecl, NewConstInit, | ||||||
2866 | /*AttrBeforeInit=*/false); | ||||||
2867 | NewVD->dropAttr<ConstInitAttr>(); | ||||||
2868 | } | ||||||
2869 | } | ||||||
2870 | } | ||||||
2871 | |||||||
2872 | // Attributes declared post-definition are currently ignored. | ||||||
2873 | checkNewAttributesAfterDef(*this, New, Old); | ||||||
2874 | |||||||
2875 | if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { | ||||||
2876 | if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { | ||||||
2877 | if (!OldA->isEquivalent(NewA)) { | ||||||
2878 | // This redeclaration changes __asm__ label. | ||||||
2879 | Diag(New->getLocation(), diag::err_different_asm_label); | ||||||
2880 | Diag(OldA->getLocation(), diag::note_previous_declaration); | ||||||
2881 | } | ||||||
2882 | } else if (Old->isUsed()) { | ||||||
2883 | // This redeclaration adds an __asm__ label to a declaration that has | ||||||
2884 | // already been ODR-used. | ||||||
2885 | Diag(New->getLocation(), diag::err_late_asm_label_name) | ||||||
2886 | << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); | ||||||
2887 | } | ||||||
2888 | } | ||||||
2889 | |||||||
2890 | // Re-declaration cannot add abi_tag's. | ||||||
2891 | if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { | ||||||
2892 | if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { | ||||||
2893 | for (const auto &NewTag : NewAbiTagAttr->tags()) { | ||||||
2894 | if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), | ||||||
2895 | NewTag) == OldAbiTagAttr->tags_end()) { | ||||||
2896 | Diag(NewAbiTagAttr->getLocation(), | ||||||
2897 | diag::err_new_abi_tag_on_redeclaration) | ||||||
2898 | << NewTag; | ||||||
2899 | Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); | ||||||
2900 | } | ||||||
2901 | } | ||||||
2902 | } else { | ||||||
2903 | Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); | ||||||
2904 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2905 | } | ||||||
2906 | } | ||||||
2907 | |||||||
2908 | // This redeclaration adds a section attribute. | ||||||
2909 | if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { | ||||||
2910 | if (auto *VD = dyn_cast<VarDecl>(New)) { | ||||||
2911 | if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { | ||||||
2912 | Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); | ||||||
2913 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2914 | } | ||||||
2915 | } | ||||||
2916 | } | ||||||
2917 | |||||||
2918 | // Redeclaration adds code-seg attribute. | ||||||
2919 | const auto *NewCSA = New->getAttr<CodeSegAttr>(); | ||||||
2920 | if (NewCSA && !Old->hasAttr<CodeSegAttr>() && | ||||||
2921 | !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { | ||||||
2922 | Diag(New->getLocation(), diag::warn_mismatched_section) | ||||||
2923 | << 0 /*codeseg*/; | ||||||
2924 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
2925 | } | ||||||
2926 | |||||||
2927 | if (!Old->hasAttrs()) | ||||||
2928 | return; | ||||||
2929 | |||||||
2930 | bool foundAny = New->hasAttrs(); | ||||||
2931 | |||||||
2932 | // Ensure that any moving of objects within the allocated map is done before | ||||||
2933 | // we process them. | ||||||
2934 | if (!foundAny) New->setAttrs(AttrVec()); | ||||||
2935 | |||||||
2936 | for (auto *I : Old->specific_attrs<InheritableAttr>()) { | ||||||
2937 | // Ignore deprecated/unavailable/availability attributes if requested. | ||||||
2938 | AvailabilityMergeKind LocalAMK = AMK_None; | ||||||
2939 | if (isa<DeprecatedAttr>(I) || | ||||||
2940 | isa<UnavailableAttr>(I) || | ||||||
2941 | isa<AvailabilityAttr>(I)) { | ||||||
2942 | switch (AMK) { | ||||||
2943 | case AMK_None: | ||||||
2944 | continue; | ||||||
2945 | |||||||
2946 | case AMK_Redeclaration: | ||||||
2947 | case AMK_Override: | ||||||
2948 | case AMK_ProtocolImplementation: | ||||||
2949 | LocalAMK = AMK; | ||||||
2950 | break; | ||||||
2951 | } | ||||||
2952 | } | ||||||
2953 | |||||||
2954 | // Already handled. | ||||||
2955 | if (isa<UsedAttr>(I)) | ||||||
2956 | continue; | ||||||
2957 | |||||||
2958 | if (mergeDeclAttribute(*this, New, I, LocalAMK)) | ||||||
2959 | foundAny = true; | ||||||
2960 | } | ||||||
2961 | |||||||
2962 | if (mergeAlignedAttrs(*this, New, Old)) | ||||||
2963 | foundAny = true; | ||||||
2964 | |||||||
2965 | if (!foundAny) New->dropAttrs(); | ||||||
2966 | } | ||||||
2967 | |||||||
2968 | /// mergeParamDeclAttributes - Copy attributes from the old parameter | ||||||
2969 | /// to the new one. | ||||||
2970 | static void mergeParamDeclAttributes(ParmVarDecl *newDecl, | ||||||
2971 | const ParmVarDecl *oldDecl, | ||||||
2972 | Sema &S) { | ||||||
2973 | // C++11 [dcl.attr.depend]p2: | ||||||
2974 | // The first declaration of a function shall specify the | ||||||
2975 | // carries_dependency attribute for its declarator-id if any declaration | ||||||
2976 | // of the function specifies the carries_dependency attribute. | ||||||
2977 | const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); | ||||||
2978 | if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { | ||||||
2979 | S.Diag(CDA->getLocation(), | ||||||
2980 | diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; | ||||||
2981 | // Find the first declaration of the parameter. | ||||||
2982 | // FIXME: Should we build redeclaration chains for function parameters? | ||||||
2983 | const FunctionDecl *FirstFD = | ||||||
2984 | cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); | ||||||
2985 | const ParmVarDecl *FirstVD = | ||||||
2986 | FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); | ||||||
2987 | S.Diag(FirstVD->getLocation(), | ||||||
2988 | diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; | ||||||
2989 | } | ||||||
2990 | |||||||
2991 | if (!oldDecl->hasAttrs()) | ||||||
2992 | return; | ||||||
2993 | |||||||
2994 | bool foundAny = newDecl->hasAttrs(); | ||||||
2995 | |||||||
2996 | // Ensure that any moving of objects within the allocated map is | ||||||
2997 | // done before we process them. | ||||||
2998 | if (!foundAny) newDecl->setAttrs(AttrVec()); | ||||||
2999 | |||||||
3000 | for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { | ||||||
3001 | if (!DeclHasAttr(newDecl, I)) { | ||||||
3002 | InheritableAttr *newAttr = | ||||||
3003 | cast<InheritableParamAttr>(I->clone(S.Context)); | ||||||
3004 | newAttr->setInherited(true); | ||||||
3005 | newDecl->addAttr(newAttr); | ||||||
3006 | foundAny = true; | ||||||
3007 | } | ||||||
3008 | } | ||||||
3009 | |||||||
3010 | if (!foundAny) newDecl->dropAttrs(); | ||||||
3011 | } | ||||||
3012 | |||||||
3013 | static void mergeParamDeclTypes(ParmVarDecl *NewParam, | ||||||
3014 | const ParmVarDecl *OldParam, | ||||||
3015 | Sema &S) { | ||||||
3016 | if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { | ||||||
3017 | if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { | ||||||
3018 | if (*Oldnullability != *Newnullability) { | ||||||
3019 | S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) | ||||||
3020 | << DiagNullabilityKind( | ||||||
3021 | *Newnullability, | ||||||
3022 | ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||||
3023 | != 0)) | ||||||
3024 | << DiagNullabilityKind( | ||||||
3025 | *Oldnullability, | ||||||
3026 | ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) | ||||||
3027 | != 0)); | ||||||
3028 | S.Diag(OldParam->getLocation(), diag::note_previous_declaration); | ||||||
3029 | } | ||||||
3030 | } else { | ||||||
3031 | QualType NewT = NewParam->getType(); | ||||||
3032 | NewT = S.Context.getAttributedType( | ||||||
3033 | AttributedType::getNullabilityAttrKind(*Oldnullability), | ||||||
3034 | NewT, NewT); | ||||||
3035 | NewParam->setType(NewT); | ||||||
3036 | } | ||||||
3037 | } | ||||||
3038 | } | ||||||
3039 | |||||||
3040 | namespace { | ||||||
3041 | |||||||
3042 | /// Used in MergeFunctionDecl to keep track of function parameters in | ||||||
3043 | /// C. | ||||||
3044 | struct GNUCompatibleParamWarning { | ||||||
3045 | ParmVarDecl *OldParm; | ||||||
3046 | ParmVarDecl *NewParm; | ||||||
3047 | QualType PromotedType; | ||||||
3048 | }; | ||||||
3049 | |||||||
3050 | } // end anonymous namespace | ||||||
3051 | |||||||
3052 | // Determine whether the previous declaration was a definition, implicit | ||||||
3053 | // declaration, or a declaration. | ||||||
3054 | template <typename T> | ||||||
3055 | static std::pair<diag::kind, SourceLocation> | ||||||
3056 | getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { | ||||||
3057 | diag::kind PrevDiag; | ||||||
3058 | SourceLocation OldLocation = Old->getLocation(); | ||||||
3059 | if (Old->isThisDeclarationADefinition()) | ||||||
3060 | PrevDiag = diag::note_previous_definition; | ||||||
3061 | else if (Old->isImplicit()) { | ||||||
3062 | PrevDiag = diag::note_previous_implicit_declaration; | ||||||
3063 | if (OldLocation.isInvalid()) | ||||||
3064 | OldLocation = New->getLocation(); | ||||||
3065 | } else | ||||||
3066 | PrevDiag = diag::note_previous_declaration; | ||||||
3067 | return std::make_pair(PrevDiag, OldLocation); | ||||||
3068 | } | ||||||
3069 | |||||||
3070 | /// canRedefineFunction - checks if a function can be redefined. Currently, | ||||||
3071 | /// only extern inline functions can be redefined, and even then only in | ||||||
3072 | /// GNU89 mode. | ||||||
3073 | static bool canRedefineFunction(const FunctionDecl *FD, | ||||||
3074 | const LangOptions& LangOpts) { | ||||||
3075 | return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && | ||||||
3076 | !LangOpts.CPlusPlus && | ||||||
3077 | FD->isInlineSpecified() && | ||||||
3078 | FD->getStorageClass() == SC_Extern); | ||||||
3079 | } | ||||||
3080 | |||||||
3081 | const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { | ||||||
3082 | const AttributedType *AT = T->getAs<AttributedType>(); | ||||||
3083 | while (AT && !AT->isCallingConv()) | ||||||
3084 | AT = AT->getModifiedType()->getAs<AttributedType>(); | ||||||
3085 | return AT; | ||||||
3086 | } | ||||||
3087 | |||||||
3088 | template <typename T> | ||||||
3089 | static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { | ||||||
3090 | const DeclContext *DC = Old->getDeclContext(); | ||||||
3091 | if (DC->isRecord()) | ||||||
3092 | return false; | ||||||
3093 | |||||||
3094 | LanguageLinkage OldLinkage = Old->getLanguageLinkage(); | ||||||
3095 | if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) | ||||||
3096 | return true; | ||||||
3097 | if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) | ||||||
3098 | return true; | ||||||
3099 | return false; | ||||||
3100 | } | ||||||
3101 | |||||||
3102 | template<typename T> static bool isExternC(T *D) { return D->isExternC(); } | ||||||
3103 | static bool isExternC(VarTemplateDecl *) { return false; } | ||||||
3104 | |||||||
3105 | /// Check whether a redeclaration of an entity introduced by a | ||||||
3106 | /// using-declaration is valid, given that we know it's not an overload | ||||||
3107 | /// (nor a hidden tag declaration). | ||||||
3108 | template<typename ExpectedDecl> | ||||||
3109 | static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, | ||||||
3110 | ExpectedDecl *New) { | ||||||
3111 | // C++11 [basic.scope.declarative]p4: | ||||||
3112 | // Given a set of declarations in a single declarative region, each of | ||||||
3113 | // which specifies the same unqualified name, | ||||||
3114 | // -- they shall all refer to the same entity, or all refer to functions | ||||||
3115 | // and function templates; or | ||||||
3116 | // -- exactly one declaration shall declare a class name or enumeration | ||||||
3117 | // name that is not a typedef name and the other declarations shall all | ||||||
3118 | // refer to the same variable or enumerator, or all refer to functions | ||||||
3119 | // and function templates; in this case the class name or enumeration | ||||||
3120 | // name is hidden (3.3.10). | ||||||
3121 | |||||||
3122 | // C++11 [namespace.udecl]p14: | ||||||
3123 | // If a function declaration in namespace scope or block scope has the | ||||||
3124 | // same name and the same parameter-type-list as a function introduced | ||||||
3125 | // by a using-declaration, and the declarations do not declare the same | ||||||
3126 | // function, the program is ill-formed. | ||||||
3127 | |||||||
3128 | auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); | ||||||
3129 | if (Old && | ||||||
3130 | !Old->getDeclContext()->getRedeclContext()->Equals( | ||||||
3131 | New->getDeclContext()->getRedeclContext()) && | ||||||
3132 | !(isExternC(Old) && isExternC(New))) | ||||||
3133 | Old = nullptr; | ||||||
3134 | |||||||
3135 | if (!Old) { | ||||||
3136 | S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); | ||||||
3137 | S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); | ||||||
3138 | S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; | ||||||
3139 | return true; | ||||||
3140 | } | ||||||
3141 | return false; | ||||||
3142 | } | ||||||
3143 | |||||||
3144 | static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, | ||||||
3145 | const FunctionDecl *B) { | ||||||
3146 | assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast <void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 3146, __PRETTY_FUNCTION__)); | ||||||
3147 | |||||||
3148 | auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { | ||||||
3149 | const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); | ||||||
3150 | const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); | ||||||
3151 | if (AttrA == AttrB) | ||||||
3152 | return true; | ||||||
3153 | return AttrA && AttrB && AttrA->getType() == AttrB->getType() && | ||||||
3154 | AttrA->isDynamic() == AttrB->isDynamic(); | ||||||
3155 | }; | ||||||
3156 | |||||||
3157 | return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); | ||||||
3158 | } | ||||||
3159 | |||||||
3160 | /// If necessary, adjust the semantic declaration context for a qualified | ||||||
3161 | /// declaration to name the correct inline namespace within the qualifier. | ||||||
3162 | static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, | ||||||
3163 | DeclaratorDecl *OldD) { | ||||||
3164 | // The only case where we need to update the DeclContext is when | ||||||
3165 | // redeclaration lookup for a qualified name finds a declaration | ||||||
3166 | // in an inline namespace within the context named by the qualifier: | ||||||
3167 | // | ||||||
3168 | // inline namespace N { int f(); } | ||||||
3169 | // int ::f(); // Sema DC needs adjusting from :: to N::. | ||||||
3170 | // | ||||||
3171 | // For unqualified declarations, the semantic context *can* change | ||||||
3172 | // along the redeclaration chain (for local extern declarations, | ||||||
3173 | // extern "C" declarations, and friend declarations in particular). | ||||||
3174 | if (!NewD->getQualifier()) | ||||||
3175 | return; | ||||||
3176 | |||||||
3177 | // NewD is probably already in the right context. | ||||||
3178 | auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); | ||||||
3179 | auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); | ||||||
3180 | if (NamedDC->Equals(SemaDC)) | ||||||
3181 | return; | ||||||
3182 | |||||||
3183 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 3185, __PRETTY_FUNCTION__)) | ||||||
3184 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 3185, __PRETTY_FUNCTION__)) | ||||||
3185 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 3185, __PRETTY_FUNCTION__)); | ||||||
3186 | |||||||
3187 | auto *LexDC = NewD->getLexicalDeclContext(); | ||||||
3188 | auto FixSemaDC = [=](NamedDecl *D) { | ||||||
3189 | if (!D) | ||||||
3190 | return; | ||||||
3191 | D->setDeclContext(SemaDC); | ||||||
3192 | D->setLexicalDeclContext(LexDC); | ||||||
3193 | }; | ||||||
3194 | |||||||
3195 | FixSemaDC(NewD); | ||||||
3196 | if (auto *FD = dyn_cast<FunctionDecl>(NewD)) | ||||||
3197 | FixSemaDC(FD->getDescribedFunctionTemplate()); | ||||||
3198 | else if (auto *VD = dyn_cast<VarDecl>(NewD)) | ||||||
3199 | FixSemaDC(VD->getDescribedVarTemplate()); | ||||||
3200 | } | ||||||
3201 | |||||||
3202 | /// MergeFunctionDecl - We just parsed a function 'New' from | ||||||
3203 | /// declarator D which has the same name and scope as a previous | ||||||
3204 | /// declaration 'Old'. Figure out how to resolve this situation, | ||||||
3205 | /// merging decls or emitting diagnostics as appropriate. | ||||||
3206 | /// | ||||||
3207 | /// In C++, New and Old must be declarations that are not | ||||||
3208 | /// overloaded. Use IsOverload to determine whether New and Old are | ||||||
3209 | /// overloaded, and to select the Old declaration that New should be | ||||||
3210 | /// merged with. | ||||||
3211 | /// | ||||||
3212 | /// Returns true if there was an error, false otherwise. | ||||||
3213 | bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, | ||||||
3214 | Scope *S, bool MergeTypeWithOld) { | ||||||
3215 | // Verify the old decl was also a function. | ||||||
3216 | FunctionDecl *Old = OldD->getAsFunction(); | ||||||
3217 | if (!Old) { | ||||||
3218 | if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { | ||||||
3219 | if (New->getFriendObjectKind()) { | ||||||
3220 | Diag(New->getLocation(), diag::err_using_decl_friend); | ||||||
3221 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||||
3222 | diag::note_using_decl_target); | ||||||
3223 | Diag(Shadow->getUsingDecl()->getLocation(), | ||||||
3224 | diag::note_using_decl) << 0; | ||||||
3225 | return true; | ||||||
3226 | } | ||||||
3227 | |||||||
3228 | // Check whether the two declarations might declare the same function. | ||||||
3229 | if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) | ||||||
3230 | return true; | ||||||
3231 | OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); | ||||||
3232 | } else { | ||||||
3233 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
3234 | << New->getDeclName(); | ||||||
3235 | notePreviousDefinition(OldD, New->getLocation()); | ||||||
3236 | return true; | ||||||
3237 | } | ||||||
3238 | } | ||||||
3239 | |||||||
3240 | // If the old declaration is invalid, just give up here. | ||||||
3241 | if (Old->isInvalidDecl()) | ||||||
3242 | return true; | ||||||
3243 | |||||||
3244 | // Disallow redeclaration of some builtins. | ||||||
3245 | if (!getASTContext().canBuiltinBeRedeclared(Old)) { | ||||||
3246 | Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); | ||||||
3247 | Diag(Old->getLocation(), diag::note_previous_builtin_declaration) | ||||||
3248 | << Old << Old->getType(); | ||||||
3249 | return true; | ||||||
3250 | } | ||||||
3251 | |||||||
3252 | diag::kind PrevDiag; | ||||||
3253 | SourceLocation OldLocation; | ||||||
3254 | std::tie(PrevDiag, OldLocation) = | ||||||
3255 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
3256 | |||||||
3257 | // Don't complain about this if we're in GNU89 mode and the old function | ||||||
3258 | // is an extern inline function. | ||||||
3259 | // Don't complain about specializations. They are not supposed to have | ||||||
3260 | // storage classes. | ||||||
3261 | if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && | ||||||
3262 | New->getStorageClass() == SC_Static && | ||||||
3263 | Old->hasExternalFormalLinkage() && | ||||||
3264 | !New->getTemplateSpecializationInfo() && | ||||||
3265 | !canRedefineFunction(Old, getLangOpts())) { | ||||||
3266 | if (getLangOpts().MicrosoftExt) { | ||||||
3267 | Diag(New->getLocation(), diag::ext_static_non_static) << New; | ||||||
3268 | Diag(OldLocation, PrevDiag); | ||||||
3269 | } else { | ||||||
3270 | Diag(New->getLocation(), diag::err_static_non_static) << New; | ||||||
3271 | Diag(OldLocation, PrevDiag); | ||||||
3272 | return true; | ||||||
3273 | } | ||||||
3274 | } | ||||||
3275 | |||||||
3276 | if (New->hasAttr<InternalLinkageAttr>() && | ||||||
3277 | !Old->hasAttr<InternalLinkageAttr>()) { | ||||||
3278 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | ||||||
3279 | << New->getDeclName(); | ||||||
3280 | notePreviousDefinition(Old, New->getLocation()); | ||||||
3281 | New->dropAttr<InternalLinkageAttr>(); | ||||||
3282 | } | ||||||
3283 | |||||||
3284 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||||
3285 | return true; | ||||||
3286 | |||||||
3287 | if (!getLangOpts().CPlusPlus) { | ||||||
3288 | bool OldOvl = Old->hasAttr<OverloadableAttr>(); | ||||||
3289 | if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { | ||||||
3290 | Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) | ||||||
3291 | << New << OldOvl; | ||||||
3292 | |||||||
3293 | // Try our best to find a decl that actually has the overloadable | ||||||
3294 | // attribute for the note. In most cases (e.g. programs with only one | ||||||
3295 | // broken declaration/definition), this won't matter. | ||||||
3296 | // | ||||||
3297 | // FIXME: We could do this if we juggled some extra state in | ||||||
3298 | // OverloadableAttr, rather than just removing it. | ||||||
3299 | const Decl *DiagOld = Old; | ||||||
3300 | if (OldOvl) { | ||||||
3301 | auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { | ||||||
3302 | const auto *A = D->getAttr<OverloadableAttr>(); | ||||||
3303 | return A && !A->isImplicit(); | ||||||
3304 | }); | ||||||
3305 | // If we've implicitly added *all* of the overloadable attrs to this | ||||||
3306 | // chain, emitting a "previous redecl" note is pointless. | ||||||
3307 | DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; | ||||||
3308 | } | ||||||
3309 | |||||||
3310 | if (DiagOld) | ||||||
3311 | Diag(DiagOld->getLocation(), | ||||||
3312 | diag::note_attribute_overloadable_prev_overload) | ||||||
3313 | << OldOvl; | ||||||
3314 | |||||||
3315 | if (OldOvl) | ||||||
3316 | New->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||||
3317 | else | ||||||
3318 | New->dropAttr<OverloadableAttr>(); | ||||||
3319 | } | ||||||
3320 | } | ||||||
3321 | |||||||
3322 | // If a function is first declared with a calling convention, but is later | ||||||
3323 | // declared or defined without one, all following decls assume the calling | ||||||
3324 | // convention of the first. | ||||||
3325 | // | ||||||
3326 | // It's OK if a function is first declared without a calling convention, | ||||||
3327 | // but is later declared or defined with the default calling convention. | ||||||
3328 | // | ||||||
3329 | // To test if either decl has an explicit calling convention, we look for | ||||||
3330 | // AttributedType sugar nodes on the type as written. If they are missing or | ||||||
3331 | // were canonicalized away, we assume the calling convention was implicit. | ||||||
3332 | // | ||||||
3333 | // Note also that we DO NOT return at this point, because we still have | ||||||
3334 | // other tests to run. | ||||||
3335 | QualType OldQType = Context.getCanonicalType(Old->getType()); | ||||||
3336 | QualType NewQType = Context.getCanonicalType(New->getType()); | ||||||
3337 | const FunctionType *OldType = cast<FunctionType>(OldQType); | ||||||
3338 | const FunctionType *NewType = cast<FunctionType>(NewQType); | ||||||
3339 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||||
3340 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||||
3341 | bool RequiresAdjustment = false; | ||||||
3342 | |||||||
3343 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { | ||||||
3344 | FunctionDecl *First = Old->getFirstDecl(); | ||||||
3345 | const FunctionType *FT = | ||||||
3346 | First->getType().getCanonicalType()->castAs<FunctionType>(); | ||||||
3347 | FunctionType::ExtInfo FI = FT->getExtInfo(); | ||||||
3348 | bool NewCCExplicit = getCallingConvAttributedType(New->getType()); | ||||||
3349 | if (!NewCCExplicit) { | ||||||
3350 | // Inherit the CC from the previous declaration if it was specified | ||||||
3351 | // there but not here. | ||||||
3352 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||||
3353 | RequiresAdjustment = true; | ||||||
3354 | } else if (Old->getBuiltinID()) { | ||||||
3355 | // Builtin attribute isn't propagated to the new one yet at this point, | ||||||
3356 | // so we check if the old one is a builtin. | ||||||
3357 | |||||||
3358 | // Calling Conventions on a Builtin aren't really useful and setting a | ||||||
3359 | // default calling convention and cdecl'ing some builtin redeclarations is | ||||||
3360 | // common, so warn and ignore the calling convention on the redeclaration. | ||||||
3361 | Diag(New->getLocation(), diag::warn_cconv_unsupported) | ||||||
3362 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||||
3363 | << (int)CallingConventionIgnoredReason::BuiltinFunction; | ||||||
3364 | NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); | ||||||
3365 | RequiresAdjustment = true; | ||||||
3366 | } else { | ||||||
3367 | // Calling conventions aren't compatible, so complain. | ||||||
3368 | bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); | ||||||
3369 | Diag(New->getLocation(), diag::err_cconv_change) | ||||||
3370 | << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) | ||||||
3371 | << !FirstCCExplicit | ||||||
3372 | << (!FirstCCExplicit ? "" : | ||||||
3373 | FunctionType::getNameForCallConv(FI.getCC())); | ||||||
3374 | |||||||
3375 | // Put the note on the first decl, since it is the one that matters. | ||||||
3376 | Diag(First->getLocation(), diag::note_previous_declaration); | ||||||
3377 | return true; | ||||||
3378 | } | ||||||
3379 | } | ||||||
3380 | |||||||
3381 | // FIXME: diagnose the other way around? | ||||||
3382 | if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { | ||||||
3383 | NewTypeInfo = NewTypeInfo.withNoReturn(true); | ||||||
3384 | RequiresAdjustment = true; | ||||||
3385 | } | ||||||
3386 | |||||||
3387 | // Merge regparm attribute. | ||||||
3388 | if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || | ||||||
3389 | OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { | ||||||
3390 | if (NewTypeInfo.getHasRegParm()) { | ||||||
3391 | Diag(New->getLocation(), diag::err_regparm_mismatch) | ||||||
3392 | << NewType->getRegParmType() | ||||||
3393 | << OldType->getRegParmType(); | ||||||
3394 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3395 | return true; | ||||||
3396 | } | ||||||
3397 | |||||||
3398 | NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); | ||||||
3399 | RequiresAdjustment = true; | ||||||
3400 | } | ||||||
3401 | |||||||
3402 | // Merge ns_returns_retained attribute. | ||||||
3403 | if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { | ||||||
3404 | if (NewTypeInfo.getProducesResult()) { | ||||||
3405 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) | ||||||
3406 | << "'ns_returns_retained'"; | ||||||
3407 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3408 | return true; | ||||||
3409 | } | ||||||
3410 | |||||||
3411 | NewTypeInfo = NewTypeInfo.withProducesResult(true); | ||||||
3412 | RequiresAdjustment = true; | ||||||
3413 | } | ||||||
3414 | |||||||
3415 | if (OldTypeInfo.getNoCallerSavedRegs() != | ||||||
3416 | NewTypeInfo.getNoCallerSavedRegs()) { | ||||||
3417 | if (NewTypeInfo.getNoCallerSavedRegs()) { | ||||||
3418 | AnyX86NoCallerSavedRegistersAttr *Attr = | ||||||
3419 | New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); | ||||||
3420 | Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; | ||||||
3421 | Diag(OldLocation, diag::note_previous_declaration); | ||||||
3422 | return true; | ||||||
3423 | } | ||||||
3424 | |||||||
3425 | NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); | ||||||
3426 | RequiresAdjustment = true; | ||||||
3427 | } | ||||||
3428 | |||||||
3429 | if (RequiresAdjustment) { | ||||||
3430 | const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); | ||||||
3431 | AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); | ||||||
3432 | New->setType(QualType(AdjustedType, 0)); | ||||||
3433 | NewQType = Context.getCanonicalType(New->getType()); | ||||||
3434 | } | ||||||
3435 | |||||||
3436 | // If this redeclaration makes the function inline, we may need to add it to | ||||||
3437 | // UndefinedButUsed. | ||||||
3438 | if (!Old->isInlined() && New->isInlined() && | ||||||
3439 | !New->hasAttr<GNUInlineAttr>() && | ||||||
3440 | !getLangOpts().GNUInline && | ||||||
3441 | Old->isUsed(false) && | ||||||
3442 | !Old->isDefined() && !New->isThisDeclarationADefinition()) | ||||||
3443 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||||
3444 | SourceLocation())); | ||||||
3445 | |||||||
3446 | // If this redeclaration makes it newly gnu_inline, we don't want to warn | ||||||
3447 | // about it. | ||||||
3448 | if (New->hasAttr<GNUInlineAttr>() && | ||||||
3449 | Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { | ||||||
3450 | UndefinedButUsed.erase(Old->getCanonicalDecl()); | ||||||
3451 | } | ||||||
3452 | |||||||
3453 | // If pass_object_size params don't match up perfectly, this isn't a valid | ||||||
3454 | // redeclaration. | ||||||
3455 | if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && | ||||||
3456 | !hasIdenticalPassObjectSizeAttrs(Old, New)) { | ||||||
3457 | Diag(New->getLocation(), diag::err_different_pass_object_size_params) | ||||||
3458 | << New->getDeclName(); | ||||||
3459 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3460 | return true; | ||||||
3461 | } | ||||||
3462 | |||||||
3463 | if (getLangOpts().CPlusPlus) { | ||||||
3464 | // C++1z [over.load]p2 | ||||||
3465 | // Certain function declarations cannot be overloaded: | ||||||
3466 | // -- Function declarations that differ only in the return type, | ||||||
3467 | // the exception specification, or both cannot be overloaded. | ||||||
3468 | |||||||
3469 | // Check the exception specifications match. This may recompute the type of | ||||||
3470 | // both Old and New if it resolved exception specifications, so grab the | ||||||
3471 | // types again after this. Because this updates the type, we do this before | ||||||
3472 | // any of the other checks below, which may update the "de facto" NewQType | ||||||
3473 | // but do not necessarily update the type of New. | ||||||
3474 | if (CheckEquivalentExceptionSpec(Old, New)) | ||||||
3475 | return true; | ||||||
3476 | OldQType = Context.getCanonicalType(Old->getType()); | ||||||
3477 | NewQType = Context.getCanonicalType(New->getType()); | ||||||
3478 | |||||||
3479 | // Go back to the type source info to compare the declared return types, | ||||||
3480 | // per C++1y [dcl.type.auto]p13: | ||||||
3481 | // Redeclarations or specializations of a function or function template | ||||||
3482 | // with a declared return type that uses a placeholder type shall also | ||||||
3483 | // use that placeholder, not a deduced type. | ||||||
3484 | QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); | ||||||
3485 | QualType NewDeclaredReturnType = New->getDeclaredReturnType(); | ||||||
3486 | if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && | ||||||
3487 | canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, | ||||||
3488 | OldDeclaredReturnType)) { | ||||||
3489 | QualType ResQT; | ||||||
3490 | if (NewDeclaredReturnType->isObjCObjectPointerType() && | ||||||
3491 | OldDeclaredReturnType->isObjCObjectPointerType()) | ||||||
3492 | // FIXME: This does the wrong thing for a deduced return type. | ||||||
3493 | ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); | ||||||
3494 | if (ResQT.isNull()) { | ||||||
3495 | if (New->isCXXClassMember() && New->isOutOfLine()) | ||||||
3496 | Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) | ||||||
3497 | << New << New->getReturnTypeSourceRange(); | ||||||
3498 | else | ||||||
3499 | Diag(New->getLocation(), diag::err_ovl_diff_return_type) | ||||||
3500 | << New->getReturnTypeSourceRange(); | ||||||
3501 | Diag(OldLocation, PrevDiag) << Old << Old->getType() | ||||||
3502 | << Old->getReturnTypeSourceRange(); | ||||||
3503 | return true; | ||||||
3504 | } | ||||||
3505 | else | ||||||
3506 | NewQType = ResQT; | ||||||
3507 | } | ||||||
3508 | |||||||
3509 | QualType OldReturnType = OldType->getReturnType(); | ||||||
3510 | QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); | ||||||
3511 | if (OldReturnType != NewReturnType) { | ||||||
3512 | // If this function has a deduced return type and has already been | ||||||
3513 | // defined, copy the deduced value from the old declaration. | ||||||
3514 | AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); | ||||||
3515 | if (OldAT && OldAT->isDeduced()) { | ||||||
3516 | New->setType( | ||||||
3517 | SubstAutoType(New->getType(), | ||||||
3518 | OldAT->isDependentType() ? Context.DependentTy | ||||||
3519 | : OldAT->getDeducedType())); | ||||||
3520 | NewQType = Context.getCanonicalType( | ||||||
3521 | SubstAutoType(NewQType, | ||||||
3522 | OldAT->isDependentType() ? Context.DependentTy | ||||||
3523 | : OldAT->getDeducedType())); | ||||||
3524 | } | ||||||
3525 | } | ||||||
3526 | |||||||
3527 | const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); | ||||||
3528 | CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); | ||||||
3529 | if (OldMethod && NewMethod) { | ||||||
3530 | // Preserve triviality. | ||||||
3531 | NewMethod->setTrivial(OldMethod->isTrivial()); | ||||||
3532 | |||||||
3533 | // MSVC allows explicit template specialization at class scope: | ||||||
3534 | // 2 CXXMethodDecls referring to the same function will be injected. | ||||||
3535 | // We don't want a redeclaration error. | ||||||
3536 | bool IsClassScopeExplicitSpecialization = | ||||||
3537 | OldMethod->isFunctionTemplateSpecialization() && | ||||||
3538 | NewMethod->isFunctionTemplateSpecialization(); | ||||||
3539 | bool isFriend = NewMethod->getFriendObjectKind(); | ||||||
3540 | |||||||
3541 | if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && | ||||||
3542 | !IsClassScopeExplicitSpecialization) { | ||||||
3543 | // -- Member function declarations with the same name and the | ||||||
3544 | // same parameter types cannot be overloaded if any of them | ||||||
3545 | // is a static member function declaration. | ||||||
3546 | if (OldMethod->isStatic() != NewMethod->isStatic()) { | ||||||
3547 | Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); | ||||||
3548 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3549 | return true; | ||||||
3550 | } | ||||||
3551 | |||||||
3552 | // C++ [class.mem]p1: | ||||||
3553 | // [...] A member shall not be declared twice in the | ||||||
3554 | // member-specification, except that a nested class or member | ||||||
3555 | // class template can be declared and then later defined. | ||||||
3556 | if (!inTemplateInstantiation()) { | ||||||
3557 | unsigned NewDiag; | ||||||
3558 | if (isa<CXXConstructorDecl>(OldMethod)) | ||||||
3559 | NewDiag = diag::err_constructor_redeclared; | ||||||
3560 | else if (isa<CXXDestructorDecl>(NewMethod)) | ||||||
3561 | NewDiag = diag::err_destructor_redeclared; | ||||||
3562 | else if (isa<CXXConversionDecl>(NewMethod)) | ||||||
3563 | NewDiag = diag::err_conv_function_redeclared; | ||||||
3564 | else | ||||||
3565 | NewDiag = diag::err_member_redeclared; | ||||||
3566 | |||||||
3567 | Diag(New->getLocation(), NewDiag); | ||||||
3568 | } else { | ||||||
3569 | Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) | ||||||
3570 | << New << New->getType(); | ||||||
3571 | } | ||||||
3572 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3573 | return true; | ||||||
3574 | |||||||
3575 | // Complain if this is an explicit declaration of a special | ||||||
3576 | // member that was initially declared implicitly. | ||||||
3577 | // | ||||||
3578 | // As an exception, it's okay to befriend such methods in order | ||||||
3579 | // to permit the implicit constructor/destructor/operator calls. | ||||||
3580 | } else if (OldMethod->isImplicit()) { | ||||||
3581 | if (isFriend) { | ||||||
3582 | NewMethod->setImplicit(); | ||||||
3583 | } else { | ||||||
3584 | Diag(NewMethod->getLocation(), | ||||||
3585 | diag::err_definition_of_implicitly_declared_member) | ||||||
3586 | << New << getSpecialMember(OldMethod); | ||||||
3587 | return true; | ||||||
3588 | } | ||||||
3589 | } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { | ||||||
3590 | Diag(NewMethod->getLocation(), | ||||||
3591 | diag::err_definition_of_explicitly_defaulted_member) | ||||||
3592 | << getSpecialMember(OldMethod); | ||||||
3593 | return true; | ||||||
3594 | } | ||||||
3595 | } | ||||||
3596 | |||||||
3597 | // C++11 [dcl.attr.noreturn]p1: | ||||||
3598 | // The first declaration of a function shall specify the noreturn | ||||||
3599 | // attribute if any declaration of that function specifies the noreturn | ||||||
3600 | // attribute. | ||||||
3601 | const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); | ||||||
3602 | if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { | ||||||
3603 | Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); | ||||||
3604 | Diag(Old->getFirstDecl()->getLocation(), | ||||||
3605 | diag::note_noreturn_missing_first_decl); | ||||||
3606 | } | ||||||
3607 | |||||||
3608 | // C++11 [dcl.attr.depend]p2: | ||||||
3609 | // The first declaration of a function shall specify the | ||||||
3610 | // carries_dependency attribute for its declarator-id if any declaration | ||||||
3611 | // of the function specifies the carries_dependency attribute. | ||||||
3612 | const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); | ||||||
3613 | if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { | ||||||
3614 | Diag(CDA->getLocation(), | ||||||
3615 | diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; | ||||||
3616 | Diag(Old->getFirstDecl()->getLocation(), | ||||||
3617 | diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; | ||||||
3618 | } | ||||||
3619 | |||||||
3620 | // (C++98 8.3.5p3): | ||||||
3621 | // All declarations for a function shall agree exactly in both the | ||||||
3622 | // return type and the parameter-type-list. | ||||||
3623 | // We also want to respect all the extended bits except noreturn. | ||||||
3624 | |||||||
3625 | // noreturn should now match unless the old type info didn't have it. | ||||||
3626 | QualType OldQTypeForComparison = OldQType; | ||||||
3627 | if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { | ||||||
3628 | auto *OldType = OldQType->castAs<FunctionProtoType>(); | ||||||
3629 | const FunctionType *OldTypeForComparison | ||||||
3630 | = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); | ||||||
3631 | OldQTypeForComparison = QualType(OldTypeForComparison, 0); | ||||||
3632 | assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void> (0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 3632, __PRETTY_FUNCTION__)); | ||||||
3633 | } | ||||||
3634 | |||||||
3635 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||||
3636 | // As a special case, retain the language linkage from previous | ||||||
3637 | // declarations of a friend function as an extension. | ||||||
3638 | // | ||||||
3639 | // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC | ||||||
3640 | // and is useful because there's otherwise no way to specify language | ||||||
3641 | // linkage within class scope. | ||||||
3642 | // | ||||||
3643 | // Check cautiously as the friend object kind isn't yet complete. | ||||||
3644 | if (New->getFriendObjectKind() != Decl::FOK_None) { | ||||||
3645 | Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; | ||||||
3646 | Diag(OldLocation, PrevDiag); | ||||||
3647 | } else { | ||||||
3648 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||||
3649 | Diag(OldLocation, PrevDiag); | ||||||
3650 | return true; | ||||||
3651 | } | ||||||
3652 | } | ||||||
3653 | |||||||
3654 | // If the function types are compatible, merge the declarations. Ignore the | ||||||
3655 | // exception specifier because it was already checked above in | ||||||
3656 | // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics | ||||||
3657 | // about incompatible types under -fms-compatibility. | ||||||
3658 | if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, | ||||||
3659 | NewQType)) | ||||||
3660 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3661 | |||||||
3662 | // If the types are imprecise (due to dependent constructs in friends or | ||||||
3663 | // local extern declarations), it's OK if they differ. We'll check again | ||||||
3664 | // during instantiation. | ||||||
3665 | if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) | ||||||
3666 | return false; | ||||||
3667 | |||||||
3668 | // Fall through for conflicting redeclarations and redefinitions. | ||||||
3669 | } | ||||||
3670 | |||||||
3671 | // C: Function types need to be compatible, not identical. This handles | ||||||
3672 | // duplicate function decls like "void f(int); void f(enum X);" properly. | ||||||
3673 | if (!getLangOpts().CPlusPlus && | ||||||
3674 | Context.typesAreCompatible(OldQType, NewQType)) { | ||||||
3675 | const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); | ||||||
3676 | const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); | ||||||
3677 | const FunctionProtoType *OldProto = nullptr; | ||||||
3678 | if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && | ||||||
3679 | (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { | ||||||
3680 | // The old declaration provided a function prototype, but the | ||||||
3681 | // new declaration does not. Merge in the prototype. | ||||||
3682 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 3682, __PRETTY_FUNCTION__)); | ||||||
3683 | SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); | ||||||
3684 | NewQType = | ||||||
3685 | Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, | ||||||
3686 | OldProto->getExtProtoInfo()); | ||||||
3687 | New->setType(NewQType); | ||||||
3688 | New->setHasInheritedPrototype(); | ||||||
3689 | |||||||
3690 | // Synthesize parameters with the same types. | ||||||
3691 | SmallVector<ParmVarDecl*, 16> Params; | ||||||
3692 | for (const auto &ParamType : OldProto->param_types()) { | ||||||
3693 | ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), | ||||||
3694 | SourceLocation(), nullptr, | ||||||
3695 | ParamType, /*TInfo=*/nullptr, | ||||||
3696 | SC_None, nullptr); | ||||||
3697 | Param->setScopeInfo(0, Params.size()); | ||||||
3698 | Param->setImplicit(); | ||||||
3699 | Params.push_back(Param); | ||||||
3700 | } | ||||||
3701 | |||||||
3702 | New->setParams(Params); | ||||||
3703 | } | ||||||
3704 | |||||||
3705 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3706 | } | ||||||
3707 | |||||||
3708 | // Check if the function types are compatible when pointer size address | ||||||
3709 | // spaces are ignored. | ||||||
3710 | if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) | ||||||
3711 | return false; | ||||||
3712 | |||||||
3713 | // GNU C permits a K&R definition to follow a prototype declaration | ||||||
3714 | // if the declared types of the parameters in the K&R definition | ||||||
3715 | // match the types in the prototype declaration, even when the | ||||||
3716 | // promoted types of the parameters from the K&R definition differ | ||||||
3717 | // from the types in the prototype. GCC then keeps the types from | ||||||
3718 | // the prototype. | ||||||
3719 | // | ||||||
3720 | // If a variadic prototype is followed by a non-variadic K&R definition, | ||||||
3721 | // the K&R definition becomes variadic. This is sort of an edge case, but | ||||||
3722 | // it's legal per the standard depending on how you read C99 6.7.5.3p15 and | ||||||
3723 | // C99 6.9.1p8. | ||||||
3724 | if (!getLangOpts().CPlusPlus && | ||||||
3725 | Old->hasPrototype() && !New->hasPrototype() && | ||||||
3726 | New->getType()->getAs<FunctionProtoType>() && | ||||||
3727 | Old->getNumParams() == New->getNumParams()) { | ||||||
3728 | SmallVector<QualType, 16> ArgTypes; | ||||||
3729 | SmallVector<GNUCompatibleParamWarning, 16> Warnings; | ||||||
3730 | const FunctionProtoType *OldProto | ||||||
3731 | = Old->getType()->getAs<FunctionProtoType>(); | ||||||
3732 | const FunctionProtoType *NewProto | ||||||
3733 | = New->getType()->getAs<FunctionProtoType>(); | ||||||
3734 | |||||||
3735 | // Determine whether this is the GNU C extension. | ||||||
3736 | QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), | ||||||
3737 | NewProto->getReturnType()); | ||||||
3738 | bool LooseCompatible = !MergedReturn.isNull(); | ||||||
3739 | for (unsigned Idx = 0, End = Old->getNumParams(); | ||||||
3740 | LooseCompatible && Idx != End; ++Idx) { | ||||||
3741 | ParmVarDecl *OldParm = Old->getParamDecl(Idx); | ||||||
3742 | ParmVarDecl *NewParm = New->getParamDecl(Idx); | ||||||
3743 | if (Context.typesAreCompatible(OldParm->getType(), | ||||||
3744 | NewProto->getParamType(Idx))) { | ||||||
3745 | ArgTypes.push_back(NewParm->getType()); | ||||||
3746 | } else if (Context.typesAreCompatible(OldParm->getType(), | ||||||
3747 | NewParm->getType(), | ||||||
3748 | /*CompareUnqualified=*/true)) { | ||||||
3749 | GNUCompatibleParamWarning Warn = { OldParm, NewParm, | ||||||
3750 | NewProto->getParamType(Idx) }; | ||||||
3751 | Warnings.push_back(Warn); | ||||||
3752 | ArgTypes.push_back(NewParm->getType()); | ||||||
3753 | } else | ||||||
3754 | LooseCompatible = false; | ||||||
3755 | } | ||||||
3756 | |||||||
3757 | if (LooseCompatible) { | ||||||
3758 | for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { | ||||||
3759 | Diag(Warnings[Warn].NewParm->getLocation(), | ||||||
3760 | diag::ext_param_promoted_not_compatible_with_prototype) | ||||||
3761 | << Warnings[Warn].PromotedType | ||||||
3762 | << Warnings[Warn].OldParm->getType(); | ||||||
3763 | if (Warnings[Warn].OldParm->getLocation().isValid()) | ||||||
3764 | Diag(Warnings[Warn].OldParm->getLocation(), | ||||||
3765 | diag::note_previous_declaration); | ||||||
3766 | } | ||||||
3767 | |||||||
3768 | if (MergeTypeWithOld) | ||||||
3769 | New->setType(Context.getFunctionType(MergedReturn, ArgTypes, | ||||||
3770 | OldProto->getExtProtoInfo())); | ||||||
3771 | return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); | ||||||
3772 | } | ||||||
3773 | |||||||
3774 | // Fall through to diagnose conflicting types. | ||||||
3775 | } | ||||||
3776 | |||||||
3777 | // A function that has already been declared has been redeclared or | ||||||
3778 | // defined with a different type; show an appropriate diagnostic. | ||||||
3779 | |||||||
3780 | // If the previous declaration was an implicitly-generated builtin | ||||||
3781 | // declaration, then at the very least we should use a specialized note. | ||||||
3782 | unsigned BuiltinID; | ||||||
3783 | if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { | ||||||
3784 | // If it's actually a library-defined builtin function like 'malloc' | ||||||
3785 | // or 'printf', just warn about the incompatible redeclaration. | ||||||
3786 | if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { | ||||||
3787 | Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; | ||||||
3788 | Diag(OldLocation, diag::note_previous_builtin_declaration) | ||||||
3789 | << Old << Old->getType(); | ||||||
3790 | return false; | ||||||
3791 | } | ||||||
3792 | |||||||
3793 | PrevDiag = diag::note_previous_builtin_declaration; | ||||||
3794 | } | ||||||
3795 | |||||||
3796 | Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); | ||||||
3797 | Diag(OldLocation, PrevDiag) << Old << Old->getType(); | ||||||
3798 | return true; | ||||||
3799 | } | ||||||
3800 | |||||||
3801 | /// Completes the merge of two function declarations that are | ||||||
3802 | /// known to be compatible. | ||||||
3803 | /// | ||||||
3804 | /// This routine handles the merging of attributes and other | ||||||
3805 | /// properties of function declarations from the old declaration to | ||||||
3806 | /// the new declaration, once we know that New is in fact a | ||||||
3807 | /// redeclaration of Old. | ||||||
3808 | /// | ||||||
3809 | /// \returns false | ||||||
3810 | bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, | ||||||
3811 | Scope *S, bool MergeTypeWithOld) { | ||||||
3812 | // Merge the attributes | ||||||
3813 | mergeDeclAttributes(New, Old); | ||||||
3814 | |||||||
3815 | // Merge "pure" flag. | ||||||
3816 | if (Old->isPure()) | ||||||
3817 | New->setPure(); | ||||||
3818 | |||||||
3819 | // Merge "used" flag. | ||||||
3820 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||||
3821 | New->setIsUsed(); | ||||||
3822 | |||||||
3823 | // Merge attributes from the parameters. These can mismatch with K&R | ||||||
3824 | // declarations. | ||||||
3825 | if (New->getNumParams() == Old->getNumParams()) | ||||||
3826 | for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { | ||||||
3827 | ParmVarDecl *NewParam = New->getParamDecl(i); | ||||||
3828 | ParmVarDecl *OldParam = Old->getParamDecl(i); | ||||||
3829 | mergeParamDeclAttributes(NewParam, OldParam, *this); | ||||||
3830 | mergeParamDeclTypes(NewParam, OldParam, *this); | ||||||
3831 | } | ||||||
3832 | |||||||
3833 | if (getLangOpts().CPlusPlus) | ||||||
3834 | return MergeCXXFunctionDecl(New, Old, S); | ||||||
3835 | |||||||
3836 | // Merge the function types so the we get the composite types for the return | ||||||
3837 | // and argument types. Per C11 6.2.7/4, only update the type if the old decl | ||||||
3838 | // was visible. | ||||||
3839 | QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); | ||||||
3840 | if (!Merged.isNull() && MergeTypeWithOld) | ||||||
3841 | New->setType(Merged); | ||||||
3842 | |||||||
3843 | return false; | ||||||
3844 | } | ||||||
3845 | |||||||
3846 | void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, | ||||||
3847 | ObjCMethodDecl *oldMethod) { | ||||||
3848 | // Merge the attributes, including deprecated/unavailable | ||||||
3849 | AvailabilityMergeKind MergeKind = | ||||||
3850 | isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) | ||||||
3851 | ? AMK_ProtocolImplementation | ||||||
3852 | : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration | ||||||
3853 | : AMK_Override; | ||||||
3854 | |||||||
3855 | mergeDeclAttributes(newMethod, oldMethod, MergeKind); | ||||||
3856 | |||||||
3857 | // Merge attributes from the parameters. | ||||||
3858 | ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), | ||||||
3859 | oe = oldMethod->param_end(); | ||||||
3860 | for (ObjCMethodDecl::param_iterator | ||||||
3861 | ni = newMethod->param_begin(), ne = newMethod->param_end(); | ||||||
3862 | ni != ne && oi != oe; ++ni, ++oi) | ||||||
3863 | mergeParamDeclAttributes(*ni, *oi, *this); | ||||||
3864 | |||||||
3865 | CheckObjCMethodOverride(newMethod, oldMethod); | ||||||
3866 | } | ||||||
3867 | |||||||
3868 | static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { | ||||||
3869 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 3869, __PRETTY_FUNCTION__)); | ||||||
3870 | |||||||
3871 | S.Diag(New->getLocation(), New->isThisDeclarationADefinition() | ||||||
3872 | ? diag::err_redefinition_different_type | ||||||
3873 | : diag::err_redeclaration_different_type) | ||||||
3874 | << New->getDeclName() << New->getType() << Old->getType(); | ||||||
3875 | |||||||
3876 | diag::kind PrevDiag; | ||||||
3877 | SourceLocation OldLocation; | ||||||
3878 | std::tie(PrevDiag, OldLocation) | ||||||
3879 | = getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
3880 | S.Diag(OldLocation, PrevDiag); | ||||||
3881 | New->setInvalidDecl(); | ||||||
3882 | } | ||||||
3883 | |||||||
3884 | /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and | ||||||
3885 | /// scope as a previous declaration 'Old'. Figure out how to merge their types, | ||||||
3886 | /// emitting diagnostics as appropriate. | ||||||
3887 | /// | ||||||
3888 | /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back | ||||||
3889 | /// to here in AddInitializerToDecl. We can't check them before the initializer | ||||||
3890 | /// is attached. | ||||||
3891 | void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, | ||||||
3892 | bool MergeTypeWithOld) { | ||||||
3893 | if (New->isInvalidDecl() || Old->isInvalidDecl()) | ||||||
3894 | return; | ||||||
3895 | |||||||
3896 | QualType MergedT; | ||||||
3897 | if (getLangOpts().CPlusPlus) { | ||||||
3898 | if (New->getType()->isUndeducedType()) { | ||||||
3899 | // We don't know what the new type is until the initializer is attached. | ||||||
3900 | return; | ||||||
3901 | } else if (Context.hasSameType(New->getType(), Old->getType())) { | ||||||
3902 | // These could still be something that needs exception specs checked. | ||||||
3903 | return MergeVarDeclExceptionSpecs(New, Old); | ||||||
3904 | } | ||||||
3905 | // C++ [basic.link]p10: | ||||||
3906 | // [...] the types specified by all declarations referring to a given | ||||||
3907 | // object or function shall be identical, except that declarations for an | ||||||
3908 | // array object can specify array types that differ by the presence or | ||||||
3909 | // absence of a major array bound (8.3.4). | ||||||
3910 | else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { | ||||||
3911 | const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); | ||||||
3912 | const ArrayType *NewArray = Context.getAsArrayType(New->getType()); | ||||||
3913 | |||||||
3914 | // We are merging a variable declaration New into Old. If it has an array | ||||||
3915 | // bound, and that bound differs from Old's bound, we should diagnose the | ||||||
3916 | // mismatch. | ||||||
3917 | if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { | ||||||
3918 | for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; | ||||||
3919 | PrevVD = PrevVD->getPreviousDecl()) { | ||||||
3920 | QualType PrevVDTy = PrevVD->getType(); | ||||||
3921 | if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) | ||||||
3922 | continue; | ||||||
3923 | |||||||
3924 | if (!Context.hasSameType(New->getType(), PrevVDTy)) | ||||||
3925 | return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); | ||||||
3926 | } | ||||||
3927 | } | ||||||
3928 | |||||||
3929 | if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { | ||||||
3930 | if (Context.hasSameType(OldArray->getElementType(), | ||||||
3931 | NewArray->getElementType())) | ||||||
3932 | MergedT = New->getType(); | ||||||
3933 | } | ||||||
3934 | // FIXME: Check visibility. New is hidden but has a complete type. If New | ||||||
3935 | // has no array bound, it should not inherit one from Old, if Old is not | ||||||
3936 | // visible. | ||||||
3937 | else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { | ||||||
3938 | if (Context.hasSameType(OldArray->getElementType(), | ||||||
3939 | NewArray->getElementType())) | ||||||
3940 | MergedT = Old->getType(); | ||||||
3941 | } | ||||||
3942 | } | ||||||
3943 | else if (New->getType()->isObjCObjectPointerType() && | ||||||
3944 | Old->getType()->isObjCObjectPointerType()) { | ||||||
3945 | MergedT = Context.mergeObjCGCQualifiers(New->getType(), | ||||||
3946 | Old->getType()); | ||||||
3947 | } | ||||||
3948 | } else { | ||||||
3949 | // C 6.2.7p2: | ||||||
3950 | // All declarations that refer to the same object or function shall have | ||||||
3951 | // compatible type. | ||||||
3952 | MergedT = Context.mergeTypes(New->getType(), Old->getType()); | ||||||
3953 | } | ||||||
3954 | if (MergedT.isNull()) { | ||||||
3955 | // It's OK if we couldn't merge types if either type is dependent, for a | ||||||
3956 | // block-scope variable. In other cases (static data members of class | ||||||
3957 | // templates, variable templates, ...), we require the types to be | ||||||
3958 | // equivalent. | ||||||
3959 | // FIXME: The C++ standard doesn't say anything about this. | ||||||
3960 | if ((New->getType()->isDependentType() || | ||||||
3961 | Old->getType()->isDependentType()) && New->isLocalVarDecl()) { | ||||||
3962 | // If the old type was dependent, we can't merge with it, so the new type | ||||||
3963 | // becomes dependent for now. We'll reproduce the original type when we | ||||||
3964 | // instantiate the TypeSourceInfo for the variable. | ||||||
3965 | if (!New->getType()->isDependentType() && MergeTypeWithOld) | ||||||
3966 | New->setType(Context.DependentTy); | ||||||
3967 | return; | ||||||
3968 | } | ||||||
3969 | return diagnoseVarDeclTypeMismatch(*this, New, Old); | ||||||
3970 | } | ||||||
3971 | |||||||
3972 | // Don't actually update the type on the new declaration if the old | ||||||
3973 | // declaration was an extern declaration in a different scope. | ||||||
3974 | if (MergeTypeWithOld) | ||||||
3975 | New->setType(MergedT); | ||||||
3976 | } | ||||||
3977 | |||||||
3978 | static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, | ||||||
3979 | LookupResult &Previous) { | ||||||
3980 | // C11 6.2.7p4: | ||||||
3981 | // For an identifier with internal or external linkage declared | ||||||
3982 | // in a scope in which a prior declaration of that identifier is | ||||||
3983 | // visible, if the prior declaration specifies internal or | ||||||
3984 | // external linkage, the type of the identifier at the later | ||||||
3985 | // declaration becomes the composite type. | ||||||
3986 | // | ||||||
3987 | // If the variable isn't visible, we do not merge with its type. | ||||||
3988 | if (Previous.isShadowed()) | ||||||
3989 | return false; | ||||||
3990 | |||||||
3991 | if (S.getLangOpts().CPlusPlus) { | ||||||
3992 | // C++11 [dcl.array]p3: | ||||||
3993 | // If there is a preceding declaration of the entity in the same | ||||||
3994 | // scope in which the bound was specified, an omitted array bound | ||||||
3995 | // is taken to be the same as in that earlier declaration. | ||||||
3996 | return NewVD->isPreviousDeclInSameBlockScope() || | ||||||
3997 | (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && | ||||||
3998 | !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); | ||||||
3999 | } else { | ||||||
4000 | // If the old declaration was function-local, don't merge with its | ||||||
4001 | // type unless we're in the same function. | ||||||
4002 | return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || | ||||||
4003 | OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); | ||||||
4004 | } | ||||||
4005 | } | ||||||
4006 | |||||||
4007 | /// MergeVarDecl - We just parsed a variable 'New' which has the same name | ||||||
4008 | /// and scope as a previous declaration 'Old'. Figure out how to resolve this | ||||||
4009 | /// situation, merging decls or emitting diagnostics as appropriate. | ||||||
4010 | /// | ||||||
4011 | /// Tentative definition rules (C99 6.9.2p2) are checked by | ||||||
4012 | /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative | ||||||
4013 | /// definitions here, since the initializer hasn't been attached. | ||||||
4014 | /// | ||||||
4015 | void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { | ||||||
4016 | // If the new decl is already invalid, don't do any other checking. | ||||||
4017 | if (New->isInvalidDecl()) | ||||||
4018 | return; | ||||||
4019 | |||||||
4020 | if (!shouldLinkPossiblyHiddenDecl(Previous, New)) | ||||||
4021 | return; | ||||||
4022 | |||||||
4023 | VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); | ||||||
4024 | |||||||
4025 | // Verify the old decl was also a variable or variable template. | ||||||
4026 | VarDecl *Old = nullptr; | ||||||
4027 | VarTemplateDecl *OldTemplate = nullptr; | ||||||
4028 | if (Previous.isSingleResult()) { | ||||||
4029 | if (NewTemplate) { | ||||||
4030 | OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); | ||||||
4031 | Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; | ||||||
4032 | |||||||
4033 | if (auto *Shadow = | ||||||
4034 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||||
4035 | if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) | ||||||
4036 | return New->setInvalidDecl(); | ||||||
4037 | } else { | ||||||
4038 | Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); | ||||||
4039 | |||||||
4040 | if (auto *Shadow = | ||||||
4041 | dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) | ||||||
4042 | if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) | ||||||
4043 | return New->setInvalidDecl(); | ||||||
4044 | } | ||||||
4045 | } | ||||||
4046 | if (!Old) { | ||||||
4047 | Diag(New->getLocation(), diag::err_redefinition_different_kind) | ||||||
4048 | << New->getDeclName(); | ||||||
4049 | notePreviousDefinition(Previous.getRepresentativeDecl(), | ||||||
4050 | New->getLocation()); | ||||||
4051 | return New->setInvalidDecl(); | ||||||
4052 | } | ||||||
4053 | |||||||
4054 | // Ensure the template parameters are compatible. | ||||||
4055 | if (NewTemplate && | ||||||
4056 | !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), | ||||||
4057 | OldTemplate->getTemplateParameters(), | ||||||
4058 | /*Complain=*/true, TPL_TemplateMatch)) | ||||||
4059 | return New->setInvalidDecl(); | ||||||
4060 | |||||||
4061 | // C++ [class.mem]p1: | ||||||
4062 | // A member shall not be declared twice in the member-specification [...] | ||||||
4063 | // | ||||||
4064 | // Here, we need only consider static data members. | ||||||
4065 | if (Old->isStaticDataMember() && !New->isOutOfLine()) { | ||||||
4066 | Diag(New->getLocation(), diag::err_duplicate_member) | ||||||
4067 | << New->getIdentifier(); | ||||||
4068 | Diag(Old->getLocation(), diag::note_previous_declaration); | ||||||
4069 | New->setInvalidDecl(); | ||||||
4070 | } | ||||||
4071 | |||||||
4072 | mergeDeclAttributes(New, Old); | ||||||
4073 | // Warn if an already-declared variable is made a weak_import in a subsequent | ||||||
4074 | // declaration | ||||||
4075 | if (New->hasAttr<WeakImportAttr>() && | ||||||
4076 | Old->getStorageClass() == SC_None && | ||||||
4077 | !Old->hasAttr<WeakImportAttr>()) { | ||||||
4078 | Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); | ||||||
4079 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4080 | // Remove weak_import attribute on new declaration. | ||||||
4081 | New->dropAttr<WeakImportAttr>(); | ||||||
4082 | } | ||||||
4083 | |||||||
4084 | if (New->hasAttr<InternalLinkageAttr>() && | ||||||
4085 | !Old->hasAttr<InternalLinkageAttr>()) { | ||||||
4086 | Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) | ||||||
4087 | << New->getDeclName(); | ||||||
4088 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4089 | New->dropAttr<InternalLinkageAttr>(); | ||||||
4090 | } | ||||||
4091 | |||||||
4092 | // Merge the types. | ||||||
4093 | VarDecl *MostRecent = Old->getMostRecentDecl(); | ||||||
4094 | if (MostRecent != Old) { | ||||||
4095 | MergeVarDeclTypes(New, MostRecent, | ||||||
4096 | mergeTypeWithPrevious(*this, New, MostRecent, Previous)); | ||||||
4097 | if (New->isInvalidDecl()) | ||||||
4098 | return; | ||||||
4099 | } | ||||||
4100 | |||||||
4101 | MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); | ||||||
4102 | if (New->isInvalidDecl()) | ||||||
4103 | return; | ||||||
4104 | |||||||
4105 | diag::kind PrevDiag; | ||||||
4106 | SourceLocation OldLocation; | ||||||
4107 | std::tie(PrevDiag, OldLocation) = | ||||||
4108 | getNoteDiagForInvalidRedeclaration(Old, New); | ||||||
4109 | |||||||
4110 | // [dcl.stc]p8: Check if we have a non-static decl followed by a static. | ||||||
4111 | if (New->getStorageClass() == SC_Static && | ||||||
4112 | !New->isStaticDataMember() && | ||||||
4113 | Old->hasExternalFormalLinkage()) { | ||||||
4114 | if (getLangOpts().MicrosoftExt) { | ||||||
4115 | Diag(New->getLocation(), diag::ext_static_non_static) | ||||||
4116 | << New->getDeclName(); | ||||||
4117 | Diag(OldLocation, PrevDiag); | ||||||
4118 | } else { | ||||||
4119 | Diag(New->getLocation(), diag::err_static_non_static) | ||||||
4120 | << New->getDeclName(); | ||||||
4121 | Diag(OldLocation, PrevDiag); | ||||||
4122 | return New->setInvalidDecl(); | ||||||
4123 | } | ||||||
4124 | } | ||||||
4125 | // C99 6.2.2p4: | ||||||
4126 | // For an identifier declared with the storage-class specifier | ||||||
4127 | // extern in a scope in which a prior declaration of that | ||||||
4128 | // identifier is visible,23) if the prior declaration specifies | ||||||
4129 | // internal or external linkage, the linkage of the identifier at | ||||||
4130 | // the later declaration is the same as the linkage specified at | ||||||
4131 | // the prior declaration. If no prior declaration is visible, or | ||||||
4132 | // if the prior declaration specifies no linkage, then the | ||||||
4133 | // identifier has external linkage. | ||||||
4134 | if (New->hasExternalStorage() && Old->hasLinkage()) | ||||||
4135 | /* Okay */; | ||||||
4136 | else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && | ||||||
4137 | !New->isStaticDataMember() && | ||||||
4138 | Old->getCanonicalDecl()->getStorageClass() == SC_Static) { | ||||||
4139 | Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); | ||||||
4140 | Diag(OldLocation, PrevDiag); | ||||||
4141 | return New->setInvalidDecl(); | ||||||
4142 | } | ||||||
4143 | |||||||
4144 | // Check if extern is followed by non-extern and vice-versa. | ||||||
4145 | if (New->hasExternalStorage() && | ||||||
4146 | !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { | ||||||
4147 | Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); | ||||||
4148 | Diag(OldLocation, PrevDiag); | ||||||
4149 | return New->setInvalidDecl(); | ||||||
4150 | } | ||||||
4151 | if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && | ||||||
4152 | !New->hasExternalStorage()) { | ||||||
4153 | Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); | ||||||
4154 | Diag(OldLocation, PrevDiag); | ||||||
4155 | return New->setInvalidDecl(); | ||||||
4156 | } | ||||||
4157 | |||||||
4158 | if (CheckRedeclarationModuleOwnership(New, Old)) | ||||||
4159 | return; | ||||||
4160 | |||||||
4161 | // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. | ||||||
4162 | |||||||
4163 | // FIXME: The test for external storage here seems wrong? We still | ||||||
4164 | // need to check for mismatches. | ||||||
4165 | if (!New->hasExternalStorage() && !New->isFileVarDecl() && | ||||||
4166 | // Don't complain about out-of-line definitions of static members. | ||||||
4167 | !(Old->getLexicalDeclContext()->isRecord() && | ||||||
4168 | !New->getLexicalDeclContext()->isRecord())) { | ||||||
4169 | Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); | ||||||
4170 | Diag(OldLocation, PrevDiag); | ||||||
4171 | return New->setInvalidDecl(); | ||||||
4172 | } | ||||||
4173 | |||||||
4174 | if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { | ||||||
4175 | if (VarDecl *Def = Old->getDefinition()) { | ||||||
4176 | // C++1z [dcl.fcn.spec]p4: | ||||||
4177 | // If the definition of a variable appears in a translation unit before | ||||||
4178 | // its first declaration as inline, the program is ill-formed. | ||||||
4179 | Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; | ||||||
4180 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
4181 | } | ||||||
4182 | } | ||||||
4183 | |||||||
4184 | // If this redeclaration makes the variable inline, we may need to add it to | ||||||
4185 | // UndefinedButUsed. | ||||||
4186 | if (!Old->isInline() && New->isInline() && Old->isUsed(false) && | ||||||
4187 | !Old->getDefinition() && !New->isThisDeclarationADefinition()) | ||||||
4188 | UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), | ||||||
4189 | SourceLocation())); | ||||||
4190 | |||||||
4191 | if (New->getTLSKind() != Old->getTLSKind()) { | ||||||
4192 | if (!Old->getTLSKind()) { | ||||||
4193 | Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); | ||||||
4194 | Diag(OldLocation, PrevDiag); | ||||||
4195 | } else if (!New->getTLSKind()) { | ||||||
4196 | Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); | ||||||
4197 | Diag(OldLocation, PrevDiag); | ||||||
4198 | } else { | ||||||
4199 | // Do not allow redeclaration to change the variable between requiring | ||||||
4200 | // static and dynamic initialization. | ||||||
4201 | // FIXME: GCC allows this, but uses the TLS keyword on the first | ||||||
4202 | // declaration to determine the kind. Do we need to be compatible here? | ||||||
4203 | Diag(New->getLocation(), diag::err_thread_thread_different_kind) | ||||||
4204 | << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); | ||||||
4205 | Diag(OldLocation, PrevDiag); | ||||||
4206 | } | ||||||
4207 | } | ||||||
4208 | |||||||
4209 | // C++ doesn't have tentative definitions, so go right ahead and check here. | ||||||
4210 | if (getLangOpts().CPlusPlus && | ||||||
4211 | New->isThisDeclarationADefinition() == VarDecl::Definition) { | ||||||
4212 | if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && | ||||||
4213 | Old->getCanonicalDecl()->isConstexpr()) { | ||||||
4214 | // This definition won't be a definition any more once it's been merged. | ||||||
4215 | Diag(New->getLocation(), | ||||||
4216 | diag::warn_deprecated_redundant_constexpr_static_def); | ||||||
4217 | } else if (VarDecl *Def = Old->getDefinition()) { | ||||||
4218 | if (checkVarDeclRedefinition(Def, New)) | ||||||
4219 | return; | ||||||
4220 | } | ||||||
4221 | } | ||||||
4222 | |||||||
4223 | if (haveIncompatibleLanguageLinkages(Old, New)) { | ||||||
4224 | Diag(New->getLocation(), diag::err_different_language_linkage) << New; | ||||||
4225 | Diag(OldLocation, PrevDiag); | ||||||
4226 | New->setInvalidDecl(); | ||||||
4227 | return; | ||||||
4228 | } | ||||||
4229 | |||||||
4230 | // Merge "used" flag. | ||||||
4231 | if (Old->getMostRecentDecl()->isUsed(false)) | ||||||
4232 | New->setIsUsed(); | ||||||
4233 | |||||||
4234 | // Keep a chain of previous declarations. | ||||||
4235 | New->setPreviousDecl(Old); | ||||||
4236 | if (NewTemplate) | ||||||
4237 | NewTemplate->setPreviousDecl(OldTemplate); | ||||||
4238 | adjustDeclContextForDeclaratorDecl(New, Old); | ||||||
4239 | |||||||
4240 | // Inherit access appropriately. | ||||||
4241 | New->setAccess(Old->getAccess()); | ||||||
4242 | if (NewTemplate) | ||||||
4243 | NewTemplate->setAccess(New->getAccess()); | ||||||
4244 | |||||||
4245 | if (Old->isInline()) | ||||||
4246 | New->setImplicitlyInline(); | ||||||
4247 | } | ||||||
4248 | |||||||
4249 | void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { | ||||||
4250 | SourceManager &SrcMgr = getSourceManager(); | ||||||
4251 | auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); | ||||||
4252 | auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); | ||||||
4253 | auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); | ||||||
4254 | auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); | ||||||
4255 | auto &HSI = PP.getHeaderSearchInfo(); | ||||||
4256 | StringRef HdrFilename = | ||||||
4257 | SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); | ||||||
4258 | |||||||
4259 | auto noteFromModuleOrInclude = [&](Module *Mod, | ||||||
4260 | SourceLocation IncLoc) -> bool { | ||||||
4261 | // Redefinition errors with modules are common with non modular mapped | ||||||
4262 | // headers, example: a non-modular header H in module A that also gets | ||||||
4263 | // included directly in a TU. Pointing twice to the same header/definition | ||||||
4264 | // is confusing, try to get better diagnostics when modules is on. | ||||||
4265 | if (IncLoc.isValid()) { | ||||||
4266 | if (Mod) { | ||||||
4267 | Diag(IncLoc, diag::note_redefinition_modules_same_file) | ||||||
4268 | << HdrFilename.str() << Mod->getFullModuleName(); | ||||||
4269 | if (!Mod->DefinitionLoc.isInvalid()) | ||||||
4270 | Diag(Mod->DefinitionLoc, diag::note_defined_here) | ||||||
4271 | << Mod->getFullModuleName(); | ||||||
4272 | } else { | ||||||
4273 | Diag(IncLoc, diag::note_redefinition_include_same_file) | ||||||
4274 | << HdrFilename.str(); | ||||||
4275 | } | ||||||
4276 | return true; | ||||||
4277 | } | ||||||
4278 | |||||||
4279 | return false; | ||||||
4280 | }; | ||||||
4281 | |||||||
4282 | // Is it the same file and same offset? Provide more information on why | ||||||
4283 | // this leads to a redefinition error. | ||||||
4284 | if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { | ||||||
4285 | SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); | ||||||
4286 | SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); | ||||||
4287 | bool EmittedDiag = | ||||||
4288 | noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); | ||||||
4289 | EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); | ||||||
4290 | |||||||
4291 | // If the header has no guards, emit a note suggesting one. | ||||||
4292 | if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) | ||||||
4293 | Diag(Old->getLocation(), diag::note_use_ifdef_guards); | ||||||
4294 | |||||||
4295 | if (EmittedDiag) | ||||||
4296 | return; | ||||||
4297 | } | ||||||
4298 | |||||||
4299 | // Redefinition coming from different files or couldn't do better above. | ||||||
4300 | if (Old->getLocation().isValid()) | ||||||
4301 | Diag(Old->getLocation(), diag::note_previous_definition); | ||||||
4302 | } | ||||||
4303 | |||||||
4304 | /// We've just determined that \p Old and \p New both appear to be definitions | ||||||
4305 | /// of the same variable. Either diagnose or fix the problem. | ||||||
4306 | bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { | ||||||
4307 | if (!hasVisibleDefinition(Old) && | ||||||
4308 | (New->getFormalLinkage() == InternalLinkage || | ||||||
4309 | New->isInline() || | ||||||
4310 | New->getDescribedVarTemplate() || | ||||||
4311 | New->getNumTemplateParameterLists() || | ||||||
4312 | New->getDeclContext()->isDependentContext())) { | ||||||
4313 | // The previous definition is hidden, and multiple definitions are | ||||||
4314 | // permitted (in separate TUs). Demote this to a declaration. | ||||||
4315 | New->demoteThisDefinitionToDeclaration(); | ||||||
4316 | |||||||
4317 | // Make the canonical definition visible. | ||||||
4318 | if (auto *OldTD = Old->getDescribedVarTemplate()) | ||||||
4319 | makeMergedDefinitionVisible(OldTD); | ||||||
4320 | makeMergedDefinitionVisible(Old); | ||||||
4321 | return false; | ||||||
4322 | } else { | ||||||
4323 | Diag(New->getLocation(), diag::err_redefinition) << New; | ||||||
4324 | notePreviousDefinition(Old, New->getLocation()); | ||||||
4325 | New->setInvalidDecl(); | ||||||
4326 | return true; | ||||||
4327 | } | ||||||
4328 | } | ||||||
4329 | |||||||
4330 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||||
4331 | /// no declarator (e.g. "struct foo;") is parsed. | ||||||
4332 | Decl * | ||||||
4333 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||||
4334 | RecordDecl *&AnonRecord) { | ||||||
4335 | return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, | ||||||
4336 | AnonRecord); | ||||||
4337 | } | ||||||
4338 | |||||||
4339 | // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to | ||||||
4340 | // disambiguate entities defined in different scopes. | ||||||
4341 | // While the VS2015 ABI fixes potential miscompiles, it is also breaks | ||||||
4342 | // compatibility. | ||||||
4343 | // We will pick our mangling number depending on which version of MSVC is being | ||||||
4344 | // targeted. | ||||||
4345 | static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { | ||||||
4346 | return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) | ||||||
4347 | ? S->getMSCurManglingNumber() | ||||||
4348 | : S->getMSLastManglingNumber(); | ||||||
4349 | } | ||||||
4350 | |||||||
4351 | void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { | ||||||
4352 | if (!Context.getLangOpts().CPlusPlus) | ||||||
4353 | return; | ||||||
4354 | |||||||
4355 | if (isa<CXXRecordDecl>(Tag->getParent())) { | ||||||
4356 | // If this tag is the direct child of a class, number it if | ||||||
4357 | // it is anonymous. | ||||||
4358 | if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) | ||||||
4359 | return; | ||||||
4360 | MangleNumberingContext &MCtx = | ||||||
4361 | Context.getManglingNumberContext(Tag->getParent()); | ||||||
4362 | Context.setManglingNumber( | ||||||
4363 | Tag, MCtx.getManglingNumber( | ||||||
4364 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||||
4365 | return; | ||||||
4366 | } | ||||||
4367 | |||||||
4368 | // If this tag isn't a direct child of a class, number it if it is local. | ||||||
4369 | MangleNumberingContext *MCtx; | ||||||
4370 | Decl *ManglingContextDecl; | ||||||
4371 | std::tie(MCtx, ManglingContextDecl) = | ||||||
4372 | getCurrentMangleNumberContext(Tag->getDeclContext()); | ||||||
4373 | if (MCtx) { | ||||||
4374 | Context.setManglingNumber( | ||||||
4375 | Tag, MCtx->getManglingNumber( | ||||||
4376 | Tag, getMSManglingNumber(getLangOpts(), TagScope))); | ||||||
4377 | } | ||||||
4378 | } | ||||||
4379 | |||||||
4380 | namespace { | ||||||
4381 | struct NonCLikeKind { | ||||||
4382 | enum { | ||||||
4383 | None, | ||||||
4384 | BaseClass, | ||||||
4385 | DefaultMemberInit, | ||||||
4386 | Lambda, | ||||||
4387 | Friend, | ||||||
4388 | OtherMember, | ||||||
4389 | Invalid, | ||||||
4390 | } Kind = None; | ||||||
4391 | SourceRange Range; | ||||||
4392 | |||||||
4393 | explicit operator bool() { return Kind != None; } | ||||||
4394 | }; | ||||||
4395 | } | ||||||
4396 | |||||||
4397 | /// Determine whether a class is C-like, according to the rules of C++ | ||||||
4398 | /// [dcl.typedef] for anonymous classes with typedef names for linkage. | ||||||
4399 | static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { | ||||||
4400 | if (RD->isInvalidDecl()) | ||||||
4401 | return {NonCLikeKind::Invalid, {}}; | ||||||
4402 | |||||||
4403 | // C++ [dcl.typedef]p9: [P1766R1] | ||||||
4404 | // An unnamed class with a typedef name for linkage purposes shall not | ||||||
4405 | // | ||||||
4406 | // -- have any base classes | ||||||
4407 | if (RD->getNumBases()) | ||||||
4408 | return {NonCLikeKind::BaseClass, | ||||||
4409 | SourceRange(RD->bases_begin()->getBeginLoc(), | ||||||
4410 | RD->bases_end()[-1].getEndLoc())}; | ||||||
4411 | bool Invalid = false; | ||||||
4412 | for (Decl *D : RD->decls()) { | ||||||
4413 | // Don't complain about things we already diagnosed. | ||||||
4414 | if (D->isInvalidDecl()) { | ||||||
4415 | Invalid = true; | ||||||
4416 | continue; | ||||||
4417 | } | ||||||
4418 | |||||||
4419 | // -- have any [...] default member initializers | ||||||
4420 | if (auto *FD = dyn_cast<FieldDecl>(D)) { | ||||||
4421 | if (FD->hasInClassInitializer()) { | ||||||
4422 | auto *Init = FD->getInClassInitializer(); | ||||||
4423 | return {NonCLikeKind::DefaultMemberInit, | ||||||
4424 | Init ? Init->getSourceRange() : D->getSourceRange()}; | ||||||
4425 | } | ||||||
4426 | continue; | ||||||
4427 | } | ||||||
4428 | |||||||
4429 | // FIXME: We don't allow friend declarations. This violates the wording of | ||||||
4430 | // P1766, but not the intent. | ||||||
4431 | if (isa<FriendDecl>(D)) | ||||||
4432 | return {NonCLikeKind::Friend, D->getSourceRange()}; | ||||||
4433 | |||||||
4434 | // -- declare any members other than non-static data members, member | ||||||
4435 | // enumerations, or member classes, | ||||||
4436 | if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || | ||||||
4437 | isa<EnumDecl>(D)) | ||||||
4438 | continue; | ||||||
4439 | auto *MemberRD = dyn_cast<CXXRecordDecl>(D); | ||||||
4440 | if (!MemberRD) { | ||||||
4441 | if (D->isImplicit()) | ||||||
4442 | continue; | ||||||
4443 | return {NonCLikeKind::OtherMember, D->getSourceRange()}; | ||||||
4444 | } | ||||||
4445 | |||||||
4446 | // -- contain a lambda-expression, | ||||||
4447 | if (MemberRD->isLambda()) | ||||||
4448 | return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; | ||||||
4449 | |||||||
4450 | // and all member classes shall also satisfy these requirements | ||||||
4451 | // (recursively). | ||||||
4452 | if (MemberRD->isThisDeclarationADefinition()) { | ||||||
4453 | if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) | ||||||
4454 | return Kind; | ||||||
4455 | } | ||||||
4456 | } | ||||||
4457 | |||||||
4458 | return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; | ||||||
4459 | } | ||||||
4460 | |||||||
4461 | void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, | ||||||
4462 | TypedefNameDecl *NewTD) { | ||||||
4463 | if (TagFromDeclSpec->isInvalidDecl()) | ||||||
4464 | return; | ||||||
4465 | |||||||
4466 | // Do nothing if the tag already has a name for linkage purposes. | ||||||
4467 | if (TagFromDeclSpec->hasNameForLinkage()) | ||||||
4468 | return; | ||||||
4469 | |||||||
4470 | // A well-formed anonymous tag must always be a TUK_Definition. | ||||||
4471 | assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast <void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4471, __PRETTY_FUNCTION__)); | ||||||
4472 | |||||||
4473 | // The type must match the tag exactly; no qualifiers allowed. | ||||||
4474 | if (!Context.hasSameType(NewTD->getUnderlyingType(), | ||||||
4475 | Context.getTagDeclType(TagFromDeclSpec))) { | ||||||
4476 | if (getLangOpts().CPlusPlus) | ||||||
4477 | Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); | ||||||
4478 | return; | ||||||
4479 | } | ||||||
4480 | |||||||
4481 | // C++ [dcl.typedef]p9: [P1766R1, applied as DR] | ||||||
4482 | // An unnamed class with a typedef name for linkage purposes shall [be | ||||||
4483 | // C-like]. | ||||||
4484 | // | ||||||
4485 | // FIXME: Also diagnose if we've already computed the linkage. That ideally | ||||||
4486 | // shouldn't happen, but there are constructs that the language rule doesn't | ||||||
4487 | // disallow for which we can't reasonably avoid computing linkage early. | ||||||
4488 | const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); | ||||||
4489 | NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) | ||||||
4490 | : NonCLikeKind(); | ||||||
4491 | bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); | ||||||
4492 | if (NonCLike || ChangesLinkage) { | ||||||
4493 | if (NonCLike.Kind == NonCLikeKind::Invalid) | ||||||
4494 | return; | ||||||
4495 | |||||||
4496 | unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; | ||||||
4497 | if (ChangesLinkage) { | ||||||
4498 | // If the linkage changes, we can't accept this as an extension. | ||||||
4499 | if (NonCLike.Kind == NonCLikeKind::None) | ||||||
4500 | DiagID = diag::err_typedef_changes_linkage; | ||||||
4501 | else | ||||||
4502 | DiagID = diag::err_non_c_like_anon_struct_in_typedef; | ||||||
4503 | } | ||||||
4504 | |||||||
4505 | SourceLocation FixitLoc = | ||||||
4506 | getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); | ||||||
4507 | llvm::SmallString<40> TextToInsert; | ||||||
4508 | TextToInsert += ' '; | ||||||
4509 | TextToInsert += NewTD->getIdentifier()->getName(); | ||||||
4510 | |||||||
4511 | Diag(FixitLoc, DiagID) | ||||||
4512 | << isa<TypeAliasDecl>(NewTD) | ||||||
4513 | << FixItHint::CreateInsertion(FixitLoc, TextToInsert); | ||||||
4514 | if (NonCLike.Kind != NonCLikeKind::None) { | ||||||
4515 | Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) | ||||||
4516 | << NonCLike.Kind - 1 << NonCLike.Range; | ||||||
4517 | } | ||||||
4518 | Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) | ||||||
4519 | << NewTD << isa<TypeAliasDecl>(NewTD); | ||||||
4520 | |||||||
4521 | if (ChangesLinkage) | ||||||
4522 | return; | ||||||
4523 | } | ||||||
4524 | |||||||
4525 | // Otherwise, set this as the anon-decl typedef for the tag. | ||||||
4526 | TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); | ||||||
4527 | } | ||||||
4528 | |||||||
4529 | static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { | ||||||
4530 | switch (T) { | ||||||
4531 | case DeclSpec::TST_class: | ||||||
4532 | return 0; | ||||||
4533 | case DeclSpec::TST_struct: | ||||||
4534 | return 1; | ||||||
4535 | case DeclSpec::TST_interface: | ||||||
4536 | return 2; | ||||||
4537 | case DeclSpec::TST_union: | ||||||
4538 | return 3; | ||||||
4539 | case DeclSpec::TST_enum: | ||||||
4540 | return 4; | ||||||
4541 | default: | ||||||
4542 | llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4542); | ||||||
4543 | } | ||||||
4544 | } | ||||||
4545 | |||||||
4546 | /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with | ||||||
4547 | /// no declarator (e.g. "struct foo;") is parsed. It also accepts template | ||||||
4548 | /// parameters to cope with template friend declarations. | ||||||
4549 | Decl * | ||||||
4550 | Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, | ||||||
4551 | MultiTemplateParamsArg TemplateParams, | ||||||
4552 | bool IsExplicitInstantiation, | ||||||
4553 | RecordDecl *&AnonRecord) { | ||||||
4554 | Decl *TagD = nullptr; | ||||||
4555 | TagDecl *Tag = nullptr; | ||||||
4556 | if (DS.getTypeSpecType() == DeclSpec::TST_class || | ||||||
4557 | DS.getTypeSpecType() == DeclSpec::TST_struct || | ||||||
4558 | DS.getTypeSpecType() == DeclSpec::TST_interface || | ||||||
4559 | DS.getTypeSpecType() == DeclSpec::TST_union || | ||||||
4560 | DS.getTypeSpecType() == DeclSpec::TST_enum) { | ||||||
4561 | TagD = DS.getRepAsDecl(); | ||||||
4562 | |||||||
4563 | if (!TagD) // We probably had an error | ||||||
4564 | return nullptr; | ||||||
4565 | |||||||
4566 | // Note that the above type specs guarantee that the | ||||||
4567 | // type rep is a Decl, whereas in many of the others | ||||||
4568 | // it's a Type. | ||||||
4569 | if (isa<TagDecl>(TagD)) | ||||||
4570 | Tag = cast<TagDecl>(TagD); | ||||||
4571 | else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) | ||||||
4572 | Tag = CTD->getTemplatedDecl(); | ||||||
4573 | } | ||||||
4574 | |||||||
4575 | if (Tag) { | ||||||
4576 | handleTagNumbering(Tag, S); | ||||||
4577 | Tag->setFreeStanding(); | ||||||
4578 | if (Tag->isInvalidDecl()) | ||||||
4579 | return Tag; | ||||||
4580 | } | ||||||
4581 | |||||||
4582 | if (unsigned TypeQuals = DS.getTypeQualifiers()) { | ||||||
4583 | // Enforce C99 6.7.3p2: "Types other than pointer types derived from object | ||||||
4584 | // or incomplete types shall not be restrict-qualified." | ||||||
4585 | if (TypeQuals & DeclSpec::TQ_restrict) | ||||||
4586 | Diag(DS.getRestrictSpecLoc(), | ||||||
4587 | diag::err_typecheck_invalid_restrict_not_pointer_noarg) | ||||||
4588 | << DS.getSourceRange(); | ||||||
4589 | } | ||||||
4590 | |||||||
4591 | if (DS.isInlineSpecified()) | ||||||
4592 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
4593 | << getLangOpts().CPlusPlus17; | ||||||
4594 | |||||||
4595 | if (DS.hasConstexprSpecifier()) { | ||||||
4596 | // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations | ||||||
4597 | // and definitions of functions and variables. | ||||||
4598 | // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to | ||||||
4599 | // the declaration of a function or function template | ||||||
4600 | if (Tag) | ||||||
4601 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) | ||||||
4602 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) | ||||||
4603 | << DS.getConstexprSpecifier(); | ||||||
4604 | else | ||||||
4605 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) | ||||||
4606 | << DS.getConstexprSpecifier(); | ||||||
4607 | // Don't emit warnings after this error. | ||||||
4608 | return TagD; | ||||||
4609 | } | ||||||
4610 | |||||||
4611 | DiagnoseFunctionSpecifiers(DS); | ||||||
4612 | |||||||
4613 | if (DS.isFriendSpecified()) { | ||||||
4614 | // If we're dealing with a decl but not a TagDecl, assume that | ||||||
4615 | // whatever routines created it handled the friendship aspect. | ||||||
4616 | if (TagD && !Tag) | ||||||
4617 | return nullptr; | ||||||
4618 | return ActOnFriendTypeDecl(S, DS, TemplateParams); | ||||||
4619 | } | ||||||
4620 | |||||||
4621 | const CXXScopeSpec &SS = DS.getTypeSpecScope(); | ||||||
4622 | bool IsExplicitSpecialization = | ||||||
4623 | !TemplateParams.empty() && TemplateParams.back()->size() == 0; | ||||||
4624 | if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && | ||||||
4625 | !IsExplicitInstantiation && !IsExplicitSpecialization && | ||||||
4626 | !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { | ||||||
4627 | // Per C++ [dcl.type.elab]p1, a class declaration cannot have a | ||||||
4628 | // nested-name-specifier unless it is an explicit instantiation | ||||||
4629 | // or an explicit specialization. | ||||||
4630 | // | ||||||
4631 | // FIXME: We allow class template partial specializations here too, per the | ||||||
4632 | // obvious intent of DR1819. | ||||||
4633 | // | ||||||
4634 | // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. | ||||||
4635 | Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) | ||||||
4636 | << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); | ||||||
4637 | return nullptr; | ||||||
4638 | } | ||||||
4639 | |||||||
4640 | // Track whether this decl-specifier declares anything. | ||||||
4641 | bool DeclaresAnything = true; | ||||||
4642 | |||||||
4643 | // Handle anonymous struct definitions. | ||||||
4644 | if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { | ||||||
4645 | if (!Record->getDeclName() && Record->isCompleteDefinition() && | ||||||
4646 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { | ||||||
4647 | if (getLangOpts().CPlusPlus || | ||||||
4648 | Record->getDeclContext()->isRecord()) { | ||||||
4649 | // If CurContext is a DeclContext that can contain statements, | ||||||
4650 | // RecursiveASTVisitor won't visit the decls that | ||||||
4651 | // BuildAnonymousStructOrUnion() will put into CurContext. | ||||||
4652 | // Also store them here so that they can be part of the | ||||||
4653 | // DeclStmt that gets created in this case. | ||||||
4654 | // FIXME: Also return the IndirectFieldDecls created by | ||||||
4655 | // BuildAnonymousStructOr union, for the same reason? | ||||||
4656 | if (CurContext->isFunctionOrMethod()) | ||||||
4657 | AnonRecord = Record; | ||||||
4658 | return BuildAnonymousStructOrUnion(S, DS, AS, Record, | ||||||
4659 | Context.getPrintingPolicy()); | ||||||
4660 | } | ||||||
4661 | |||||||
4662 | DeclaresAnything = false; | ||||||
4663 | } | ||||||
4664 | } | ||||||
4665 | |||||||
4666 | // C11 6.7.2.1p2: | ||||||
4667 | // A struct-declaration that does not declare an anonymous structure or | ||||||
4668 | // anonymous union shall contain a struct-declarator-list. | ||||||
4669 | // | ||||||
4670 | // This rule also existed in C89 and C99; the grammar for struct-declaration | ||||||
4671 | // did not permit a struct-declaration without a struct-declarator-list. | ||||||
4672 | if (!getLangOpts().CPlusPlus && CurContext->isRecord() && | ||||||
4673 | DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { | ||||||
4674 | // Check for Microsoft C extension: anonymous struct/union member. | ||||||
4675 | // Handle 2 kinds of anonymous struct/union: | ||||||
4676 | // struct STRUCT; | ||||||
4677 | // union UNION; | ||||||
4678 | // and | ||||||
4679 | // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. | ||||||
4680 | // UNION_TYPE; <- where UNION_TYPE is a typedef union. | ||||||
4681 | if ((Tag && Tag->getDeclName()) || | ||||||
4682 | DS.getTypeSpecType() == DeclSpec::TST_typename) { | ||||||
4683 | RecordDecl *Record = nullptr; | ||||||
4684 | if (Tag) | ||||||
4685 | Record = dyn_cast<RecordDecl>(Tag); | ||||||
4686 | else if (const RecordType *RT = | ||||||
4687 | DS.getRepAsType().get()->getAsStructureType()) | ||||||
4688 | Record = RT->getDecl(); | ||||||
4689 | else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) | ||||||
4690 | Record = UT->getDecl(); | ||||||
4691 | |||||||
4692 | if (Record && getLangOpts().MicrosoftExt) { | ||||||
4693 | Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) | ||||||
4694 | << Record->isUnion() << DS.getSourceRange(); | ||||||
4695 | return BuildMicrosoftCAnonymousStruct(S, DS, Record); | ||||||
4696 | } | ||||||
4697 | |||||||
4698 | DeclaresAnything = false; | ||||||
4699 | } | ||||||
4700 | } | ||||||
4701 | |||||||
4702 | // Skip all the checks below if we have a type error. | ||||||
4703 | if (DS.getTypeSpecType() == DeclSpec::TST_error || | ||||||
4704 | (TagD && TagD->isInvalidDecl())) | ||||||
4705 | return TagD; | ||||||
4706 | |||||||
4707 | if (getLangOpts().CPlusPlus && | ||||||
4708 | DS.getStorageClassSpec() != DeclSpec::SCS_typedef) | ||||||
4709 | if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) | ||||||
4710 | if (Enum->enumerator_begin() == Enum->enumerator_end() && | ||||||
4711 | !Enum->getIdentifier() && !Enum->isInvalidDecl()) | ||||||
4712 | DeclaresAnything = false; | ||||||
4713 | |||||||
4714 | if (!DS.isMissingDeclaratorOk()) { | ||||||
4715 | // Customize diagnostic for a typedef missing a name. | ||||||
4716 | if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||||
4717 | Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) | ||||||
4718 | << DS.getSourceRange(); | ||||||
4719 | else | ||||||
4720 | DeclaresAnything = false; | ||||||
4721 | } | ||||||
4722 | |||||||
4723 | if (DS.isModulePrivateSpecified() && | ||||||
4724 | Tag && Tag->getDeclContext()->isFunctionOrMethod()) | ||||||
4725 | Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) | ||||||
4726 | << Tag->getTagKind() | ||||||
4727 | << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); | ||||||
4728 | |||||||
4729 | ActOnDocumentableDecl(TagD); | ||||||
4730 | |||||||
4731 | // C 6.7/2: | ||||||
4732 | // A declaration [...] shall declare at least a declarator [...], a tag, | ||||||
4733 | // or the members of an enumeration. | ||||||
4734 | // C++ [dcl.dcl]p3: | ||||||
4735 | // [If there are no declarators], and except for the declaration of an | ||||||
4736 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||||
4737 | // names into the program, or shall redeclare a name introduced by a | ||||||
4738 | // previous declaration. | ||||||
4739 | if (!DeclaresAnything) { | ||||||
4740 | // In C, we allow this as a (popular) extension / bug. Don't bother | ||||||
4741 | // producing further diagnostics for redundant qualifiers after this. | ||||||
4742 | Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty()) | ||||||
4743 | ? diag::err_no_declarators | ||||||
4744 | : diag::ext_no_declarators) | ||||||
4745 | << DS.getSourceRange(); | ||||||
4746 | return TagD; | ||||||
4747 | } | ||||||
4748 | |||||||
4749 | // C++ [dcl.stc]p1: | ||||||
4750 | // If a storage-class-specifier appears in a decl-specifier-seq, [...] the | ||||||
4751 | // init-declarator-list of the declaration shall not be empty. | ||||||
4752 | // C++ [dcl.fct.spec]p1: | ||||||
4753 | // If a cv-qualifier appears in a decl-specifier-seq, the | ||||||
4754 | // init-declarator-list of the declaration shall not be empty. | ||||||
4755 | // | ||||||
4756 | // Spurious qualifiers here appear to be valid in C. | ||||||
4757 | unsigned DiagID = diag::warn_standalone_specifier; | ||||||
4758 | if (getLangOpts().CPlusPlus) | ||||||
4759 | DiagID = diag::ext_standalone_specifier; | ||||||
4760 | |||||||
4761 | // Note that a linkage-specification sets a storage class, but | ||||||
4762 | // 'extern "C" struct foo;' is actually valid and not theoretically | ||||||
4763 | // useless. | ||||||
4764 | if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { | ||||||
4765 | if (SCS == DeclSpec::SCS_mutable) | ||||||
4766 | // Since mutable is not a viable storage class specifier in C, there is | ||||||
4767 | // no reason to treat it as an extension. Instead, diagnose as an error. | ||||||
4768 | Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); | ||||||
4769 | else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) | ||||||
4770 | Diag(DS.getStorageClassSpecLoc(), DiagID) | ||||||
4771 | << DeclSpec::getSpecifierName(SCS); | ||||||
4772 | } | ||||||
4773 | |||||||
4774 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||||
4775 | Diag(DS.getThreadStorageClassSpecLoc(), DiagID) | ||||||
4776 | << DeclSpec::getSpecifierName(TSCS); | ||||||
4777 | if (DS.getTypeQualifiers()) { | ||||||
4778 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||||
4779 | Diag(DS.getConstSpecLoc(), DiagID) << "const"; | ||||||
4780 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||||
4781 | Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; | ||||||
4782 | // Restrict is covered above. | ||||||
4783 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||||
4784 | Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; | ||||||
4785 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||||
4786 | Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; | ||||||
4787 | } | ||||||
4788 | |||||||
4789 | // Warn about ignored type attributes, for example: | ||||||
4790 | // __attribute__((aligned)) struct A; | ||||||
4791 | // Attributes should be placed after tag to apply to type declaration. | ||||||
4792 | if (!DS.getAttributes().empty()) { | ||||||
4793 | DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); | ||||||
4794 | if (TypeSpecType == DeclSpec::TST_class || | ||||||
4795 | TypeSpecType == DeclSpec::TST_struct || | ||||||
4796 | TypeSpecType == DeclSpec::TST_interface || | ||||||
4797 | TypeSpecType == DeclSpec::TST_union || | ||||||
4798 | TypeSpecType == DeclSpec::TST_enum) { | ||||||
4799 | for (const ParsedAttr &AL : DS.getAttributes()) | ||||||
4800 | Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) | ||||||
4801 | << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); | ||||||
4802 | } | ||||||
4803 | } | ||||||
4804 | |||||||
4805 | return TagD; | ||||||
4806 | } | ||||||
4807 | |||||||
4808 | /// We are trying to inject an anonymous member into the given scope; | ||||||
4809 | /// check if there's an existing declaration that can't be overloaded. | ||||||
4810 | /// | ||||||
4811 | /// \return true if this is a forbidden redeclaration | ||||||
4812 | static bool CheckAnonMemberRedeclaration(Sema &SemaRef, | ||||||
4813 | Scope *S, | ||||||
4814 | DeclContext *Owner, | ||||||
4815 | DeclarationName Name, | ||||||
4816 | SourceLocation NameLoc, | ||||||
4817 | bool IsUnion) { | ||||||
4818 | LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, | ||||||
4819 | Sema::ForVisibleRedeclaration); | ||||||
4820 | if (!SemaRef.LookupName(R, S)) return false; | ||||||
4821 | |||||||
4822 | // Pick a representative declaration. | ||||||
4823 | NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); | ||||||
4824 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4824, __PRETTY_FUNCTION__)); | ||||||
4825 | |||||||
4826 | if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) | ||||||
4827 | return false; | ||||||
4828 | |||||||
4829 | SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) | ||||||
4830 | << IsUnion << Name; | ||||||
4831 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
4832 | |||||||
4833 | return true; | ||||||
4834 | } | ||||||
4835 | |||||||
4836 | /// InjectAnonymousStructOrUnionMembers - Inject the members of the | ||||||
4837 | /// anonymous struct or union AnonRecord into the owning context Owner | ||||||
4838 | /// and scope S. This routine will be invoked just after we realize | ||||||
4839 | /// that an unnamed union or struct is actually an anonymous union or | ||||||
4840 | /// struct, e.g., | ||||||
4841 | /// | ||||||
4842 | /// @code | ||||||
4843 | /// union { | ||||||
4844 | /// int i; | ||||||
4845 | /// float f; | ||||||
4846 | /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and | ||||||
4847 | /// // f into the surrounding scope.x | ||||||
4848 | /// @endcode | ||||||
4849 | /// | ||||||
4850 | /// This routine is recursive, injecting the names of nested anonymous | ||||||
4851 | /// structs/unions into the owning context and scope as well. | ||||||
4852 | static bool | ||||||
4853 | InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, | ||||||
4854 | RecordDecl *AnonRecord, AccessSpecifier AS, | ||||||
4855 | SmallVectorImpl<NamedDecl *> &Chaining) { | ||||||
4856 | bool Invalid = false; | ||||||
4857 | |||||||
4858 | // Look every FieldDecl and IndirectFieldDecl with a name. | ||||||
4859 | for (auto *D : AnonRecord->decls()) { | ||||||
4860 | if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && | ||||||
4861 | cast<NamedDecl>(D)->getDeclName()) { | ||||||
4862 | ValueDecl *VD = cast<ValueDecl>(D); | ||||||
4863 | if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), | ||||||
4864 | VD->getLocation(), | ||||||
4865 | AnonRecord->isUnion())) { | ||||||
4866 | // C++ [class.union]p2: | ||||||
4867 | // The names of the members of an anonymous union shall be | ||||||
4868 | // distinct from the names of any other entity in the | ||||||
4869 | // scope in which the anonymous union is declared. | ||||||
4870 | Invalid = true; | ||||||
4871 | } else { | ||||||
4872 | // C++ [class.union]p2: | ||||||
4873 | // For the purpose of name lookup, after the anonymous union | ||||||
4874 | // definition, the members of the anonymous union are | ||||||
4875 | // considered to have been defined in the scope in which the | ||||||
4876 | // anonymous union is declared. | ||||||
4877 | unsigned OldChainingSize = Chaining.size(); | ||||||
4878 | if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) | ||||||
4879 | Chaining.append(IF->chain_begin(), IF->chain_end()); | ||||||
4880 | else | ||||||
4881 | Chaining.push_back(VD); | ||||||
4882 | |||||||
4883 | assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4883, __PRETTY_FUNCTION__)); | ||||||
4884 | NamedDecl **NamedChain = | ||||||
4885 | new (SemaRef.Context)NamedDecl*[Chaining.size()]; | ||||||
4886 | for (unsigned i = 0; i < Chaining.size(); i++) | ||||||
4887 | NamedChain[i] = Chaining[i]; | ||||||
4888 | |||||||
4889 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( | ||||||
4890 | SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), | ||||||
4891 | VD->getType(), {NamedChain, Chaining.size()}); | ||||||
4892 | |||||||
4893 | for (const auto *Attr : VD->attrs()) | ||||||
4894 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); | ||||||
4895 | |||||||
4896 | IndirectField->setAccess(AS); | ||||||
4897 | IndirectField->setImplicit(); | ||||||
4898 | SemaRef.PushOnScopeChains(IndirectField, S); | ||||||
4899 | |||||||
4900 | // That includes picking up the appropriate access specifier. | ||||||
4901 | if (AS != AS_none) IndirectField->setAccess(AS); | ||||||
4902 | |||||||
4903 | Chaining.resize(OldChainingSize); | ||||||
4904 | } | ||||||
4905 | } | ||||||
4906 | } | ||||||
4907 | |||||||
4908 | return Invalid; | ||||||
4909 | } | ||||||
4910 | |||||||
4911 | /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to | ||||||
4912 | /// a VarDecl::StorageClass. Any error reporting is up to the caller: | ||||||
4913 | /// illegal input values are mapped to SC_None. | ||||||
4914 | static StorageClass | ||||||
4915 | StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { | ||||||
4916 | DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); | ||||||
4917 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4918, __PRETTY_FUNCTION__)) | ||||||
4918 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4918, __PRETTY_FUNCTION__)); | ||||||
4919 | switch (StorageClassSpec) { | ||||||
4920 | case DeclSpec::SCS_unspecified: return SC_None; | ||||||
4921 | case DeclSpec::SCS_extern: | ||||||
4922 | if (DS.isExternInLinkageSpec()) | ||||||
4923 | return SC_None; | ||||||
4924 | return SC_Extern; | ||||||
4925 | case DeclSpec::SCS_static: return SC_Static; | ||||||
4926 | case DeclSpec::SCS_auto: return SC_Auto; | ||||||
4927 | case DeclSpec::SCS_register: return SC_Register; | ||||||
4928 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||||
4929 | // Illegal SCSs map to None: error reporting is up to the caller. | ||||||
4930 | case DeclSpec::SCS_mutable: // Fall through. | ||||||
4931 | case DeclSpec::SCS_typedef: return SC_None; | ||||||
4932 | } | ||||||
4933 | llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4933); | ||||||
4934 | } | ||||||
4935 | |||||||
4936 | static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { | ||||||
4937 | assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void> (0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4937, __PRETTY_FUNCTION__)); | ||||||
4938 | |||||||
4939 | for (const auto *I : Record->decls()) { | ||||||
4940 | const auto *FD = dyn_cast<FieldDecl>(I); | ||||||
4941 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||||
4942 | FD = IFD->getAnonField(); | ||||||
4943 | if (FD && FD->hasInClassInitializer()) | ||||||
4944 | return FD->getLocation(); | ||||||
4945 | } | ||||||
4946 | |||||||
4947 | llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 4947); | ||||||
4948 | } | ||||||
4949 | |||||||
4950 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||||
4951 | SourceLocation DefaultInitLoc) { | ||||||
4952 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||||
4953 | return; | ||||||
4954 | |||||||
4955 | S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); | ||||||
4956 | S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; | ||||||
4957 | } | ||||||
4958 | |||||||
4959 | static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, | ||||||
4960 | CXXRecordDecl *AnonUnion) { | ||||||
4961 | if (!Parent->isUnion() || !Parent->hasInClassInitializer()) | ||||||
4962 | return; | ||||||
4963 | |||||||
4964 | checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); | ||||||
4965 | } | ||||||
4966 | |||||||
4967 | /// BuildAnonymousStructOrUnion - Handle the declaration of an | ||||||
4968 | /// anonymous structure or union. Anonymous unions are a C++ feature | ||||||
4969 | /// (C++ [class.union]) and a C11 feature; anonymous structures | ||||||
4970 | /// are a C11 feature and GNU C++ extension. | ||||||
4971 | Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, | ||||||
4972 | AccessSpecifier AS, | ||||||
4973 | RecordDecl *Record, | ||||||
4974 | const PrintingPolicy &Policy) { | ||||||
4975 | DeclContext *Owner = Record->getDeclContext(); | ||||||
4976 | |||||||
4977 | // Diagnose whether this anonymous struct/union is an extension. | ||||||
4978 | if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) | ||||||
4979 | Diag(Record->getLocation(), diag::ext_anonymous_union); | ||||||
4980 | else if (!Record->isUnion() && getLangOpts().CPlusPlus) | ||||||
4981 | Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); | ||||||
4982 | else if (!Record->isUnion() && !getLangOpts().C11) | ||||||
4983 | Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); | ||||||
4984 | |||||||
4985 | // C and C++ require different kinds of checks for anonymous | ||||||
4986 | // structs/unions. | ||||||
4987 | bool Invalid = false; | ||||||
4988 | if (getLangOpts().CPlusPlus) { | ||||||
4989 | const char *PrevSpec = nullptr; | ||||||
4990 | if (Record->isUnion()) { | ||||||
4991 | // C++ [class.union]p6: | ||||||
4992 | // C++17 [class.union.anon]p2: | ||||||
4993 | // Anonymous unions declared in a named namespace or in the | ||||||
4994 | // global namespace shall be declared static. | ||||||
4995 | unsigned DiagID; | ||||||
4996 | DeclContext *OwnerScope = Owner->getRedeclContext(); | ||||||
4997 | if (DS.getStorageClassSpec() != DeclSpec::SCS_static && | ||||||
4998 | (OwnerScope->isTranslationUnit() || | ||||||
4999 | (OwnerScope->isNamespace() && | ||||||
5000 | !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { | ||||||
5001 | Diag(Record->getLocation(), diag::err_anonymous_union_not_static) | ||||||
5002 | << FixItHint::CreateInsertion(Record->getLocation(), "static "); | ||||||
5003 | |||||||
5004 | // Recover by adding 'static'. | ||||||
5005 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), | ||||||
5006 | PrevSpec, DiagID, Policy); | ||||||
5007 | } | ||||||
5008 | // C++ [class.union]p6: | ||||||
5009 | // A storage class is not allowed in a declaration of an | ||||||
5010 | // anonymous union in a class scope. | ||||||
5011 | else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && | ||||||
5012 | isa<RecordDecl>(Owner)) { | ||||||
5013 | Diag(DS.getStorageClassSpecLoc(), | ||||||
5014 | diag::err_anonymous_union_with_storage_spec) | ||||||
5015 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
5016 | |||||||
5017 | // Recover by removing the storage specifier. | ||||||
5018 | DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, | ||||||
5019 | SourceLocation(), | ||||||
5020 | PrevSpec, DiagID, Context.getPrintingPolicy()); | ||||||
5021 | } | ||||||
5022 | } | ||||||
5023 | |||||||
5024 | // Ignore const/volatile/restrict qualifiers. | ||||||
5025 | if (DS.getTypeQualifiers()) { | ||||||
5026 | if (DS.getTypeQualifiers() & DeclSpec::TQ_const) | ||||||
5027 | Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) | ||||||
5028 | << Record->isUnion() << "const" | ||||||
5029 | << FixItHint::CreateRemoval(DS.getConstSpecLoc()); | ||||||
5030 | if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) | ||||||
5031 | Diag(DS.getVolatileSpecLoc(), | ||||||
5032 | diag::ext_anonymous_struct_union_qualified) | ||||||
5033 | << Record->isUnion() << "volatile" | ||||||
5034 | << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); | ||||||
5035 | if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) | ||||||
5036 | Diag(DS.getRestrictSpecLoc(), | ||||||
5037 | diag::ext_anonymous_struct_union_qualified) | ||||||
5038 | << Record->isUnion() << "restrict" | ||||||
5039 | << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); | ||||||
5040 | if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) | ||||||
5041 | Diag(DS.getAtomicSpecLoc(), | ||||||
5042 | diag::ext_anonymous_struct_union_qualified) | ||||||
5043 | << Record->isUnion() << "_Atomic" | ||||||
5044 | << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); | ||||||
5045 | if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) | ||||||
5046 | Diag(DS.getUnalignedSpecLoc(), | ||||||
5047 | diag::ext_anonymous_struct_union_qualified) | ||||||
5048 | << Record->isUnion() << "__unaligned" | ||||||
5049 | << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); | ||||||
5050 | |||||||
5051 | DS.ClearTypeQualifiers(); | ||||||
5052 | } | ||||||
5053 | |||||||
5054 | // C++ [class.union]p2: | ||||||
5055 | // The member-specification of an anonymous union shall only | ||||||
5056 | // define non-static data members. [Note: nested types and | ||||||
5057 | // functions cannot be declared within an anonymous union. ] | ||||||
5058 | for (auto *Mem : Record->decls()) { | ||||||
5059 | // Ignore invalid declarations; we already diagnosed them. | ||||||
5060 | if (Mem->isInvalidDecl()) | ||||||
5061 | continue; | ||||||
5062 | |||||||
5063 | if (auto *FD = dyn_cast<FieldDecl>(Mem)) { | ||||||
5064 | // C++ [class.union]p3: | ||||||
5065 | // An anonymous union shall not have private or protected | ||||||
5066 | // members (clause 11). | ||||||
5067 | assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0 ) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 5067, __PRETTY_FUNCTION__)); | ||||||
5068 | if (FD->getAccess() != AS_public) { | ||||||
5069 | Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) | ||||||
5070 | << Record->isUnion() << (FD->getAccess() == AS_protected); | ||||||
5071 | Invalid = true; | ||||||
5072 | } | ||||||
5073 | |||||||
5074 | // C++ [class.union]p1 | ||||||
5075 | // An object of a class with a non-trivial constructor, a non-trivial | ||||||
5076 | // copy constructor, a non-trivial destructor, or a non-trivial copy | ||||||
5077 | // assignment operator cannot be a member of a union, nor can an | ||||||
5078 | // array of such objects. | ||||||
5079 | if (CheckNontrivialField(FD)) | ||||||
5080 | Invalid = true; | ||||||
5081 | } else if (Mem->isImplicit()) { | ||||||
5082 | // Any implicit members are fine. | ||||||
5083 | } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { | ||||||
5084 | // This is a type that showed up in an | ||||||
5085 | // elaborated-type-specifier inside the anonymous struct or | ||||||
5086 | // union, but which actually declares a type outside of the | ||||||
5087 | // anonymous struct or union. It's okay. | ||||||
5088 | } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { | ||||||
5089 | if (!MemRecord->isAnonymousStructOrUnion() && | ||||||
5090 | MemRecord->getDeclName()) { | ||||||
5091 | // Visual C++ allows type definition in anonymous struct or union. | ||||||
5092 | if (getLangOpts().MicrosoftExt) | ||||||
5093 | Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) | ||||||
5094 | << Record->isUnion(); | ||||||
5095 | else { | ||||||
5096 | // This is a nested type declaration. | ||||||
5097 | Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) | ||||||
5098 | << Record->isUnion(); | ||||||
5099 | Invalid = true; | ||||||
5100 | } | ||||||
5101 | } else { | ||||||
5102 | // This is an anonymous type definition within another anonymous type. | ||||||
5103 | // This is a popular extension, provided by Plan9, MSVC and GCC, but | ||||||
5104 | // not part of standard C++. | ||||||
5105 | Diag(MemRecord->getLocation(), | ||||||
5106 | diag::ext_anonymous_record_with_anonymous_type) | ||||||
5107 | << Record->isUnion(); | ||||||
5108 | } | ||||||
5109 | } else if (isa<AccessSpecDecl>(Mem)) { | ||||||
5110 | // Any access specifier is fine. | ||||||
5111 | } else if (isa<StaticAssertDecl>(Mem)) { | ||||||
5112 | // In C++1z, static_assert declarations are also fine. | ||||||
5113 | } else { | ||||||
5114 | // We have something that isn't a non-static data | ||||||
5115 | // member. Complain about it. | ||||||
5116 | unsigned DK = diag::err_anonymous_record_bad_member; | ||||||
5117 | if (isa<TypeDecl>(Mem)) | ||||||
5118 | DK = diag::err_anonymous_record_with_type; | ||||||
5119 | else if (isa<FunctionDecl>(Mem)) | ||||||
5120 | DK = diag::err_anonymous_record_with_function; | ||||||
5121 | else if (isa<VarDecl>(Mem)) | ||||||
5122 | DK = diag::err_anonymous_record_with_static; | ||||||
5123 | |||||||
5124 | // Visual C++ allows type definition in anonymous struct or union. | ||||||
5125 | if (getLangOpts().MicrosoftExt && | ||||||
5126 | DK == diag::err_anonymous_record_with_type) | ||||||
5127 | Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) | ||||||
5128 | << Record->isUnion(); | ||||||
5129 | else { | ||||||
5130 | Diag(Mem->getLocation(), DK) << Record->isUnion(); | ||||||
5131 | Invalid = true; | ||||||
5132 | } | ||||||
5133 | } | ||||||
5134 | } | ||||||
5135 | |||||||
5136 | // C++11 [class.union]p8 (DR1460): | ||||||
5137 | // At most one variant member of a union may have a | ||||||
5138 | // brace-or-equal-initializer. | ||||||
5139 | if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && | ||||||
5140 | Owner->isRecord()) | ||||||
5141 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), | ||||||
5142 | cast<CXXRecordDecl>(Record)); | ||||||
5143 | } | ||||||
5144 | |||||||
5145 | if (!Record->isUnion() && !Owner->isRecord()) { | ||||||
5146 | Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) | ||||||
5147 | << getLangOpts().CPlusPlus; | ||||||
5148 | Invalid = true; | ||||||
5149 | } | ||||||
5150 | |||||||
5151 | // C++ [dcl.dcl]p3: | ||||||
5152 | // [If there are no declarators], and except for the declaration of an | ||||||
5153 | // unnamed bit-field, the decl-specifier-seq shall introduce one or more | ||||||
5154 | // names into the program | ||||||
5155 | // C++ [class.mem]p2: | ||||||
5156 | // each such member-declaration shall either declare at least one member | ||||||
5157 | // name of the class or declare at least one unnamed bit-field | ||||||
5158 | // | ||||||
5159 | // For C this is an error even for a named struct, and is diagnosed elsewhere. | ||||||
5160 | if (getLangOpts().CPlusPlus && Record->field_empty()) | ||||||
5161 | Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); | ||||||
5162 | |||||||
5163 | // Mock up a declarator. | ||||||
5164 | Declarator Dc(DS, DeclaratorContext::MemberContext); | ||||||
5165 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||||
5166 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 5166, __PRETTY_FUNCTION__)); | ||||||
5167 | |||||||
5168 | // Create a declaration for this anonymous struct/union. | ||||||
5169 | NamedDecl *Anon = nullptr; | ||||||
5170 | if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { | ||||||
5171 | Anon = FieldDecl::Create( | ||||||
5172 | Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), | ||||||
5173 | /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, | ||||||
5174 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||||
5175 | /*InitStyle=*/ICIS_NoInit); | ||||||
5176 | Anon->setAccess(AS); | ||||||
5177 | ProcessDeclAttributes(S, Anon, Dc); | ||||||
5178 | |||||||
5179 | if (getLangOpts().CPlusPlus) | ||||||
5180 | FieldCollector->Add(cast<FieldDecl>(Anon)); | ||||||
5181 | } else { | ||||||
5182 | DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); | ||||||
5183 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); | ||||||
5184 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||||
5185 | // mutable can only appear on non-static class members, so it's always | ||||||
5186 | // an error here | ||||||
5187 | Diag(Record->getLocation(), diag::err_mutable_nonmember); | ||||||
5188 | Invalid = true; | ||||||
5189 | SC = SC_None; | ||||||
5190 | } | ||||||
5191 | |||||||
5192 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 5192, __PRETTY_FUNCTION__)); | ||||||
5193 | Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), | ||||||
5194 | Record->getLocation(), /*IdentifierInfo=*/nullptr, | ||||||
5195 | Context.getTypeDeclType(Record), TInfo, SC); | ||||||
5196 | |||||||
5197 | // Default-initialize the implicit variable. This initialization will be | ||||||
5198 | // trivial in almost all cases, except if a union member has an in-class | ||||||
5199 | // initializer: | ||||||
5200 | // union { int n = 0; }; | ||||||
5201 | ActOnUninitializedDecl(Anon); | ||||||
5202 | } | ||||||
5203 | Anon->setImplicit(); | ||||||
5204 | |||||||
5205 | // Mark this as an anonymous struct/union type. | ||||||
5206 | Record->setAnonymousStructOrUnion(true); | ||||||
5207 | |||||||
5208 | // Add the anonymous struct/union object to the current | ||||||
5209 | // context. We'll be referencing this object when we refer to one of | ||||||
5210 | // its members. | ||||||
5211 | Owner->addDecl(Anon); | ||||||
5212 | |||||||
5213 | // Inject the members of the anonymous struct/union into the owning | ||||||
5214 | // context and into the identifier resolver chain for name lookup | ||||||
5215 | // purposes. | ||||||
5216 | SmallVector<NamedDecl*, 2> Chain; | ||||||
5217 | Chain.push_back(Anon); | ||||||
5218 | |||||||
5219 | if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) | ||||||
5220 | Invalid = true; | ||||||
5221 | |||||||
5222 | if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { | ||||||
5223 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||||
5224 | MangleNumberingContext *MCtx; | ||||||
5225 | Decl *ManglingContextDecl; | ||||||
5226 | std::tie(MCtx, ManglingContextDecl) = | ||||||
5227 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | ||||||
5228 | if (MCtx) { | ||||||
5229 | Context.setManglingNumber( | ||||||
5230 | NewVD, MCtx->getManglingNumber( | ||||||
5231 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||||
5232 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||||
5233 | } | ||||||
5234 | } | ||||||
5235 | } | ||||||
5236 | |||||||
5237 | if (Invalid) | ||||||
5238 | Anon->setInvalidDecl(); | ||||||
5239 | |||||||
5240 | return Anon; | ||||||
5241 | } | ||||||
5242 | |||||||
5243 | /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an | ||||||
5244 | /// Microsoft C anonymous structure. | ||||||
5245 | /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx | ||||||
5246 | /// Example: | ||||||
5247 | /// | ||||||
5248 | /// struct A { int a; }; | ||||||
5249 | /// struct B { struct A; int b; }; | ||||||
5250 | /// | ||||||
5251 | /// void foo() { | ||||||
5252 | /// B var; | ||||||
5253 | /// var.a = 3; | ||||||
5254 | /// } | ||||||
5255 | /// | ||||||
5256 | Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, | ||||||
5257 | RecordDecl *Record) { | ||||||
5258 | assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void > (0) : __assert_fail ("Record && \"expected a record!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 5258, __PRETTY_FUNCTION__)); | ||||||
5259 | |||||||
5260 | // Mock up a declarator. | ||||||
5261 | Declarator Dc(DS, DeclaratorContext::TypeNameContext); | ||||||
5262 | TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); | ||||||
5263 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 5263, __PRETTY_FUNCTION__)); | ||||||
5264 | |||||||
5265 | auto *ParentDecl = cast<RecordDecl>(CurContext); | ||||||
5266 | QualType RecTy = Context.getTypeDeclType(Record); | ||||||
5267 | |||||||
5268 | // Create a declaration for this anonymous struct. | ||||||
5269 | NamedDecl *Anon = | ||||||
5270 | FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), | ||||||
5271 | /*IdentifierInfo=*/nullptr, RecTy, TInfo, | ||||||
5272 | /*BitWidth=*/nullptr, /*Mutable=*/false, | ||||||
5273 | /*InitStyle=*/ICIS_NoInit); | ||||||
5274 | Anon->setImplicit(); | ||||||
5275 | |||||||
5276 | // Add the anonymous struct object to the current context. | ||||||
5277 | CurContext->addDecl(Anon); | ||||||
5278 | |||||||
5279 | // Inject the members of the anonymous struct into the current | ||||||
5280 | // context and into the identifier resolver chain for name lookup | ||||||
5281 | // purposes. | ||||||
5282 | SmallVector<NamedDecl*, 2> Chain; | ||||||
5283 | Chain.push_back(Anon); | ||||||
5284 | |||||||
5285 | RecordDecl *RecordDef = Record->getDefinition(); | ||||||
5286 | if (RequireCompleteSizedType(Anon->getLocation(), RecTy, | ||||||
5287 | diag::err_field_incomplete_or_sizeless) || | ||||||
5288 | InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, | ||||||
5289 | AS_none, Chain)) { | ||||||
5290 | Anon->setInvalidDecl(); | ||||||
5291 | ParentDecl->setInvalidDecl(); | ||||||
5292 | } | ||||||
5293 | |||||||
5294 | return Anon; | ||||||
5295 | } | ||||||
5296 | |||||||
5297 | /// GetNameForDeclarator - Determine the full declaration name for the | ||||||
5298 | /// given Declarator. | ||||||
5299 | DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { | ||||||
5300 | return GetNameFromUnqualifiedId(D.getName()); | ||||||
5301 | } | ||||||
5302 | |||||||
5303 | /// Retrieves the declaration name from a parsed unqualified-id. | ||||||
5304 | DeclarationNameInfo | ||||||
5305 | Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { | ||||||
5306 | DeclarationNameInfo NameInfo; | ||||||
5307 | NameInfo.setLoc(Name.StartLocation); | ||||||
5308 | |||||||
5309 | switch (Name.getKind()) { | ||||||
5310 | |||||||
5311 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||||
5312 | case UnqualifiedIdKind::IK_Identifier: | ||||||
5313 | NameInfo.setName(Name.Identifier); | ||||||
5314 | return NameInfo; | ||||||
5315 | |||||||
5316 | case UnqualifiedIdKind::IK_DeductionGuideName: { | ||||||
5317 | // C++ [temp.deduct.guide]p3: | ||||||
5318 | // The simple-template-id shall name a class template specialization. | ||||||
5319 | // The template-name shall be the same identifier as the template-name | ||||||
5320 | // of the simple-template-id. | ||||||
5321 | // These together intend to imply that the template-name shall name a | ||||||
5322 | // class template. | ||||||
5323 | // FIXME: template<typename T> struct X {}; | ||||||
5324 | // template<typename T> using Y = X<T>; | ||||||
5325 | // Y(int) -> Y<int>; | ||||||
5326 | // satisfies these rules but does not name a class template. | ||||||
5327 | TemplateName TN = Name.TemplateName.get().get(); | ||||||
5328 | auto *Template = TN.getAsTemplateDecl(); | ||||||
5329 | if (!Template || !isa<ClassTemplateDecl>(Template)) { | ||||||
5330 | Diag(Name.StartLocation, | ||||||
5331 | diag::err_deduction_guide_name_not_class_template) | ||||||
5332 | << (int)getTemplateNameKindForDiagnostics(TN) << TN; | ||||||
5333 | if (Template) | ||||||
5334 | Diag(Template->getLocation(), diag::note_template_decl_here); | ||||||
5335 | return DeclarationNameInfo(); | ||||||
5336 | } | ||||||
5337 | |||||||
5338 | NameInfo.setName( | ||||||
5339 | Context.DeclarationNames.getCXXDeductionGuideName(Template)); | ||||||
5340 | return NameInfo; | ||||||
5341 | } | ||||||
5342 | |||||||
5343 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||||
5344 | NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( | ||||||
5345 | Name.OperatorFunctionId.Operator)); | ||||||
5346 | NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc | ||||||
5347 | = Name.OperatorFunctionId.SymbolLocations[0]; | ||||||
5348 | NameInfo.getInfo().CXXOperatorName.EndOpNameLoc | ||||||
5349 | = Name.EndLocation.getRawEncoding(); | ||||||
5350 | return NameInfo; | ||||||
5351 | |||||||
5352 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||||
5353 | NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( | ||||||
5354 | Name.Identifier)); | ||||||
5355 | NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); | ||||||
5356 | return NameInfo; | ||||||
5357 | |||||||
5358 | case UnqualifiedIdKind::IK_ConversionFunctionId: { | ||||||
5359 | TypeSourceInfo *TInfo; | ||||||
5360 | QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); | ||||||
5361 | if (Ty.isNull()) | ||||||
5362 | return DeclarationNameInfo(); | ||||||
5363 | NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( | ||||||
5364 | Context.getCanonicalType(Ty))); | ||||||
5365 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5366 | return NameInfo; | ||||||
5367 | } | ||||||
5368 | |||||||
5369 | case UnqualifiedIdKind::IK_ConstructorName: { | ||||||
5370 | TypeSourceInfo *TInfo; | ||||||
5371 | QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); | ||||||
5372 | if (Ty.isNull()) | ||||||
5373 | return DeclarationNameInfo(); | ||||||
5374 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||||
5375 | Context.getCanonicalType(Ty))); | ||||||
5376 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5377 | return NameInfo; | ||||||
5378 | } | ||||||
5379 | |||||||
5380 | case UnqualifiedIdKind::IK_ConstructorTemplateId: { | ||||||
5381 | // In well-formed code, we can only have a constructor | ||||||
5382 | // template-id that refers to the current context, so go there | ||||||
5383 | // to find the actual type being constructed. | ||||||
5384 | CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); | ||||||
5385 | if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) | ||||||
5386 | return DeclarationNameInfo(); | ||||||
5387 | |||||||
5388 | // Determine the type of the class being constructed. | ||||||
5389 | QualType CurClassType = Context.getTypeDeclType(CurClass); | ||||||
5390 | |||||||
5391 | // FIXME: Check two things: that the template-id names the same type as | ||||||
5392 | // CurClassType, and that the template-id does not occur when the name | ||||||
5393 | // was qualified. | ||||||
5394 | |||||||
5395 | NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( | ||||||
5396 | Context.getCanonicalType(CurClassType))); | ||||||
5397 | // FIXME: should we retrieve TypeSourceInfo? | ||||||
5398 | NameInfo.setNamedTypeInfo(nullptr); | ||||||
5399 | return NameInfo; | ||||||
5400 | } | ||||||
5401 | |||||||
5402 | case UnqualifiedIdKind::IK_DestructorName: { | ||||||
5403 | TypeSourceInfo *TInfo; | ||||||
5404 | QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); | ||||||
5405 | if (Ty.isNull()) | ||||||
5406 | return DeclarationNameInfo(); | ||||||
5407 | NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( | ||||||
5408 | Context.getCanonicalType(Ty))); | ||||||
5409 | NameInfo.setNamedTypeInfo(TInfo); | ||||||
5410 | return NameInfo; | ||||||
5411 | } | ||||||
5412 | |||||||
5413 | case UnqualifiedIdKind::IK_TemplateId: { | ||||||
5414 | TemplateName TName = Name.TemplateId->Template.get(); | ||||||
5415 | SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; | ||||||
5416 | return Context.getNameForTemplate(TName, TNameLoc); | ||||||
5417 | } | ||||||
5418 | |||||||
5419 | } // switch (Name.getKind()) | ||||||
5420 | |||||||
5421 | llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 5421); | ||||||
5422 | } | ||||||
5423 | |||||||
5424 | static QualType getCoreType(QualType Ty) { | ||||||
5425 | do { | ||||||
5426 | if (Ty->isPointerType() || Ty->isReferenceType()) | ||||||
5427 | Ty = Ty->getPointeeType(); | ||||||
5428 | else if (Ty->isArrayType()) | ||||||
5429 | Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); | ||||||
5430 | else | ||||||
5431 | return Ty.withoutLocalFastQualifiers(); | ||||||
5432 | } while (true); | ||||||
5433 | } | ||||||
5434 | |||||||
5435 | /// hasSimilarParameters - Determine whether the C++ functions Declaration | ||||||
5436 | /// and Definition have "nearly" matching parameters. This heuristic is | ||||||
5437 | /// used to improve diagnostics in the case where an out-of-line function | ||||||
5438 | /// definition doesn't match any declaration within the class or namespace. | ||||||
5439 | /// Also sets Params to the list of indices to the parameters that differ | ||||||
5440 | /// between the declaration and the definition. If hasSimilarParameters | ||||||
5441 | /// returns true and Params is empty, then all of the parameters match. | ||||||
5442 | static bool hasSimilarParameters(ASTContext &Context, | ||||||
5443 | FunctionDecl *Declaration, | ||||||
5444 | FunctionDecl *Definition, | ||||||
5445 | SmallVectorImpl<unsigned> &Params) { | ||||||
5446 | Params.clear(); | ||||||
5447 | if (Declaration->param_size() != Definition->param_size()) | ||||||
5448 | return false; | ||||||
5449 | for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { | ||||||
5450 | QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); | ||||||
5451 | QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); | ||||||
5452 | |||||||
5453 | // The parameter types are identical | ||||||
5454 | if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) | ||||||
5455 | continue; | ||||||
5456 | |||||||
5457 | QualType DeclParamBaseTy = getCoreType(DeclParamTy); | ||||||
5458 | QualType DefParamBaseTy = getCoreType(DefParamTy); | ||||||
5459 | const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); | ||||||
5460 | const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); | ||||||
5461 | |||||||
5462 | if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || | ||||||
5463 | (DeclTyName && DeclTyName == DefTyName)) | ||||||
5464 | Params.push_back(Idx); | ||||||
5465 | else // The two parameters aren't even close | ||||||
5466 | return false; | ||||||
5467 | } | ||||||
5468 | |||||||
5469 | return true; | ||||||
5470 | } | ||||||
5471 | |||||||
5472 | /// NeedsRebuildingInCurrentInstantiation - Checks whether the given | ||||||
5473 | /// declarator needs to be rebuilt in the current instantiation. | ||||||
5474 | /// Any bits of declarator which appear before the name are valid for | ||||||
5475 | /// consideration here. That's specifically the type in the decl spec | ||||||
5476 | /// and the base type in any member-pointer chunks. | ||||||
5477 | static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, | ||||||
5478 | DeclarationName Name) { | ||||||
5479 | // The types we specifically need to rebuild are: | ||||||
5480 | // - typenames, typeofs, and decltypes | ||||||
5481 | // - types which will become injected class names | ||||||
5482 | // Of course, we also need to rebuild any type referencing such a | ||||||
5483 | // type. It's safest to just say "dependent", but we call out a | ||||||
5484 | // few cases here. | ||||||
5485 | |||||||
5486 | DeclSpec &DS = D.getMutableDeclSpec(); | ||||||
5487 | switch (DS.getTypeSpecType()) { | ||||||
5488 | case DeclSpec::TST_typename: | ||||||
5489 | case DeclSpec::TST_typeofType: | ||||||
5490 | case DeclSpec::TST_underlyingType: | ||||||
5491 | case DeclSpec::TST_atomic: { | ||||||
5492 | // Grab the type from the parser. | ||||||
5493 | TypeSourceInfo *TSI = nullptr; | ||||||
5494 | QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); | ||||||
5495 | if (T.isNull() || !T->isDependentType()) break; | ||||||
5496 | |||||||
5497 | // Make sure there's a type source info. This isn't really much | ||||||
5498 | // of a waste; most dependent types should have type source info | ||||||
5499 | // attached already. | ||||||
5500 | if (!TSI) | ||||||
5501 | TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); | ||||||
5502 | |||||||
5503 | // Rebuild the type in the current instantiation. | ||||||
5504 | TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); | ||||||
5505 | if (!TSI) return true; | ||||||
5506 | |||||||
5507 | // Store the new type back in the decl spec. | ||||||
5508 | ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); | ||||||
5509 | DS.UpdateTypeRep(LocType); | ||||||
5510 | break; | ||||||
5511 | } | ||||||
5512 | |||||||
5513 | case DeclSpec::TST_decltype: | ||||||
5514 | case DeclSpec::TST_typeofExpr: { | ||||||
5515 | Expr *E = DS.getRepAsExpr(); | ||||||
5516 | ExprResult Result = S.RebuildExprInCurrentInstantiation(E); | ||||||
5517 | if (Result.isInvalid()) return true; | ||||||
5518 | DS.UpdateExprRep(Result.get()); | ||||||
5519 | break; | ||||||
5520 | } | ||||||
5521 | |||||||
5522 | default: | ||||||
5523 | // Nothing to do for these decl specs. | ||||||
5524 | break; | ||||||
5525 | } | ||||||
5526 | |||||||
5527 | // It doesn't matter what order we do this in. | ||||||
5528 | for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { | ||||||
5529 | DeclaratorChunk &Chunk = D.getTypeObject(I); | ||||||
5530 | |||||||
5531 | // The only type information in the declarator which can come | ||||||
5532 | // before the declaration name is the base type of a member | ||||||
5533 | // pointer. | ||||||
5534 | if (Chunk.Kind != DeclaratorChunk::MemberPointer) | ||||||
5535 | continue; | ||||||
5536 | |||||||
5537 | // Rebuild the scope specifier in-place. | ||||||
5538 | CXXScopeSpec &SS = Chunk.Mem.Scope(); | ||||||
5539 | if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) | ||||||
5540 | return true; | ||||||
5541 | } | ||||||
5542 | |||||||
5543 | return false; | ||||||
5544 | } | ||||||
5545 | |||||||
5546 | Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { | ||||||
5547 | D.setFunctionDefinitionKind(FDK_Declaration); | ||||||
5548 | Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); | ||||||
5549 | |||||||
5550 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && | ||||||
5551 | Dcl && Dcl->getDeclContext()->isFileContext()) | ||||||
5552 | Dcl->setTopLevelDeclInObjCContainer(); | ||||||
5553 | |||||||
5554 | if (getLangOpts().OpenCL) | ||||||
5555 | setCurrentOpenCLExtensionForDecl(Dcl); | ||||||
5556 | |||||||
5557 | return Dcl; | ||||||
5558 | } | ||||||
5559 | |||||||
5560 | /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: | ||||||
5561 | /// If T is the name of a class, then each of the following shall have a | ||||||
5562 | /// name different from T: | ||||||
5563 | /// - every static data member of class T; | ||||||
5564 | /// - every member function of class T | ||||||
5565 | /// - every member of class T that is itself a type; | ||||||
5566 | /// \returns true if the declaration name violates these rules. | ||||||
5567 | bool Sema::DiagnoseClassNameShadow(DeclContext *DC, | ||||||
5568 | DeclarationNameInfo NameInfo) { | ||||||
5569 | DeclarationName Name = NameInfo.getName(); | ||||||
5570 | |||||||
5571 | CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); | ||||||
5572 | while (Record && Record->isAnonymousStructOrUnion()) | ||||||
5573 | Record = dyn_cast<CXXRecordDecl>(Record->getParent()); | ||||||
5574 | if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { | ||||||
5575 | Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; | ||||||
5576 | return true; | ||||||
5577 | } | ||||||
5578 | |||||||
5579 | return false; | ||||||
5580 | } | ||||||
5581 | |||||||
5582 | /// Diagnose a declaration whose declarator-id has the given | ||||||
5583 | /// nested-name-specifier. | ||||||
5584 | /// | ||||||
5585 | /// \param SS The nested-name-specifier of the declarator-id. | ||||||
5586 | /// | ||||||
5587 | /// \param DC The declaration context to which the nested-name-specifier | ||||||
5588 | /// resolves. | ||||||
5589 | /// | ||||||
5590 | /// \param Name The name of the entity being declared. | ||||||
5591 | /// | ||||||
5592 | /// \param Loc The location of the name of the entity being declared. | ||||||
5593 | /// | ||||||
5594 | /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus | ||||||
5595 | /// we're declaring an explicit / partial specialization / instantiation. | ||||||
5596 | /// | ||||||
5597 | /// \returns true if we cannot safely recover from this error, false otherwise. | ||||||
5598 | bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, | ||||||
5599 | DeclarationName Name, | ||||||
5600 | SourceLocation Loc, bool IsTemplateId) { | ||||||
5601 | DeclContext *Cur = CurContext; | ||||||
5602 | while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) | ||||||
5603 | Cur = Cur->getParent(); | ||||||
5604 | |||||||
5605 | // If the user provided a superfluous scope specifier that refers back to the | ||||||
5606 | // class in which the entity is already declared, diagnose and ignore it. | ||||||
5607 | // | ||||||
5608 | // class X { | ||||||
5609 | // void X::f(); | ||||||
5610 | // }; | ||||||
5611 | // | ||||||
5612 | // Note, it was once ill-formed to give redundant qualification in all | ||||||
5613 | // contexts, but that rule was removed by DR482. | ||||||
5614 | if (Cur->Equals(DC)) { | ||||||
5615 | if (Cur->isRecord()) { | ||||||
5616 | Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification | ||||||
5617 | : diag::err_member_extra_qualification) | ||||||
5618 | << Name << FixItHint::CreateRemoval(SS.getRange()); | ||||||
5619 | SS.clear(); | ||||||
5620 | } else { | ||||||
5621 | Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; | ||||||
5622 | } | ||||||
5623 | return false; | ||||||
5624 | } | ||||||
5625 | |||||||
5626 | // Check whether the qualifying scope encloses the scope of the original | ||||||
5627 | // declaration. For a template-id, we perform the checks in | ||||||
5628 | // CheckTemplateSpecializationScope. | ||||||
5629 | if (!Cur->Encloses(DC) && !IsTemplateId) { | ||||||
5630 | if (Cur->isRecord()) | ||||||
5631 | Diag(Loc, diag::err_member_qualification) | ||||||
5632 | << Name << SS.getRange(); | ||||||
5633 | else if (isa<TranslationUnitDecl>(DC)) | ||||||
5634 | Diag(Loc, diag::err_invalid_declarator_global_scope) | ||||||
5635 | << Name << SS.getRange(); | ||||||
5636 | else if (isa<FunctionDecl>(Cur)) | ||||||
5637 | Diag(Loc, diag::err_invalid_declarator_in_function) | ||||||
5638 | << Name << SS.getRange(); | ||||||
5639 | else if (isa<BlockDecl>(Cur)) | ||||||
5640 | Diag(Loc, diag::err_invalid_declarator_in_block) | ||||||
5641 | << Name << SS.getRange(); | ||||||
5642 | else | ||||||
5643 | Diag(Loc, diag::err_invalid_declarator_scope) | ||||||
5644 | << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); | ||||||
5645 | |||||||
5646 | return true; | ||||||
5647 | } | ||||||
5648 | |||||||
5649 | if (Cur->isRecord()) { | ||||||
5650 | // Cannot qualify members within a class. | ||||||
5651 | Diag(Loc, diag::err_member_qualification) | ||||||
5652 | << Name << SS.getRange(); | ||||||
5653 | SS.clear(); | ||||||
5654 | |||||||
5655 | // C++ constructors and destructors with incorrect scopes can break | ||||||
5656 | // our AST invariants by having the wrong underlying types. If | ||||||
5657 | // that's the case, then drop this declaration entirely. | ||||||
5658 | if ((Name.getNameKind() == DeclarationName::CXXConstructorName || | ||||||
5659 | Name.getNameKind() == DeclarationName::CXXDestructorName) && | ||||||
5660 | !Context.hasSameType(Name.getCXXNameType(), | ||||||
5661 | Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) | ||||||
5662 | return true; | ||||||
5663 | |||||||
5664 | return false; | ||||||
5665 | } | ||||||
5666 | |||||||
5667 | // C++11 [dcl.meaning]p1: | ||||||
5668 | // [...] "The nested-name-specifier of the qualified declarator-id shall | ||||||
5669 | // not begin with a decltype-specifer" | ||||||
5670 | NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); | ||||||
5671 | while (SpecLoc.getPrefix()) | ||||||
5672 | SpecLoc = SpecLoc.getPrefix(); | ||||||
5673 | if (dyn_cast_or_null<DecltypeType>( | ||||||
5674 | SpecLoc.getNestedNameSpecifier()->getAsType())) | ||||||
5675 | Diag(Loc, diag::err_decltype_in_declarator) | ||||||
5676 | << SpecLoc.getTypeLoc().getSourceRange(); | ||||||
5677 | |||||||
5678 | return false; | ||||||
5679 | } | ||||||
5680 | |||||||
5681 | NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, | ||||||
5682 | MultiTemplateParamsArg TemplateParamLists) { | ||||||
5683 | // TODO: consider using NameInfo for diagnostic. | ||||||
5684 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||||
5685 | DeclarationName Name = NameInfo.getName(); | ||||||
5686 | |||||||
5687 | // All of these full declarators require an identifier. If it doesn't have | ||||||
5688 | // one, the ParsedFreeStandingDeclSpec action should be used. | ||||||
5689 | if (D.isDecompositionDeclarator()) { | ||||||
5690 | return ActOnDecompositionDeclarator(S, D, TemplateParamLists); | ||||||
5691 | } else if (!Name) { | ||||||
5692 | if (!D.isInvalidType()) // Reject this if we think it is valid. | ||||||
5693 | Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) | ||||||
5694 | << D.getDeclSpec().getSourceRange() << D.getSourceRange(); | ||||||
5695 | return nullptr; | ||||||
5696 | } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) | ||||||
5697 | return nullptr; | ||||||
5698 | |||||||
5699 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||||
5700 | // we find one that is. | ||||||
5701 | while ((S->getFlags() & Scope::DeclScope) == 0 || | ||||||
5702 | (S->getFlags() & Scope::TemplateParamScope) != 0) | ||||||
5703 | S = S->getParent(); | ||||||
5704 | |||||||
5705 | DeclContext *DC = CurContext; | ||||||
5706 | if (D.getCXXScopeSpec().isInvalid()) | ||||||
5707 | D.setInvalidType(); | ||||||
5708 | else if (D.getCXXScopeSpec().isSet()) { | ||||||
5709 | if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), | ||||||
5710 | UPPC_DeclarationQualifier)) | ||||||
5711 | return nullptr; | ||||||
5712 | |||||||
5713 | bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); | ||||||
5714 | DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); | ||||||
5715 | if (!DC || isa<EnumDecl>(DC)) { | ||||||
5716 | // If we could not compute the declaration context, it's because the | ||||||
5717 | // declaration context is dependent but does not refer to a class, | ||||||
5718 | // class template, or class template partial specialization. Complain | ||||||
5719 | // and return early, to avoid the coming semantic disaster. | ||||||
5720 | Diag(D.getIdentifierLoc(), | ||||||
5721 | diag::err_template_qualified_declarator_no_match) | ||||||
5722 | << D.getCXXScopeSpec().getScopeRep() | ||||||
5723 | << D.getCXXScopeSpec().getRange(); | ||||||
5724 | return nullptr; | ||||||
5725 | } | ||||||
5726 | bool IsDependentContext = DC->isDependentContext(); | ||||||
5727 | |||||||
5728 | if (!IsDependentContext && | ||||||
5729 | RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) | ||||||
5730 | return nullptr; | ||||||
5731 | |||||||
5732 | // If a class is incomplete, do not parse entities inside it. | ||||||
5733 | if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { | ||||||
5734 | Diag(D.getIdentifierLoc(), | ||||||
5735 | diag::err_member_def_undefined_record) | ||||||
5736 | << Name << DC << D.getCXXScopeSpec().getRange(); | ||||||
5737 | return nullptr; | ||||||
5738 | } | ||||||
5739 | if (!D.getDeclSpec().isFriendSpecified()) { | ||||||
5740 | if (diagnoseQualifiedDeclaration( | ||||||
5741 | D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), | ||||||
5742 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { | ||||||
5743 | if (DC->isRecord()) | ||||||
5744 | return nullptr; | ||||||
5745 | |||||||
5746 | D.setInvalidType(); | ||||||
5747 | } | ||||||
5748 | } | ||||||
5749 | |||||||
5750 | // Check whether we need to rebuild the type of the given | ||||||
5751 | // declaration in the current instantiation. | ||||||
5752 | if (EnteringContext && IsDependentContext && | ||||||
5753 | TemplateParamLists.size() != 0) { | ||||||
5754 | ContextRAII SavedContext(*this, DC); | ||||||
5755 | if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) | ||||||
5756 | D.setInvalidType(); | ||||||
5757 | } | ||||||
5758 | } | ||||||
5759 | |||||||
5760 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
5761 | QualType R = TInfo->getType(); | ||||||
5762 | |||||||
5763 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||||
5764 | UPPC_DeclarationType)) | ||||||
5765 | D.setInvalidType(); | ||||||
5766 | |||||||
5767 | LookupResult Previous(*this, NameInfo, LookupOrdinaryName, | ||||||
5768 | forRedeclarationInCurContext()); | ||||||
5769 | |||||||
5770 | // See if this is a redefinition of a variable in the same scope. | ||||||
5771 | if (!D.getCXXScopeSpec().isSet()) { | ||||||
5772 | bool IsLinkageLookup = false; | ||||||
5773 | bool CreateBuiltins = false; | ||||||
5774 | |||||||
5775 | // If the declaration we're planning to build will be a function | ||||||
5776 | // or object with linkage, then look for another declaration with | ||||||
5777 | // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). | ||||||
5778 | // | ||||||
5779 | // If the declaration we're planning to build will be declared with | ||||||
5780 | // external linkage in the translation unit, create any builtin with | ||||||
5781 | // the same name. | ||||||
5782 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) | ||||||
5783 | /* Do nothing*/; | ||||||
5784 | else if (CurContext->isFunctionOrMethod() && | ||||||
5785 | (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || | ||||||
5786 | R->isFunctionType())) { | ||||||
5787 | IsLinkageLookup = true; | ||||||
5788 | CreateBuiltins = | ||||||
5789 | CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); | ||||||
5790 | } else if (CurContext->getRedeclContext()->isTranslationUnit() && | ||||||
5791 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) | ||||||
5792 | CreateBuiltins = true; | ||||||
5793 | |||||||
5794 | if (IsLinkageLookup) { | ||||||
5795 | Previous.clear(LookupRedeclarationWithLinkage); | ||||||
5796 | Previous.setRedeclarationKind(ForExternalRedeclaration); | ||||||
5797 | } | ||||||
5798 | |||||||
5799 | LookupName(Previous, S, CreateBuiltins); | ||||||
5800 | } else { // Something like "int foo::x;" | ||||||
5801 | LookupQualifiedName(Previous, DC); | ||||||
5802 | |||||||
5803 | // C++ [dcl.meaning]p1: | ||||||
5804 | // When the declarator-id is qualified, the declaration shall refer to a | ||||||
5805 | // previously declared member of the class or namespace to which the | ||||||
5806 | // qualifier refers (or, in the case of a namespace, of an element of the | ||||||
5807 | // inline namespace set of that namespace (7.3.1)) or to a specialization | ||||||
5808 | // thereof; [...] | ||||||
5809 | // | ||||||
5810 | // Note that we already checked the context above, and that we do not have | ||||||
5811 | // enough information to make sure that Previous contains the declaration | ||||||
5812 | // we want to match. For example, given: | ||||||
5813 | // | ||||||
5814 | // class X { | ||||||
5815 | // void f(); | ||||||
5816 | // void f(float); | ||||||
5817 | // }; | ||||||
5818 | // | ||||||
5819 | // void X::f(int) { } // ill-formed | ||||||
5820 | // | ||||||
5821 | // In this case, Previous will point to the overload set | ||||||
5822 | // containing the two f's declared in X, but neither of them | ||||||
5823 | // matches. | ||||||
5824 | |||||||
5825 | // C++ [dcl.meaning]p1: | ||||||
5826 | // [...] the member shall not merely have been introduced by a | ||||||
5827 | // using-declaration in the scope of the class or namespace nominated by | ||||||
5828 | // the nested-name-specifier of the declarator-id. | ||||||
5829 | RemoveUsingDecls(Previous); | ||||||
5830 | } | ||||||
5831 | |||||||
5832 | if (Previous.isSingleResult() && | ||||||
5833 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||||
5834 | // Maybe we will complain about the shadowed template parameter. | ||||||
5835 | if (!D.isInvalidType()) | ||||||
5836 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), | ||||||
5837 | Previous.getFoundDecl()); | ||||||
5838 | |||||||
5839 | // Just pretend that we didn't see the previous declaration. | ||||||
5840 | Previous.clear(); | ||||||
5841 | } | ||||||
5842 | |||||||
5843 | if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) | ||||||
5844 | // Forget that the previous declaration is the injected-class-name. | ||||||
5845 | Previous.clear(); | ||||||
5846 | |||||||
5847 | // In C++, the previous declaration we find might be a tag type | ||||||
5848 | // (class or enum). In this case, the new declaration will hide the | ||||||
5849 | // tag type. Note that this applies to functions, function templates, and | ||||||
5850 | // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. | ||||||
5851 | if (Previous.isSingleTagDecl() && | ||||||
5852 | D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && | ||||||
5853 | (TemplateParamLists.size() == 0 || R->isFunctionType())) | ||||||
5854 | Previous.clear(); | ||||||
5855 | |||||||
5856 | // Check that there are no default arguments other than in the parameters | ||||||
5857 | // of a function declaration (C++ only). | ||||||
5858 | if (getLangOpts().CPlusPlus) | ||||||
5859 | CheckExtraCXXDefaultArguments(D); | ||||||
5860 | |||||||
5861 | NamedDecl *New; | ||||||
5862 | |||||||
5863 | bool AddToScope = true; | ||||||
5864 | if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { | ||||||
5865 | if (TemplateParamLists.size()) { | ||||||
5866 | Diag(D.getIdentifierLoc(), diag::err_template_typedef); | ||||||
5867 | return nullptr; | ||||||
5868 | } | ||||||
5869 | |||||||
5870 | New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); | ||||||
5871 | } else if (R->isFunctionType()) { | ||||||
5872 | New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, | ||||||
5873 | TemplateParamLists, | ||||||
5874 | AddToScope); | ||||||
5875 | } else { | ||||||
5876 | New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, | ||||||
5877 | AddToScope); | ||||||
5878 | } | ||||||
5879 | |||||||
5880 | if (!New) | ||||||
5881 | return nullptr; | ||||||
5882 | |||||||
5883 | // If this has an identifier and is not a function template specialization, | ||||||
5884 | // add it to the scope stack. | ||||||
5885 | if (New->getDeclName() && AddToScope) | ||||||
5886 | PushOnScopeChains(New, S); | ||||||
5887 | |||||||
5888 | if (isInOpenMPDeclareTargetContext()) | ||||||
5889 | checkDeclIsAllowedInOpenMPTarget(nullptr, New); | ||||||
5890 | |||||||
5891 | return New; | ||||||
5892 | } | ||||||
5893 | |||||||
5894 | /// Helper method to turn variable array types into constant array | ||||||
5895 | /// types in certain situations which would otherwise be errors (for | ||||||
5896 | /// GCC compatibility). | ||||||
5897 | static QualType TryToFixInvalidVariablyModifiedType(QualType T, | ||||||
5898 | ASTContext &Context, | ||||||
5899 | bool &SizeIsNegative, | ||||||
5900 | llvm::APSInt &Oversized) { | ||||||
5901 | // This method tries to turn a variable array into a constant | ||||||
5902 | // array even when the size isn't an ICE. This is necessary | ||||||
5903 | // for compatibility with code that depends on gcc's buggy | ||||||
5904 | // constant expression folding, like struct {char x[(int)(char*)2];} | ||||||
5905 | SizeIsNegative = false; | ||||||
5906 | Oversized = 0; | ||||||
5907 | |||||||
5908 | if (T->isDependentType()) | ||||||
5909 | return QualType(); | ||||||
5910 | |||||||
5911 | QualifierCollector Qs; | ||||||
5912 | const Type *Ty = Qs.strip(T); | ||||||
5913 | |||||||
5914 | if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { | ||||||
5915 | QualType Pointee = PTy->getPointeeType(); | ||||||
5916 | QualType FixedType = | ||||||
5917 | TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, | ||||||
5918 | Oversized); | ||||||
5919 | if (FixedType.isNull()) return FixedType; | ||||||
5920 | FixedType = Context.getPointerType(FixedType); | ||||||
5921 | return Qs.apply(Context, FixedType); | ||||||
5922 | } | ||||||
5923 | if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { | ||||||
5924 | QualType Inner = PTy->getInnerType(); | ||||||
5925 | QualType FixedType = | ||||||
5926 | TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, | ||||||
5927 | Oversized); | ||||||
5928 | if (FixedType.isNull()) return FixedType; | ||||||
5929 | FixedType = Context.getParenType(FixedType); | ||||||
5930 | return Qs.apply(Context, FixedType); | ||||||
5931 | } | ||||||
5932 | |||||||
5933 | const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); | ||||||
5934 | if (!VLATy) | ||||||
5935 | return QualType(); | ||||||
5936 | // FIXME: We should probably handle this case | ||||||
5937 | if (VLATy->getElementType()->isVariablyModifiedType()) | ||||||
5938 | return QualType(); | ||||||
5939 | |||||||
5940 | Expr::EvalResult Result; | ||||||
5941 | if (!VLATy->getSizeExpr() || | ||||||
5942 | !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) | ||||||
5943 | return QualType(); | ||||||
5944 | |||||||
5945 | llvm::APSInt Res = Result.Val.getInt(); | ||||||
5946 | |||||||
5947 | // Check whether the array size is negative. | ||||||
5948 | if (Res.isSigned() && Res.isNegative()) { | ||||||
5949 | SizeIsNegative = true; | ||||||
5950 | return QualType(); | ||||||
5951 | } | ||||||
5952 | |||||||
5953 | // Check whether the array is too large to be addressed. | ||||||
5954 | unsigned ActiveSizeBits | ||||||
5955 | = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), | ||||||
5956 | Res); | ||||||
5957 | if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { | ||||||
5958 | Oversized = Res; | ||||||
5959 | return QualType(); | ||||||
5960 | } | ||||||
5961 | |||||||
5962 | return Context.getConstantArrayType( | ||||||
5963 | VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); | ||||||
5964 | } | ||||||
5965 | |||||||
5966 | static void | ||||||
5967 | FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { | ||||||
5968 | SrcTL = SrcTL.getUnqualifiedLoc(); | ||||||
5969 | DstTL = DstTL.getUnqualifiedLoc(); | ||||||
5970 | if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { | ||||||
5971 | PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); | ||||||
5972 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), | ||||||
5973 | DstPTL.getPointeeLoc()); | ||||||
5974 | DstPTL.setStarLoc(SrcPTL.getStarLoc()); | ||||||
5975 | return; | ||||||
5976 | } | ||||||
5977 | if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { | ||||||
5978 | ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); | ||||||
5979 | FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), | ||||||
5980 | DstPTL.getInnerLoc()); | ||||||
5981 | DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); | ||||||
5982 | DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); | ||||||
5983 | return; | ||||||
5984 | } | ||||||
5985 | ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); | ||||||
5986 | ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); | ||||||
5987 | TypeLoc SrcElemTL = SrcATL.getElementLoc(); | ||||||
5988 | TypeLoc DstElemTL = DstATL.getElementLoc(); | ||||||
5989 | DstElemTL.initializeFullCopy(SrcElemTL); | ||||||
5990 | DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); | ||||||
5991 | DstATL.setSizeExpr(SrcATL.getSizeExpr()); | ||||||
5992 | DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); | ||||||
5993 | } | ||||||
5994 | |||||||
5995 | /// Helper method to turn variable array types into constant array | ||||||
5996 | /// types in certain situations which would otherwise be errors (for | ||||||
5997 | /// GCC compatibility). | ||||||
5998 | static TypeSourceInfo* | ||||||
5999 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, | ||||||
6000 | ASTContext &Context, | ||||||
6001 | bool &SizeIsNegative, | ||||||
6002 | llvm::APSInt &Oversized) { | ||||||
6003 | QualType FixedTy | ||||||
6004 | = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, | ||||||
6005 | SizeIsNegative, Oversized); | ||||||
6006 | if (FixedTy.isNull()) | ||||||
6007 | return nullptr; | ||||||
6008 | TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); | ||||||
6009 | FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), | ||||||
6010 | FixedTInfo->getTypeLoc()); | ||||||
6011 | return FixedTInfo; | ||||||
6012 | } | ||||||
6013 | |||||||
6014 | /// Register the given locally-scoped extern "C" declaration so | ||||||
6015 | /// that it can be found later for redeclarations. We include any extern "C" | ||||||
6016 | /// declaration that is not visible in the translation unit here, not just | ||||||
6017 | /// function-scope declarations. | ||||||
6018 | void | ||||||
6019 | Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { | ||||||
6020 | if (!getLangOpts().CPlusPlus && | ||||||
6021 | ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||||
6022 | // Don't need to track declarations in the TU in C. | ||||||
6023 | return; | ||||||
6024 | |||||||
6025 | // Note that we have a locally-scoped external with this name. | ||||||
6026 | Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); | ||||||
6027 | } | ||||||
6028 | |||||||
6029 | NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { | ||||||
6030 | // FIXME: We can have multiple results via __attribute__((overloadable)). | ||||||
6031 | auto Result = Context.getExternCContextDecl()->lookup(Name); | ||||||
6032 | return Result.empty() ? nullptr : *Result.begin(); | ||||||
6033 | } | ||||||
6034 | |||||||
6035 | /// Diagnose function specifiers on a declaration of an identifier that | ||||||
6036 | /// does not identify a function. | ||||||
6037 | void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { | ||||||
6038 | // FIXME: We should probably indicate the identifier in question to avoid | ||||||
6039 | // confusion for constructs like "virtual int a(), b;" | ||||||
6040 | if (DS.isVirtualSpecified()) | ||||||
6041 | Diag(DS.getVirtualSpecLoc(), | ||||||
6042 | diag::err_virtual_non_function); | ||||||
6043 | |||||||
6044 | if (DS.hasExplicitSpecifier()) | ||||||
6045 | Diag(DS.getExplicitSpecLoc(), | ||||||
6046 | diag::err_explicit_non_function); | ||||||
6047 | |||||||
6048 | if (DS.isNoreturnSpecified()) | ||||||
6049 | Diag(DS.getNoreturnSpecLoc(), | ||||||
6050 | diag::err_noreturn_non_function); | ||||||
6051 | } | ||||||
6052 | |||||||
6053 | NamedDecl* | ||||||
6054 | Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, | ||||||
6055 | TypeSourceInfo *TInfo, LookupResult &Previous) { | ||||||
6056 | // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||||
6057 | if (D.getCXXScopeSpec().isSet()) { | ||||||
6058 | Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) | ||||||
6059 | << D.getCXXScopeSpec().getRange(); | ||||||
6060 | D.setInvalidType(); | ||||||
6061 | // Pretend we didn't see the scope specifier. | ||||||
6062 | DC = CurContext; | ||||||
6063 | Previous.clear(); | ||||||
6064 | } | ||||||
6065 | |||||||
6066 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
6067 | |||||||
6068 | if (D.getDeclSpec().isInlineSpecified()) | ||||||
6069 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
6070 | << getLangOpts().CPlusPlus17; | ||||||
6071 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||||
6072 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||||
6073 | << 1 << D.getDeclSpec().getConstexprSpecifier(); | ||||||
6074 | |||||||
6075 | if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { | ||||||
6076 | if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) | ||||||
6077 | Diag(D.getName().StartLocation, | ||||||
6078 | diag::err_deduction_guide_invalid_specifier) | ||||||
6079 | << "typedef"; | ||||||
6080 | else | ||||||
6081 | Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) | ||||||
6082 | << D.getName().getSourceRange(); | ||||||
6083 | return nullptr; | ||||||
6084 | } | ||||||
6085 | |||||||
6086 | TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); | ||||||
6087 | if (!NewTD) return nullptr; | ||||||
6088 | |||||||
6089 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||||
6090 | ProcessDeclAttributes(S, NewTD, D); | ||||||
6091 | |||||||
6092 | CheckTypedefForVariablyModifiedType(S, NewTD); | ||||||
6093 | |||||||
6094 | bool Redeclaration = D.isRedeclaration(); | ||||||
6095 | NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); | ||||||
6096 | D.setRedeclaration(Redeclaration); | ||||||
6097 | return ND; | ||||||
6098 | } | ||||||
6099 | |||||||
6100 | void | ||||||
6101 | Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { | ||||||
6102 | // C99 6.7.7p2: If a typedef name specifies a variably modified type | ||||||
6103 | // then it shall have block scope. | ||||||
6104 | // Note that variably modified types must be fixed before merging the decl so | ||||||
6105 | // that redeclarations will match. | ||||||
6106 | TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); | ||||||
6107 | QualType T = TInfo->getType(); | ||||||
6108 | if (T->isVariablyModifiedType()) { | ||||||
6109 | setFunctionHasBranchProtectedScope(); | ||||||
6110 | |||||||
6111 | if (S->getFnParent() == nullptr) { | ||||||
6112 | bool SizeIsNegative; | ||||||
6113 | llvm::APSInt Oversized; | ||||||
6114 | TypeSourceInfo *FixedTInfo = | ||||||
6115 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||||
6116 | SizeIsNegative, | ||||||
6117 | Oversized); | ||||||
6118 | if (FixedTInfo) { | ||||||
6119 | Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); | ||||||
6120 | NewTD->setTypeSourceInfo(FixedTInfo); | ||||||
6121 | } else { | ||||||
6122 | if (SizeIsNegative) | ||||||
6123 | Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); | ||||||
6124 | else if (T->isVariableArrayType()) | ||||||
6125 | Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); | ||||||
6126 | else if (Oversized.getBoolValue()) | ||||||
6127 | Diag(NewTD->getLocation(), diag::err_array_too_large) | ||||||
6128 | << Oversized.toString(10); | ||||||
6129 | else | ||||||
6130 | Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||||
6131 | NewTD->setInvalidDecl(); | ||||||
6132 | } | ||||||
6133 | } | ||||||
6134 | } | ||||||
6135 | } | ||||||
6136 | |||||||
6137 | /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which | ||||||
6138 | /// declares a typedef-name, either using the 'typedef' type specifier or via | ||||||
6139 | /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. | ||||||
6140 | NamedDecl* | ||||||
6141 | Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, | ||||||
6142 | LookupResult &Previous, bool &Redeclaration) { | ||||||
6143 | |||||||
6144 | // Find the shadowed declaration before filtering for scope. | ||||||
6145 | NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); | ||||||
6146 | |||||||
6147 | // Merge the decl with the existing one if appropriate. If the decl is | ||||||
6148 | // in an outer scope, it isn't the same thing. | ||||||
6149 | FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, | ||||||
6150 | /*AllowInlineNamespace*/false); | ||||||
6151 | filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); | ||||||
6152 | if (!Previous.empty()) { | ||||||
6153 | Redeclaration = true; | ||||||
6154 | MergeTypedefNameDecl(S, NewTD, Previous); | ||||||
6155 | } else { | ||||||
6156 | inferGslPointerAttribute(NewTD); | ||||||
6157 | } | ||||||
6158 | |||||||
6159 | if (ShadowedDecl && !Redeclaration) | ||||||
6160 | CheckShadow(NewTD, ShadowedDecl, Previous); | ||||||
6161 | |||||||
6162 | // If this is the C FILE type, notify the AST context. | ||||||
6163 | if (IdentifierInfo *II = NewTD->getIdentifier()) | ||||||
6164 | if (!NewTD->isInvalidDecl() && | ||||||
6165 | NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
6166 | if (II->isStr("FILE")) | ||||||
6167 | Context.setFILEDecl(NewTD); | ||||||
6168 | else if (II->isStr("jmp_buf")) | ||||||
6169 | Context.setjmp_bufDecl(NewTD); | ||||||
6170 | else if (II->isStr("sigjmp_buf")) | ||||||
6171 | Context.setsigjmp_bufDecl(NewTD); | ||||||
6172 | else if (II->isStr("ucontext_t")) | ||||||
6173 | Context.setucontext_tDecl(NewTD); | ||||||
6174 | } | ||||||
6175 | |||||||
6176 | return NewTD; | ||||||
6177 | } | ||||||
6178 | |||||||
6179 | /// Determines whether the given declaration is an out-of-scope | ||||||
6180 | /// previous declaration. | ||||||
6181 | /// | ||||||
6182 | /// This routine should be invoked when name lookup has found a | ||||||
6183 | /// previous declaration (PrevDecl) that is not in the scope where a | ||||||
6184 | /// new declaration by the same name is being introduced. If the new | ||||||
6185 | /// declaration occurs in a local scope, previous declarations with | ||||||
6186 | /// linkage may still be considered previous declarations (C99 | ||||||
6187 | /// 6.2.2p4-5, C++ [basic.link]p6). | ||||||
6188 | /// | ||||||
6189 | /// \param PrevDecl the previous declaration found by name | ||||||
6190 | /// lookup | ||||||
6191 | /// | ||||||
6192 | /// \param DC the context in which the new declaration is being | ||||||
6193 | /// declared. | ||||||
6194 | /// | ||||||
6195 | /// \returns true if PrevDecl is an out-of-scope previous declaration | ||||||
6196 | /// for a new delcaration with the same name. | ||||||
6197 | static bool | ||||||
6198 | isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, | ||||||
6199 | ASTContext &Context) { | ||||||
6200 | if (!PrevDecl) | ||||||
6201 | return false; | ||||||
6202 | |||||||
6203 | if (!PrevDecl->hasLinkage()) | ||||||
6204 | return false; | ||||||
6205 | |||||||
6206 | if (Context.getLangOpts().CPlusPlus) { | ||||||
6207 | // C++ [basic.link]p6: | ||||||
6208 | // If there is a visible declaration of an entity with linkage | ||||||
6209 | // having the same name and type, ignoring entities declared | ||||||
6210 | // outside the innermost enclosing namespace scope, the block | ||||||
6211 | // scope declaration declares that same entity and receives the | ||||||
6212 | // linkage of the previous declaration. | ||||||
6213 | DeclContext *OuterContext = DC->getRedeclContext(); | ||||||
6214 | if (!OuterContext->isFunctionOrMethod()) | ||||||
6215 | // This rule only applies to block-scope declarations. | ||||||
6216 | return false; | ||||||
6217 | |||||||
6218 | DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); | ||||||
6219 | if (PrevOuterContext->isRecord()) | ||||||
6220 | // We found a member function: ignore it. | ||||||
6221 | return false; | ||||||
6222 | |||||||
6223 | // Find the innermost enclosing namespace for the new and | ||||||
6224 | // previous declarations. | ||||||
6225 | OuterContext = OuterContext->getEnclosingNamespaceContext(); | ||||||
6226 | PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); | ||||||
6227 | |||||||
6228 | // The previous declaration is in a different namespace, so it | ||||||
6229 | // isn't the same function. | ||||||
6230 | if (!OuterContext->Equals(PrevOuterContext)) | ||||||
6231 | return false; | ||||||
6232 | } | ||||||
6233 | |||||||
6234 | return true; | ||||||
6235 | } | ||||||
6236 | |||||||
6237 | static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { | ||||||
6238 | CXXScopeSpec &SS = D.getCXXScopeSpec(); | ||||||
6239 | if (!SS.isSet()) return; | ||||||
6240 | DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); | ||||||
6241 | } | ||||||
6242 | |||||||
6243 | bool Sema::inferObjCARCLifetime(ValueDecl *decl) { | ||||||
6244 | QualType type = decl->getType(); | ||||||
6245 | Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); | ||||||
6246 | if (lifetime == Qualifiers::OCL_Autoreleasing) { | ||||||
6247 | // Various kinds of declaration aren't allowed to be __autoreleasing. | ||||||
6248 | unsigned kind = -1U; | ||||||
6249 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||||
6250 | if (var->hasAttr<BlocksAttr>()) | ||||||
6251 | kind = 0; // __block | ||||||
6252 | else if (!var->hasLocalStorage()) | ||||||
6253 | kind = 1; // global | ||||||
6254 | } else if (isa<ObjCIvarDecl>(decl)) { | ||||||
6255 | kind = 3; // ivar | ||||||
6256 | } else if (isa<FieldDecl>(decl)) { | ||||||
6257 | kind = 2; // field | ||||||
6258 | } | ||||||
6259 | |||||||
6260 | if (kind != -1U) { | ||||||
6261 | Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) | ||||||
6262 | << kind; | ||||||
6263 | } | ||||||
6264 | } else if (lifetime == Qualifiers::OCL_None) { | ||||||
6265 | // Try to infer lifetime. | ||||||
6266 | if (!type->isObjCLifetimeType()) | ||||||
6267 | return false; | ||||||
6268 | |||||||
6269 | lifetime = type->getObjCARCImplicitLifetime(); | ||||||
6270 | type = Context.getLifetimeQualifiedType(type, lifetime); | ||||||
6271 | decl->setType(type); | ||||||
6272 | } | ||||||
6273 | |||||||
6274 | if (VarDecl *var = dyn_cast<VarDecl>(decl)) { | ||||||
6275 | // Thread-local variables cannot have lifetime. | ||||||
6276 | if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && | ||||||
6277 | var->getTLSKind()) { | ||||||
6278 | Diag(var->getLocation(), diag::err_arc_thread_ownership) | ||||||
6279 | << var->getType(); | ||||||
6280 | return true; | ||||||
6281 | } | ||||||
6282 | } | ||||||
6283 | |||||||
6284 | return false; | ||||||
6285 | } | ||||||
6286 | |||||||
6287 | void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { | ||||||
6288 | if (Decl->getType().hasAddressSpace()) | ||||||
6289 | return; | ||||||
6290 | if (Decl->getType()->isDependentType()) | ||||||
6291 | return; | ||||||
6292 | if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { | ||||||
6293 | QualType Type = Var->getType(); | ||||||
6294 | if (Type->isSamplerT() || Type->isVoidType()) | ||||||
6295 | return; | ||||||
6296 | LangAS ImplAS = LangAS::opencl_private; | ||||||
6297 | if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && | ||||||
6298 | Var->hasGlobalStorage()) | ||||||
6299 | ImplAS = LangAS::opencl_global; | ||||||
6300 | // If the original type from a decayed type is an array type and that array | ||||||
6301 | // type has no address space yet, deduce it now. | ||||||
6302 | if (auto DT = dyn_cast<DecayedType>(Type)) { | ||||||
6303 | auto OrigTy = DT->getOriginalType(); | ||||||
6304 | if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { | ||||||
6305 | // Add the address space to the original array type and then propagate | ||||||
6306 | // that to the element type through `getAsArrayType`. | ||||||
6307 | OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); | ||||||
6308 | OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); | ||||||
6309 | // Re-generate the decayed type. | ||||||
6310 | Type = Context.getDecayedType(OrigTy); | ||||||
6311 | } | ||||||
6312 | } | ||||||
6313 | Type = Context.getAddrSpaceQualType(Type, ImplAS); | ||||||
6314 | // Apply any qualifiers (including address space) from the array type to | ||||||
6315 | // the element type. This implements C99 6.7.3p8: "If the specification of | ||||||
6316 | // an array type includes any type qualifiers, the element type is so | ||||||
6317 | // qualified, not the array type." | ||||||
6318 | if (Type->isArrayType()) | ||||||
6319 | Type = QualType(Context.getAsArrayType(Type), 0); | ||||||
6320 | Decl->setType(Type); | ||||||
6321 | } | ||||||
6322 | } | ||||||
6323 | |||||||
6324 | static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { | ||||||
6325 | // Ensure that an auto decl is deduced otherwise the checks below might cache | ||||||
6326 | // the wrong linkage. | ||||||
6327 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6327, __PRETTY_FUNCTION__)); | ||||||
6328 | |||||||
6329 | // 'weak' only applies to declarations with external linkage. | ||||||
6330 | if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { | ||||||
6331 | if (!ND.isExternallyVisible()) { | ||||||
6332 | S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); | ||||||
6333 | ND.dropAttr<WeakAttr>(); | ||||||
6334 | } | ||||||
6335 | } | ||||||
6336 | if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { | ||||||
6337 | if (ND.isExternallyVisible()) { | ||||||
6338 | S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); | ||||||
6339 | ND.dropAttr<WeakRefAttr>(); | ||||||
6340 | ND.dropAttr<AliasAttr>(); | ||||||
6341 | } | ||||||
6342 | } | ||||||
6343 | |||||||
6344 | if (auto *VD = dyn_cast<VarDecl>(&ND)) { | ||||||
6345 | if (VD->hasInit()) { | ||||||
6346 | if (const auto *Attr = VD->getAttr<AliasAttr>()) { | ||||||
6347 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6348, __PRETTY_FUNCTION__)) | ||||||
6348 | !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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6348, __PRETTY_FUNCTION__)); | ||||||
6349 | S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; | ||||||
6350 | VD->dropAttr<AliasAttr>(); | ||||||
6351 | } | ||||||
6352 | } | ||||||
6353 | } | ||||||
6354 | |||||||
6355 | // 'selectany' only applies to externally visible variable declarations. | ||||||
6356 | // It does not apply to functions. | ||||||
6357 | if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { | ||||||
6358 | if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { | ||||||
6359 | S.Diag(Attr->getLocation(), | ||||||
6360 | diag::err_attribute_selectany_non_extern_data); | ||||||
6361 | ND.dropAttr<SelectAnyAttr>(); | ||||||
6362 | } | ||||||
6363 | } | ||||||
6364 | |||||||
6365 | if (const InheritableAttr *Attr = getDLLAttr(&ND)) { | ||||||
6366 | auto *VD = dyn_cast<VarDecl>(&ND); | ||||||
6367 | bool IsAnonymousNS = false; | ||||||
6368 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||||
6369 | if (VD) { | ||||||
6370 | const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); | ||||||
6371 | while (NS && !IsAnonymousNS) { | ||||||
6372 | IsAnonymousNS = NS->isAnonymousNamespace(); | ||||||
6373 | NS = dyn_cast<NamespaceDecl>(NS->getParent()); | ||||||
6374 | } | ||||||
6375 | } | ||||||
6376 | // dll attributes require external linkage. Static locals may have external | ||||||
6377 | // linkage but still cannot be explicitly imported or exported. | ||||||
6378 | // In Microsoft mode, a variable defined in anonymous namespace must have | ||||||
6379 | // external linkage in order to be exported. | ||||||
6380 | bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; | ||||||
6381 | if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || | ||||||
6382 | (!AnonNSInMicrosoftMode && | ||||||
6383 | (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { | ||||||
6384 | S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) | ||||||
6385 | << &ND << Attr; | ||||||
6386 | ND.setInvalidDecl(); | ||||||
6387 | } | ||||||
6388 | } | ||||||
6389 | |||||||
6390 | // Virtual functions cannot be marked as 'notail'. | ||||||
6391 | if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) | ||||||
6392 | if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) | ||||||
6393 | if (MD->isVirtual()) { | ||||||
6394 | S.Diag(ND.getLocation(), | ||||||
6395 | diag::err_invalid_attribute_on_virtual_function) | ||||||
6396 | << Attr; | ||||||
6397 | ND.dropAttr<NotTailCalledAttr>(); | ||||||
6398 | } | ||||||
6399 | |||||||
6400 | // Check the attributes on the function type, if any. | ||||||
6401 | if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { | ||||||
6402 | // Don't declare this variable in the second operand of the for-statement; | ||||||
6403 | // GCC miscompiles that by ending its lifetime before evaluating the | ||||||
6404 | // third operand. See gcc.gnu.org/PR86769. | ||||||
6405 | AttributedTypeLoc ATL; | ||||||
6406 | for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); | ||||||
6407 | (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); | ||||||
6408 | TL = ATL.getModifiedLoc()) { | ||||||
6409 | // The [[lifetimebound]] attribute can be applied to the implicit object | ||||||
6410 | // parameter of a non-static member function (other than a ctor or dtor) | ||||||
6411 | // by applying it to the function type. | ||||||
6412 | if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { | ||||||
6413 | const auto *MD = dyn_cast<CXXMethodDecl>(FD); | ||||||
6414 | if (!MD || MD->isStatic()) { | ||||||
6415 | S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) | ||||||
6416 | << !MD << A->getRange(); | ||||||
6417 | } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { | ||||||
6418 | S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) | ||||||
6419 | << isa<CXXDestructorDecl>(MD) << A->getRange(); | ||||||
6420 | } | ||||||
6421 | } | ||||||
6422 | } | ||||||
6423 | } | ||||||
6424 | } | ||||||
6425 | |||||||
6426 | static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, | ||||||
6427 | NamedDecl *NewDecl, | ||||||
6428 | bool IsSpecialization, | ||||||
6429 | bool IsDefinition) { | ||||||
6430 | if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) | ||||||
6431 | return; | ||||||
6432 | |||||||
6433 | bool IsTemplate = false; | ||||||
6434 | if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { | ||||||
6435 | OldDecl = OldTD->getTemplatedDecl(); | ||||||
6436 | IsTemplate = true; | ||||||
6437 | if (!IsSpecialization) | ||||||
6438 | IsDefinition = false; | ||||||
6439 | } | ||||||
6440 | if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { | ||||||
6441 | NewDecl = NewTD->getTemplatedDecl(); | ||||||
6442 | IsTemplate = true; | ||||||
6443 | } | ||||||
6444 | |||||||
6445 | if (!OldDecl || !NewDecl) | ||||||
6446 | return; | ||||||
6447 | |||||||
6448 | const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); | ||||||
6449 | const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); | ||||||
6450 | const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); | ||||||
6451 | const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); | ||||||
6452 | |||||||
6453 | // dllimport and dllexport are inheritable attributes so we have to exclude | ||||||
6454 | // inherited attribute instances. | ||||||
6455 | bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || | ||||||
6456 | (NewExportAttr && !NewExportAttr->isInherited()); | ||||||
6457 | |||||||
6458 | // A redeclaration is not allowed to add a dllimport or dllexport attribute, | ||||||
6459 | // the only exception being explicit specializations. | ||||||
6460 | // Implicitly generated declarations are also excluded for now because there | ||||||
6461 | // is no other way to switch these to use dllimport or dllexport. | ||||||
6462 | bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; | ||||||
6463 | |||||||
6464 | if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { | ||||||
6465 | // Allow with a warning for free functions and global variables. | ||||||
6466 | bool JustWarn = false; | ||||||
6467 | if (!OldDecl->isCXXClassMember()) { | ||||||
6468 | auto *VD = dyn_cast<VarDecl>(OldDecl); | ||||||
6469 | if (VD && !VD->getDescribedVarTemplate()) | ||||||
6470 | JustWarn = true; | ||||||
6471 | auto *FD = dyn_cast<FunctionDecl>(OldDecl); | ||||||
6472 | if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) | ||||||
6473 | JustWarn = true; | ||||||
6474 | } | ||||||
6475 | |||||||
6476 | // We cannot change a declaration that's been used because IR has already | ||||||
6477 | // been emitted. Dllimported functions will still work though (modulo | ||||||
6478 | // address equality) as they can use the thunk. | ||||||
6479 | if (OldDecl->isUsed()) | ||||||
6480 | if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) | ||||||
6481 | JustWarn = false; | ||||||
6482 | |||||||
6483 | unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration | ||||||
6484 | : diag::err_attribute_dll_redeclaration; | ||||||
6485 | S.Diag(NewDecl->getLocation(), DiagID) | ||||||
6486 | << NewDecl | ||||||
6487 | << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); | ||||||
6488 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6489 | if (!JustWarn) { | ||||||
6490 | NewDecl->setInvalidDecl(); | ||||||
6491 | return; | ||||||
6492 | } | ||||||
6493 | } | ||||||
6494 | |||||||
6495 | // A redeclaration is not allowed to drop a dllimport attribute, the only | ||||||
6496 | // exceptions being inline function definitions (except for function | ||||||
6497 | // templates), local extern declarations, qualified friend declarations or | ||||||
6498 | // special MSVC extension: in the last case, the declaration is treated as if | ||||||
6499 | // it were marked dllexport. | ||||||
6500 | bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; | ||||||
6501 | bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); | ||||||
6502 | if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { | ||||||
6503 | // Ignore static data because out-of-line definitions are diagnosed | ||||||
6504 | // separately. | ||||||
6505 | IsStaticDataMember = VD->isStaticDataMember(); | ||||||
6506 | IsDefinition = VD->isThisDeclarationADefinition(S.Context) != | ||||||
6507 | VarDecl::DeclarationOnly; | ||||||
6508 | } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { | ||||||
6509 | IsInline = FD->isInlined(); | ||||||
6510 | IsQualifiedFriend = FD->getQualifier() && | ||||||
6511 | FD->getFriendObjectKind() == Decl::FOK_Declared; | ||||||
6512 | } | ||||||
6513 | |||||||
6514 | if (OldImportAttr && !HasNewAttr && | ||||||
6515 | (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && | ||||||
6516 | !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { | ||||||
6517 | if (IsMicrosoft && IsDefinition) { | ||||||
6518 | S.Diag(NewDecl->getLocation(), | ||||||
6519 | diag::warn_redeclaration_without_import_attribute) | ||||||
6520 | << NewDecl; | ||||||
6521 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6522 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6523 | NewDecl->addAttr( | ||||||
6524 | DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); | ||||||
6525 | } else { | ||||||
6526 | S.Diag(NewDecl->getLocation(), | ||||||
6527 | diag::warn_redeclaration_without_attribute_prev_attribute_ignored) | ||||||
6528 | << NewDecl << OldImportAttr; | ||||||
6529 | S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); | ||||||
6530 | S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); | ||||||
6531 | OldDecl->dropAttr<DLLImportAttr>(); | ||||||
6532 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6533 | } | ||||||
6534 | } else if (IsInline && OldImportAttr && !IsMicrosoft) { | ||||||
6535 | // In MinGW, seeing a function declared inline drops the dllimport | ||||||
6536 | // attribute. | ||||||
6537 | OldDecl->dropAttr<DLLImportAttr>(); | ||||||
6538 | NewDecl->dropAttr<DLLImportAttr>(); | ||||||
6539 | S.Diag(NewDecl->getLocation(), | ||||||
6540 | diag::warn_dllimport_dropped_from_inline_function) | ||||||
6541 | << NewDecl << OldImportAttr; | ||||||
6542 | } | ||||||
6543 | |||||||
6544 | // A specialization of a class template member function is processed here | ||||||
6545 | // since it's a redeclaration. If the parent class is dllexport, the | ||||||
6546 | // specialization inherits that attribute. This doesn't happen automatically | ||||||
6547 | // since the parent class isn't instantiated until later. | ||||||
6548 | if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { | ||||||
6549 | if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && | ||||||
6550 | !NewImportAttr && !NewExportAttr) { | ||||||
6551 | if (const DLLExportAttr *ParentExportAttr = | ||||||
6552 | MD->getParent()->getAttr<DLLExportAttr>()) { | ||||||
6553 | DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); | ||||||
6554 | NewAttr->setInherited(true); | ||||||
6555 | NewDecl->addAttr(NewAttr); | ||||||
6556 | } | ||||||
6557 | } | ||||||
6558 | } | ||||||
6559 | } | ||||||
6560 | |||||||
6561 | /// Given that we are within the definition of the given function, | ||||||
6562 | /// will that definition behave like C99's 'inline', where the | ||||||
6563 | /// definition is discarded except for optimization purposes? | ||||||
6564 | static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { | ||||||
6565 | // Try to avoid calling GetGVALinkageForFunction. | ||||||
6566 | |||||||
6567 | // All cases of this require the 'inline' keyword. | ||||||
6568 | if (!FD->isInlined()) return false; | ||||||
6569 | |||||||
6570 | // This is only possible in C++ with the gnu_inline attribute. | ||||||
6571 | if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) | ||||||
6572 | return false; | ||||||
6573 | |||||||
6574 | // Okay, go ahead and call the relatively-more-expensive function. | ||||||
6575 | return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; | ||||||
6576 | } | ||||||
6577 | |||||||
6578 | /// Determine whether a variable is extern "C" prior to attaching | ||||||
6579 | /// an initializer. We can't just call isExternC() here, because that | ||||||
6580 | /// will also compute and cache whether the declaration is externally | ||||||
6581 | /// visible, which might change when we attach the initializer. | ||||||
6582 | /// | ||||||
6583 | /// This can only be used if the declaration is known to not be a | ||||||
6584 | /// redeclaration of an internal linkage declaration. | ||||||
6585 | /// | ||||||
6586 | /// For instance: | ||||||
6587 | /// | ||||||
6588 | /// auto x = []{}; | ||||||
6589 | /// | ||||||
6590 | /// Attaching the initializer here makes this declaration not externally | ||||||
6591 | /// visible, because its type has internal linkage. | ||||||
6592 | /// | ||||||
6593 | /// FIXME: This is a hack. | ||||||
6594 | template<typename T> | ||||||
6595 | static bool isIncompleteDeclExternC(Sema &S, const T *D) { | ||||||
6596 | if (S.getLangOpts().CPlusPlus) { | ||||||
6597 | // In C++, the overloadable attribute negates the effects of extern "C". | ||||||
6598 | if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) | ||||||
6599 | return false; | ||||||
6600 | |||||||
6601 | // So do CUDA's host/device attributes. | ||||||
6602 | if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || | ||||||
6603 | D->template hasAttr<CUDAHostAttr>())) | ||||||
6604 | return false; | ||||||
6605 | } | ||||||
6606 | return D->isExternC(); | ||||||
6607 | } | ||||||
6608 | |||||||
6609 | static bool shouldConsiderLinkage(const VarDecl *VD) { | ||||||
6610 | const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); | ||||||
6611 | if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || | ||||||
6612 | isa<OMPDeclareMapperDecl>(DC)) | ||||||
6613 | return VD->hasExternalStorage(); | ||||||
6614 | if (DC->isFileContext()) | ||||||
6615 | return true; | ||||||
6616 | if (DC->isRecord()) | ||||||
6617 | return false; | ||||||
6618 | if (isa<RequiresExprBodyDecl>(DC)) | ||||||
6619 | return false; | ||||||
6620 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6620); | ||||||
6621 | } | ||||||
6622 | |||||||
6623 | static bool shouldConsiderLinkage(const FunctionDecl *FD) { | ||||||
6624 | const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); | ||||||
6625 | if (DC->isFileContext() || DC->isFunctionOrMethod() || | ||||||
6626 | isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) | ||||||
6627 | return true; | ||||||
6628 | if (DC->isRecord()) | ||||||
6629 | return false; | ||||||
6630 | llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6630); | ||||||
6631 | } | ||||||
6632 | |||||||
6633 | static bool hasParsedAttr(Scope *S, const Declarator &PD, | ||||||
6634 | ParsedAttr::Kind Kind) { | ||||||
6635 | // Check decl attributes on the DeclSpec. | ||||||
6636 | if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) | ||||||
6637 | return true; | ||||||
6638 | |||||||
6639 | // Walk the declarator structure, checking decl attributes that were in a type | ||||||
6640 | // position to the decl itself. | ||||||
6641 | for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { | ||||||
6642 | if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) | ||||||
6643 | return true; | ||||||
6644 | } | ||||||
6645 | |||||||
6646 | // Finally, check attributes on the decl itself. | ||||||
6647 | return PD.getAttributes().hasAttribute(Kind); | ||||||
6648 | } | ||||||
6649 | |||||||
6650 | /// Adjust the \c DeclContext for a function or variable that might be a | ||||||
6651 | /// function-local external declaration. | ||||||
6652 | bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { | ||||||
6653 | if (!DC->isFunctionOrMethod()) | ||||||
6654 | return false; | ||||||
6655 | |||||||
6656 | // If this is a local extern function or variable declared within a function | ||||||
6657 | // template, don't add it into the enclosing namespace scope until it is | ||||||
6658 | // instantiated; it might have a dependent type right now. | ||||||
6659 | if (DC->isDependentContext()) | ||||||
6660 | return true; | ||||||
6661 | |||||||
6662 | // C++11 [basic.link]p7: | ||||||
6663 | // When a block scope declaration of an entity with linkage is not found to | ||||||
6664 | // refer to some other declaration, then that entity is a member of the | ||||||
6665 | // innermost enclosing namespace. | ||||||
6666 | // | ||||||
6667 | // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a | ||||||
6668 | // semantically-enclosing namespace, not a lexically-enclosing one. | ||||||
6669 | while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) | ||||||
6670 | DC = DC->getParent(); | ||||||
6671 | return true; | ||||||
6672 | } | ||||||
6673 | |||||||
6674 | /// Returns true if given declaration has external C language linkage. | ||||||
6675 | static bool isDeclExternC(const Decl *D) { | ||||||
6676 | if (const auto *FD = dyn_cast<FunctionDecl>(D)) | ||||||
6677 | return FD->isExternC(); | ||||||
6678 | if (const auto *VD = dyn_cast<VarDecl>(D)) | ||||||
6679 | return VD->isExternC(); | ||||||
6680 | |||||||
6681 | llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6681); | ||||||
6682 | } | ||||||
6683 | /// Returns true if there hasn't been any invalid type diagnosed. | ||||||
6684 | static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, | ||||||
6685 | DeclContext *DC, QualType R) { | ||||||
6686 | // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. | ||||||
6687 | // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function | ||||||
6688 | // argument. | ||||||
6689 | if (R->isImageType() || R->isPipeType()) { | ||||||
6690 | Se.Diag(D.getIdentifierLoc(), | ||||||
6691 | diag::err_opencl_type_can_only_be_used_as_function_parameter) | ||||||
6692 | << R; | ||||||
6693 | D.setInvalidType(); | ||||||
6694 | return false; | ||||||
6695 | } | ||||||
6696 | |||||||
6697 | // OpenCL v1.2 s6.9.r: | ||||||
6698 | // The event type cannot be used to declare a program scope variable. | ||||||
6699 | // OpenCL v2.0 s6.9.q: | ||||||
6700 | // The clk_event_t and reserve_id_t types cannot be declared in program | ||||||
6701 | // scope. | ||||||
6702 | if (NULL__null == S->getParent()) { | ||||||
6703 | if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { | ||||||
6704 | Se.Diag(D.getIdentifierLoc(), | ||||||
6705 | diag::err_invalid_type_for_program_scope_var) | ||||||
6706 | << R; | ||||||
6707 | D.setInvalidType(); | ||||||
6708 | return false; | ||||||
6709 | } | ||||||
6710 | } | ||||||
6711 | |||||||
6712 | // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. | ||||||
6713 | QualType NR = R; | ||||||
6714 | while (NR->isPointerType()) { | ||||||
6715 | if (NR->isFunctionPointerType()) { | ||||||
6716 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); | ||||||
6717 | D.setInvalidType(); | ||||||
6718 | return false; | ||||||
6719 | } | ||||||
6720 | NR = NR->getPointeeType(); | ||||||
6721 | } | ||||||
6722 | |||||||
6723 | if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { | ||||||
6724 | // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and | ||||||
6725 | // half array type (unless the cl_khr_fp16 extension is enabled). | ||||||
6726 | if (Se.Context.getBaseElementType(R)->isHalfType()) { | ||||||
6727 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; | ||||||
6728 | D.setInvalidType(); | ||||||
6729 | return false; | ||||||
6730 | } | ||||||
6731 | } | ||||||
6732 | |||||||
6733 | // OpenCL v1.2 s6.9.r: | ||||||
6734 | // The event type cannot be used with the __local, __constant and __global | ||||||
6735 | // address space qualifiers. | ||||||
6736 | if (R->isEventT()) { | ||||||
6737 | if (R.getAddressSpace() != LangAS::opencl_private) { | ||||||
6738 | Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); | ||||||
6739 | D.setInvalidType(); | ||||||
6740 | return false; | ||||||
6741 | } | ||||||
6742 | } | ||||||
6743 | |||||||
6744 | // C++ for OpenCL does not allow the thread_local storage qualifier. | ||||||
6745 | // OpenCL C does not support thread_local either, and | ||||||
6746 | // also reject all other thread storage class specifiers. | ||||||
6747 | DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); | ||||||
6748 | if (TSC != TSCS_unspecified) { | ||||||
6749 | bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; | ||||||
6750 | Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
6751 | diag::err_opencl_unknown_type_specifier) | ||||||
6752 | << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() | ||||||
6753 | << DeclSpec::getSpecifierName(TSC) << 1; | ||||||
6754 | D.setInvalidType(); | ||||||
6755 | return false; | ||||||
6756 | } | ||||||
6757 | |||||||
6758 | if (R->isSamplerT()) { | ||||||
6759 | // OpenCL v1.2 s6.9.b p4: | ||||||
6760 | // The sampler type cannot be used with the __local and __global address | ||||||
6761 | // space qualifiers. | ||||||
6762 | if (R.getAddressSpace() == LangAS::opencl_local || | ||||||
6763 | R.getAddressSpace() == LangAS::opencl_global) { | ||||||
6764 | Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); | ||||||
6765 | D.setInvalidType(); | ||||||
6766 | } | ||||||
6767 | |||||||
6768 | // OpenCL v1.2 s6.12.14.1: | ||||||
6769 | // A global sampler must be declared with either the constant address | ||||||
6770 | // space qualifier or with the const qualifier. | ||||||
6771 | if (DC->isTranslationUnit() && | ||||||
6772 | !(R.getAddressSpace() == LangAS::opencl_constant || | ||||||
6773 | R.isConstQualified())) { | ||||||
6774 | Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); | ||||||
6775 | D.setInvalidType(); | ||||||
6776 | } | ||||||
6777 | if (D.isInvalidType()) | ||||||
6778 | return false; | ||||||
6779 | } | ||||||
6780 | return true; | ||||||
6781 | } | ||||||
6782 | |||||||
6783 | NamedDecl *Sema::ActOnVariableDeclarator( | ||||||
6784 | Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, | ||||||
6785 | LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, | ||||||
6786 | bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { | ||||||
6787 | QualType R = TInfo->getType(); | ||||||
6788 | DeclarationName Name = GetNameForDeclarator(D).getName(); | ||||||
6789 | |||||||
6790 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||
6791 | |||||||
6792 | if (D.isDecompositionDeclarator()) { | ||||||
6793 | // Take the name of the first declarator as our name for diagnostic | ||||||
6794 | // purposes. | ||||||
6795 | auto &Decomp = D.getDecompositionDeclarator(); | ||||||
6796 | if (!Decomp.bindings().empty()) { | ||||||
6797 | II = Decomp.bindings()[0].Name; | ||||||
6798 | Name = II; | ||||||
6799 | } | ||||||
6800 | } else if (!II) { | ||||||
6801 | Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; | ||||||
6802 | return nullptr; | ||||||
6803 | } | ||||||
6804 | |||||||
6805 | |||||||
6806 | DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); | ||||||
6807 | StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); | ||||||
6808 | |||||||
6809 | // dllimport globals without explicit storage class are treated as extern. We | ||||||
6810 | // have to change the storage class this early to get the right DeclContext. | ||||||
6811 | if (SC == SC_None && !DC->isRecord() && | ||||||
6812 | hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && | ||||||
6813 | !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) | ||||||
6814 | SC = SC_Extern; | ||||||
6815 | |||||||
6816 | DeclContext *OriginalDC = DC; | ||||||
6817 | bool IsLocalExternDecl = SC == SC_Extern && | ||||||
6818 | adjustContextForLocalExternDecl(DC); | ||||||
6819 | |||||||
6820 | if (SCSpec == DeclSpec::SCS_mutable) { | ||||||
6821 | // mutable can only appear on non-static class members, so it's always | ||||||
6822 | // an error here | ||||||
6823 | Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); | ||||||
6824 | D.setInvalidType(); | ||||||
6825 | SC = SC_None; | ||||||
6826 | } | ||||||
6827 | |||||||
6828 | if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && | ||||||
6829 | !D.getAsmLabel() && !getSourceManager().isInSystemMacro( | ||||||
6830 | D.getDeclSpec().getStorageClassSpecLoc())) { | ||||||
6831 | // In C++11, the 'register' storage class specifier is deprecated. | ||||||
6832 | // Suppress the warning in system macros, it's used in macros in some | ||||||
6833 | // popular C system headers, such as in glibc's htonl() macro. | ||||||
6834 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6835 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||||
6836 | : diag::warn_deprecated_register) | ||||||
6837 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6838 | } | ||||||
6839 | |||||||
6840 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
6841 | |||||||
6842 | if (!DC->isRecord() && S->getFnParent() == nullptr) { | ||||||
6843 | // C99 6.9p2: The storage-class specifiers auto and register shall not | ||||||
6844 | // appear in the declaration specifiers in an external declaration. | ||||||
6845 | // Global Register+Asm is a GNU extension we support. | ||||||
6846 | if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { | ||||||
6847 | Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); | ||||||
6848 | D.setInvalidType(); | ||||||
6849 | } | ||||||
6850 | } | ||||||
6851 | |||||||
6852 | bool IsMemberSpecialization = false; | ||||||
6853 | bool IsVariableTemplateSpecialization = false; | ||||||
6854 | bool IsPartialSpecialization = false; | ||||||
6855 | bool IsVariableTemplate = false; | ||||||
6856 | VarDecl *NewVD = nullptr; | ||||||
6857 | VarTemplateDecl *NewTemplate = nullptr; | ||||||
6858 | TemplateParameterList *TemplateParams = nullptr; | ||||||
6859 | if (!getLangOpts().CPlusPlus) { | ||||||
6860 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), | ||||||
6861 | II, R, TInfo, SC); | ||||||
6862 | |||||||
6863 | if (R->getContainedDeducedType()) | ||||||
6864 | ParsingInitForAutoVars.insert(NewVD); | ||||||
6865 | |||||||
6866 | if (D.isInvalidType()) | ||||||
6867 | NewVD->setInvalidDecl(); | ||||||
6868 | |||||||
6869 | if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && | ||||||
6870 | NewVD->hasLocalStorage()) | ||||||
6871 | checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), | ||||||
6872 | NTCUC_AutoVar, NTCUK_Destruct); | ||||||
6873 | } else { | ||||||
6874 | bool Invalid = false; | ||||||
6875 | |||||||
6876 | if (DC->isRecord() && !CurContext->isRecord()) { | ||||||
6877 | // This is an out-of-line definition of a static data member. | ||||||
6878 | switch (SC) { | ||||||
6879 | case SC_None: | ||||||
6880 | break; | ||||||
6881 | case SC_Static: | ||||||
6882 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6883 | diag::err_static_out_of_line) | ||||||
6884 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6885 | break; | ||||||
6886 | case SC_Auto: | ||||||
6887 | case SC_Register: | ||||||
6888 | case SC_Extern: | ||||||
6889 | // [dcl.stc] p2: The auto or register specifiers shall be applied only | ||||||
6890 | // to names of variables declared in a block or to function parameters. | ||||||
6891 | // [dcl.stc] p6: The extern specifier cannot be used in the declaration | ||||||
6892 | // of class members | ||||||
6893 | |||||||
6894 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
6895 | diag::err_storage_class_for_static_member) | ||||||
6896 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
6897 | break; | ||||||
6898 | case SC_PrivateExtern: | ||||||
6899 | llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6899); | ||||||
6900 | } | ||||||
6901 | } | ||||||
6902 | |||||||
6903 | if (SC == SC_Static && CurContext->isRecord()) { | ||||||
6904 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { | ||||||
6905 | // Walk up the enclosing DeclContexts to check for any that are | ||||||
6906 | // incompatible with static data members. | ||||||
6907 | const DeclContext *FunctionOrMethod = nullptr; | ||||||
6908 | const CXXRecordDecl *AnonStruct = nullptr; | ||||||
6909 | for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) { | ||||||
6910 | if (Ctxt->isFunctionOrMethod()) { | ||||||
6911 | FunctionOrMethod = Ctxt; | ||||||
6912 | break; | ||||||
6913 | } | ||||||
6914 | const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt); | ||||||
6915 | if (ParentDecl && !ParentDecl->getDeclName()) { | ||||||
6916 | AnonStruct = ParentDecl; | ||||||
6917 | break; | ||||||
6918 | } | ||||||
6919 | } | ||||||
6920 | if (FunctionOrMethod) { | ||||||
6921 | // C++ [class.static.data]p5: A local class shall not have static data | ||||||
6922 | // members. | ||||||
6923 | Diag(D.getIdentifierLoc(), | ||||||
6924 | diag::err_static_data_member_not_allowed_in_local_class) | ||||||
6925 | << Name << RD->getDeclName() << RD->getTagKind(); | ||||||
6926 | } else if (AnonStruct) { | ||||||
6927 | // C++ [class.static.data]p4: Unnamed classes and classes contained | ||||||
6928 | // directly or indirectly within unnamed classes shall not contain | ||||||
6929 | // static data members. | ||||||
6930 | Diag(D.getIdentifierLoc(), | ||||||
6931 | diag::err_static_data_member_not_allowed_in_anon_struct) | ||||||
6932 | << Name << AnonStruct->getTagKind(); | ||||||
6933 | Invalid = true; | ||||||
6934 | } else if (RD->isUnion()) { | ||||||
6935 | // C++98 [class.union]p1: If a union contains a static data member, | ||||||
6936 | // the program is ill-formed. C++11 drops this restriction. | ||||||
6937 | Diag(D.getIdentifierLoc(), | ||||||
6938 | getLangOpts().CPlusPlus11 | ||||||
6939 | ? diag::warn_cxx98_compat_static_data_member_in_union | ||||||
6940 | : diag::ext_static_data_member_in_union) << Name; | ||||||
6941 | } | ||||||
6942 | } | ||||||
6943 | } | ||||||
6944 | |||||||
6945 | // Match up the template parameter lists with the scope specifier, then | ||||||
6946 | // determine whether we have a template or a template specialization. | ||||||
6947 | bool InvalidScope = false; | ||||||
6948 | TemplateParams = MatchTemplateParametersToScopeSpecifier( | ||||||
6949 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||||
6950 | D.getCXXScopeSpec(), | ||||||
6951 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||||
6952 | ? D.getName().TemplateId | ||||||
6953 | : nullptr, | ||||||
6954 | TemplateParamLists, | ||||||
6955 | /*never a friend*/ false, IsMemberSpecialization, InvalidScope); | ||||||
6956 | Invalid |= InvalidScope; | ||||||
6957 | |||||||
6958 | if (TemplateParams) { | ||||||
6959 | if (!TemplateParams->size() && | ||||||
6960 | D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||||
6961 | // There is an extraneous 'template<>' for this variable. Complain | ||||||
6962 | // about it, but allow the declaration of the variable. | ||||||
6963 | Diag(TemplateParams->getTemplateLoc(), | ||||||
6964 | diag::err_template_variable_noparams) | ||||||
6965 | << II | ||||||
6966 | << SourceRange(TemplateParams->getTemplateLoc(), | ||||||
6967 | TemplateParams->getRAngleLoc()); | ||||||
6968 | TemplateParams = nullptr; | ||||||
6969 | } else { | ||||||
6970 | // Check that we can declare a template here. | ||||||
6971 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||||
6972 | return nullptr; | ||||||
6973 | |||||||
6974 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||
6975 | // This is an explicit specialization or a partial specialization. | ||||||
6976 | IsVariableTemplateSpecialization = true; | ||||||
6977 | IsPartialSpecialization = TemplateParams->size() > 0; | ||||||
6978 | } else { // if (TemplateParams->size() > 0) | ||||||
6979 | // This is a template declaration. | ||||||
6980 | IsVariableTemplate = true; | ||||||
6981 | |||||||
6982 | // Only C++1y supports variable templates (N3651). | ||||||
6983 | Diag(D.getIdentifierLoc(), | ||||||
6984 | getLangOpts().CPlusPlus14 | ||||||
6985 | ? diag::warn_cxx11_compat_variable_template | ||||||
6986 | : diag::ext_variable_template); | ||||||
6987 | } | ||||||
6988 | } | ||||||
6989 | } else { | ||||||
6990 | // Check that we can declare a member specialization here. | ||||||
6991 | if (!TemplateParamLists.empty() && IsMemberSpecialization && | ||||||
6992 | CheckTemplateDeclScope(S, TemplateParamLists.back())) | ||||||
6993 | return nullptr; | ||||||
6994 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6996, __PRETTY_FUNCTION__)) | ||||||
6995 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6996, __PRETTY_FUNCTION__)) | ||||||
6996 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 6996, __PRETTY_FUNCTION__)); | ||||||
6997 | } | ||||||
6998 | |||||||
6999 | if (IsVariableTemplateSpecialization) { | ||||||
7000 | SourceLocation TemplateKWLoc = | ||||||
7001 | TemplateParamLists.size() > 0 | ||||||
7002 | ? TemplateParamLists[0]->getTemplateLoc() | ||||||
7003 | : SourceLocation(); | ||||||
7004 | DeclResult Res = ActOnVarTemplateSpecialization( | ||||||
7005 | S, D, TInfo, TemplateKWLoc, TemplateParams, SC, | ||||||
7006 | IsPartialSpecialization); | ||||||
7007 | if (Res.isInvalid()) | ||||||
7008 | return nullptr; | ||||||
7009 | NewVD = cast<VarDecl>(Res.get()); | ||||||
7010 | AddToScope = false; | ||||||
7011 | } else if (D.isDecompositionDeclarator()) { | ||||||
7012 | NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), | ||||||
7013 | D.getIdentifierLoc(), R, TInfo, SC, | ||||||
7014 | Bindings); | ||||||
7015 | } else | ||||||
7016 | NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), | ||||||
7017 | D.getIdentifierLoc(), II, R, TInfo, SC); | ||||||
7018 | |||||||
7019 | // If this is supposed to be a variable template, create it as such. | ||||||
7020 | if (IsVariableTemplate) { | ||||||
7021 | NewTemplate = | ||||||
7022 | VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, | ||||||
7023 | TemplateParams, NewVD); | ||||||
7024 | NewVD->setDescribedVarTemplate(NewTemplate); | ||||||
7025 | } | ||||||
7026 | |||||||
7027 | // If this decl has an auto type in need of deduction, make a note of the | ||||||
7028 | // Decl so we can diagnose uses of it in its own initializer. | ||||||
7029 | if (R->getContainedDeducedType()) | ||||||
7030 | ParsingInitForAutoVars.insert(NewVD); | ||||||
7031 | |||||||
7032 | if (D.isInvalidType() || Invalid) { | ||||||
7033 | NewVD->setInvalidDecl(); | ||||||
7034 | if (NewTemplate) | ||||||
7035 | NewTemplate->setInvalidDecl(); | ||||||
7036 | } | ||||||
7037 | |||||||
7038 | SetNestedNameSpecifier(*this, NewVD, D); | ||||||
7039 | |||||||
7040 | // If we have any template parameter lists that don't directly belong to | ||||||
7041 | // the variable (matching the scope specifier), store them. | ||||||
7042 | unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; | ||||||
7043 | if (TemplateParamLists.size() > VDTemplateParamLists) | ||||||
7044 | NewVD->setTemplateParameterListsInfo( | ||||||
7045 | Context, TemplateParamLists.drop_back(VDTemplateParamLists)); | ||||||
7046 | } | ||||||
7047 | |||||||
7048 | if (D.getDeclSpec().isInlineSpecified()) { | ||||||
7049 | if (!getLangOpts().CPlusPlus) { | ||||||
7050 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
7051 | << 0; | ||||||
7052 | } else if (CurContext->isFunctionOrMethod()) { | ||||||
7053 | // 'inline' is not allowed on block scope variable declaration. | ||||||
7054 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
7055 | diag::err_inline_declaration_block_scope) << Name | ||||||
7056 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||||
7057 | } else { | ||||||
7058 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
7059 | getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable | ||||||
7060 | : diag::ext_inline_variable); | ||||||
7061 | NewVD->setInlineSpecified(); | ||||||
7062 | } | ||||||
7063 | } | ||||||
7064 | |||||||
7065 | // Set the lexical context. If the declarator has a C++ scope specifier, the | ||||||
7066 | // lexical context will be different from the semantic context. | ||||||
7067 | NewVD->setLexicalDeclContext(CurContext); | ||||||
7068 | if (NewTemplate) | ||||||
7069 | NewTemplate->setLexicalDeclContext(CurContext); | ||||||
7070 | |||||||
7071 | if (IsLocalExternDecl) { | ||||||
7072 | if (D.isDecompositionDeclarator()) | ||||||
7073 | for (auto *B : Bindings) | ||||||
7074 | B->setLocalExternDecl(); | ||||||
7075 | else | ||||||
7076 | NewVD->setLocalExternDecl(); | ||||||
7077 | } | ||||||
7078 | |||||||
7079 | bool EmitTLSUnsupportedError = false; | ||||||
7080 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { | ||||||
7081 | // C++11 [dcl.stc]p4: | ||||||
7082 | // When thread_local is applied to a variable of block scope the | ||||||
7083 | // storage-class-specifier static is implied if it does not appear | ||||||
7084 | // explicitly. | ||||||
7085 | // Core issue: 'static' is not implied if the variable is declared | ||||||
7086 | // 'extern'. | ||||||
7087 | if (NewVD->hasLocalStorage() && | ||||||
7088 | (SCSpec != DeclSpec::SCS_unspecified || | ||||||
7089 | TSCS != DeclSpec::TSCS_thread_local || | ||||||
7090 | !DC->isFunctionOrMethod())) | ||||||
7091 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
7092 | diag::err_thread_non_global) | ||||||
7093 | << DeclSpec::getSpecifierName(TSCS); | ||||||
7094 | else if (!Context.getTargetInfo().isTLSSupported()) { | ||||||
7095 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || | ||||||
7096 | getLangOpts().SYCLIsDevice) { | ||||||
7097 | // Postpone error emission until we've collected attributes required to | ||||||
7098 | // figure out whether it's a host or device variable and whether the | ||||||
7099 | // error should be ignored. | ||||||
7100 | EmitTLSUnsupportedError = true; | ||||||
7101 | // We still need to mark the variable as TLS so it shows up in AST with | ||||||
7102 | // proper storage class for other tools to use even if we're not going | ||||||
7103 | // to emit any code for it. | ||||||
7104 | NewVD->setTSCSpec(TSCS); | ||||||
7105 | } else | ||||||
7106 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
7107 | diag::err_thread_unsupported); | ||||||
7108 | } else | ||||||
7109 | NewVD->setTSCSpec(TSCS); | ||||||
7110 | } | ||||||
7111 | |||||||
7112 | switch (D.getDeclSpec().getConstexprSpecifier()) { | ||||||
7113 | case CSK_unspecified: | ||||||
7114 | break; | ||||||
7115 | |||||||
7116 | case CSK_consteval: | ||||||
7117 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
7118 | diag::err_constexpr_wrong_decl_kind) | ||||||
7119 | << D.getDeclSpec().getConstexprSpecifier(); | ||||||
7120 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
7121 | |||||||
7122 | case CSK_constexpr: | ||||||
7123 | NewVD->setConstexpr(true); | ||||||
7124 | MaybeAddCUDAConstantAttr(NewVD); | ||||||
7125 | // C++1z [dcl.spec.constexpr]p1: | ||||||
7126 | // A static data member declared with the constexpr specifier is | ||||||
7127 | // implicitly an inline variable. | ||||||
7128 | if (NewVD->isStaticDataMember() && | ||||||
7129 | (getLangOpts().CPlusPlus17 || | ||||||
7130 | Context.getTargetInfo().getCXXABI().isMicrosoft())) | ||||||
7131 | NewVD->setImplicitlyInline(); | ||||||
7132 | break; | ||||||
7133 | |||||||
7134 | case CSK_constinit: | ||||||
7135 | if (!NewVD->hasGlobalStorage()) | ||||||
7136 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
7137 | diag::err_constinit_local_variable); | ||||||
7138 | else | ||||||
7139 | NewVD->addAttr(ConstInitAttr::Create( | ||||||
7140 | Context, D.getDeclSpec().getConstexprSpecLoc(), | ||||||
7141 | AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); | ||||||
7142 | break; | ||||||
7143 | } | ||||||
7144 | |||||||
7145 | // C99 6.7.4p3 | ||||||
7146 | // An inline definition of a function with external linkage shall | ||||||
7147 | // not contain a definition of a modifiable object with static or | ||||||
7148 | // thread storage duration... | ||||||
7149 | // We only apply this when the function is required to be defined | ||||||
7150 | // elsewhere, i.e. when the function is not 'extern inline'. Note | ||||||
7151 | // that a local variable with thread storage duration still has to | ||||||
7152 | // be marked 'static'. Also note that it's possible to get these | ||||||
7153 | // semantics in C++ using __attribute__((gnu_inline)). | ||||||
7154 | if (SC == SC_Static && S->getFnParent() != nullptr && | ||||||
7155 | !NewVD->getType().isConstQualified()) { | ||||||
7156 | FunctionDecl *CurFD = getCurFunctionDecl(); | ||||||
7157 | if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { | ||||||
7158 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
7159 | diag::warn_static_local_in_extern_inline); | ||||||
7160 | MaybeSuggestAddingStaticToDecl(CurFD); | ||||||
7161 | } | ||||||
7162 | } | ||||||
7163 | |||||||
7164 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
7165 | if (IsVariableTemplateSpecialization) | ||||||
7166 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||||
7167 | << (IsPartialSpecialization ? 1 : 0) | ||||||
7168 | << FixItHint::CreateRemoval( | ||||||
7169 | D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
7170 | else if (IsMemberSpecialization) | ||||||
7171 | Diag(NewVD->getLocation(), diag::err_module_private_specialization) | ||||||
7172 | << 2 | ||||||
7173 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
7174 | else if (NewVD->hasLocalStorage()) | ||||||
7175 | Diag(NewVD->getLocation(), diag::err_module_private_local) | ||||||
7176 | << 0 << NewVD | ||||||
7177 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
7178 | << FixItHint::CreateRemoval( | ||||||
7179 | D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
7180 | else { | ||||||
7181 | NewVD->setModulePrivate(); | ||||||
7182 | if (NewTemplate) | ||||||
7183 | NewTemplate->setModulePrivate(); | ||||||
7184 | for (auto *B : Bindings) | ||||||
7185 | B->setModulePrivate(); | ||||||
7186 | } | ||||||
7187 | } | ||||||
7188 | |||||||
7189 | if (getLangOpts().OpenCL) { | ||||||
7190 | |||||||
7191 | deduceOpenCLAddressSpace(NewVD); | ||||||
7192 | |||||||
7193 | diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); | ||||||
7194 | } | ||||||
7195 | |||||||
7196 | // Handle attributes prior to checking for duplicates in MergeVarDecl | ||||||
7197 | ProcessDeclAttributes(S, NewVD, D); | ||||||
7198 | |||||||
7199 | if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice || | ||||||
7200 | getLangOpts().SYCLIsDevice) { | ||||||
7201 | if (EmitTLSUnsupportedError && | ||||||
7202 | ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || | ||||||
7203 | (getLangOpts().OpenMPIsDevice && | ||||||
7204 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) | ||||||
7205 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
7206 | diag::err_thread_unsupported); | ||||||
7207 | |||||||
7208 | if (EmitTLSUnsupportedError && | ||||||
7209 | (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))) | ||||||
7210 | targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported); | ||||||
7211 | // CUDA B.2.5: "__shared__ and __constant__ variables have implied static | ||||||
7212 | // storage [duration]." | ||||||
7213 | if (SC == SC_None && S->getFnParent() != nullptr && | ||||||
7214 | (NewVD->hasAttr<CUDASharedAttr>() || | ||||||
7215 | NewVD->hasAttr<CUDAConstantAttr>())) { | ||||||
7216 | NewVD->setStorageClass(SC_Static); | ||||||
7217 | } | ||||||
7218 | } | ||||||
7219 | |||||||
7220 | // Ensure that dllimport globals without explicit storage class are treated as | ||||||
7221 | // extern. The storage class is set above using parsed attributes. Now we can | ||||||
7222 | // check the VarDecl itself. | ||||||
7223 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 7225, __PRETTY_FUNCTION__)) | ||||||
7224 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 7225, __PRETTY_FUNCTION__)) | ||||||
7225 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 7225, __PRETTY_FUNCTION__)); | ||||||
7226 | |||||||
7227 | // In auto-retain/release, infer strong retension for variables of | ||||||
7228 | // retainable type. | ||||||
7229 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) | ||||||
7230 | NewVD->setInvalidDecl(); | ||||||
7231 | |||||||
7232 | // Handle GNU asm-label extension (encoded as an attribute). | ||||||
7233 | if (Expr *E = (Expr*)D.getAsmLabel()) { | ||||||
7234 | // The parser guarantees this is a string. | ||||||
7235 | StringLiteral *SE = cast<StringLiteral>(E); | ||||||
7236 | StringRef Label = SE->getString(); | ||||||
7237 | if (S->getFnParent() != nullptr) { | ||||||
7238 | switch (SC) { | ||||||
7239 | case SC_None: | ||||||
7240 | case SC_Auto: | ||||||
7241 | Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; | ||||||
7242 | break; | ||||||
7243 | case SC_Register: | ||||||
7244 | // Local Named register | ||||||
7245 | if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && | ||||||
7246 | DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) | ||||||
7247 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||||
7248 | break; | ||||||
7249 | case SC_Static: | ||||||
7250 | case SC_Extern: | ||||||
7251 | case SC_PrivateExtern: | ||||||
7252 | break; | ||||||
7253 | } | ||||||
7254 | } else if (SC == SC_Register) { | ||||||
7255 | // Global Named register | ||||||
7256 | if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { | ||||||
7257 | const auto &TI = Context.getTargetInfo(); | ||||||
7258 | bool HasSizeMismatch; | ||||||
7259 | |||||||
7260 | if (!TI.isValidGCCRegisterName(Label)) | ||||||
7261 | Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; | ||||||
7262 | else if (!TI.validateGlobalRegisterVariable(Label, | ||||||
7263 | Context.getTypeSize(R), | ||||||
7264 | HasSizeMismatch)) | ||||||
7265 | Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; | ||||||
7266 | else if (HasSizeMismatch) | ||||||
7267 | Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; | ||||||
7268 | } | ||||||
7269 | |||||||
7270 | if (!R->isIntegralType(Context) && !R->isPointerType()) { | ||||||
7271 | Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); | ||||||
7272 | NewVD->setInvalidDecl(true); | ||||||
7273 | } | ||||||
7274 | } | ||||||
7275 | |||||||
7276 | NewVD->addAttr(AsmLabelAttr::Create(Context, Label, | ||||||
7277 | /*IsLiteralLabel=*/true, | ||||||
7278 | SE->getStrTokenLoc(0))); | ||||||
7279 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||||
7280 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||||
7281 | ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); | ||||||
7282 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||||
7283 | if (isDeclExternC(NewVD)) { | ||||||
7284 | NewVD->addAttr(I->second); | ||||||
7285 | ExtnameUndeclaredIdentifiers.erase(I); | ||||||
7286 | } else | ||||||
7287 | Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
7288 | << /*Variable*/1 << NewVD; | ||||||
7289 | } | ||||||
7290 | } | ||||||
7291 | |||||||
7292 | // Find the shadowed declaration before filtering for scope. | ||||||
7293 | NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() | ||||||
7294 | ? getShadowedDeclaration(NewVD, Previous) | ||||||
7295 | : nullptr; | ||||||
7296 | |||||||
7297 | // Don't consider existing declarations that are in a different | ||||||
7298 | // scope and are out-of-semantic-context declarations (if the new | ||||||
7299 | // declaration has linkage). | ||||||
7300 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), | ||||||
7301 | D.getCXXScopeSpec().isNotEmpty() || | ||||||
7302 | IsMemberSpecialization || | ||||||
7303 | IsVariableTemplateSpecialization); | ||||||
7304 | |||||||
7305 | // Check whether the previous declaration is in the same block scope. This | ||||||
7306 | // affects whether we merge types with it, per C++11 [dcl.array]p3. | ||||||
7307 | if (getLangOpts().CPlusPlus && | ||||||
7308 | NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) | ||||||
7309 | NewVD->setPreviousDeclInSameBlockScope( | ||||||
7310 | Previous.isSingleResult() && !Previous.isShadowed() && | ||||||
7311 | isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); | ||||||
7312 | |||||||
7313 | if (!getLangOpts().CPlusPlus) { | ||||||
7314 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||||
7315 | } else { | ||||||
7316 | // If this is an explicit specialization of a static data member, check it. | ||||||
7317 | if (IsMemberSpecialization && !NewVD->isInvalidDecl() && | ||||||
7318 | CheckMemberSpecialization(NewVD, Previous)) | ||||||
7319 | NewVD->setInvalidDecl(); | ||||||
7320 | |||||||
7321 | // Merge the decl with the existing one if appropriate. | ||||||
7322 | if (!Previous.empty()) { | ||||||
7323 | if (Previous.isSingleResult() && | ||||||
7324 | isa<FieldDecl>(Previous.getFoundDecl()) && | ||||||
7325 | D.getCXXScopeSpec().isSet()) { | ||||||
7326 | // The user tried to define a non-static data member | ||||||
7327 | // out-of-line (C++ [dcl.meaning]p1). | ||||||
7328 | Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) | ||||||
7329 | << D.getCXXScopeSpec().getRange(); | ||||||
7330 | Previous.clear(); | ||||||
7331 | NewVD->setInvalidDecl(); | ||||||
7332 | } | ||||||
7333 | } else if (D.getCXXScopeSpec().isSet()) { | ||||||
7334 | // No previous declaration in the qualifying scope. | ||||||
7335 | Diag(D.getIdentifierLoc(), diag::err_no_member) | ||||||
7336 | << Name << computeDeclContext(D.getCXXScopeSpec(), true) | ||||||
7337 | << D.getCXXScopeSpec().getRange(); | ||||||
7338 | NewVD->setInvalidDecl(); | ||||||
7339 | } | ||||||
7340 | |||||||
7341 | if (!IsVariableTemplateSpecialization) | ||||||
7342 | D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); | ||||||
7343 | |||||||
7344 | if (NewTemplate) { | ||||||
7345 | VarTemplateDecl *PrevVarTemplate = | ||||||
7346 | NewVD->getPreviousDecl() | ||||||
7347 | ? NewVD->getPreviousDecl()->getDescribedVarTemplate() | ||||||
7348 | : nullptr; | ||||||
7349 | |||||||
7350 | // Check the template parameter list of this declaration, possibly | ||||||
7351 | // merging in the template parameter list from the previous variable | ||||||
7352 | // template declaration. | ||||||
7353 | if (CheckTemplateParameterList( | ||||||
7354 | TemplateParams, | ||||||
7355 | PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() | ||||||
7356 | : nullptr, | ||||||
7357 | (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && | ||||||
7358 | DC->isDependentContext()) | ||||||
7359 | ? TPC_ClassTemplateMember | ||||||
7360 | : TPC_VarTemplate)) | ||||||
7361 | NewVD->setInvalidDecl(); | ||||||
7362 | |||||||
7363 | // If we are providing an explicit specialization of a static variable | ||||||
7364 | // template, make a note of that. | ||||||
7365 | if (PrevVarTemplate && | ||||||
7366 | PrevVarTemplate->getInstantiatedFromMemberTemplate()) | ||||||
7367 | PrevVarTemplate->setMemberSpecialization(); | ||||||
7368 | } | ||||||
7369 | } | ||||||
7370 | |||||||
7371 | // Diagnose shadowed variables iff this isn't a redeclaration. | ||||||
7372 | if (ShadowedDecl && !D.isRedeclaration()) | ||||||
7373 | CheckShadow(NewVD, ShadowedDecl, Previous); | ||||||
7374 | |||||||
7375 | ProcessPragmaWeak(S, NewVD); | ||||||
7376 | |||||||
7377 | // If this is the first declaration of an extern C variable, update | ||||||
7378 | // the map of such variables. | ||||||
7379 | if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && | ||||||
7380 | isIncompleteDeclExternC(*this, NewVD)) | ||||||
7381 | RegisterLocallyScopedExternCDecl(NewVD, S); | ||||||
7382 | |||||||
7383 | if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { | ||||||
7384 | MangleNumberingContext *MCtx; | ||||||
7385 | Decl *ManglingContextDecl; | ||||||
7386 | std::tie(MCtx, ManglingContextDecl) = | ||||||
7387 | getCurrentMangleNumberContext(NewVD->getDeclContext()); | ||||||
7388 | if (MCtx) { | ||||||
7389 | Context.setManglingNumber( | ||||||
7390 | NewVD, MCtx->getManglingNumber( | ||||||
7391 | NewVD, getMSManglingNumber(getLangOpts(), S))); | ||||||
7392 | Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); | ||||||
7393 | } | ||||||
7394 | } | ||||||
7395 | |||||||
7396 | // Special handling of variable named 'main'. | ||||||
7397 | if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && | ||||||
7398 | NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||||
7399 | !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { | ||||||
7400 | |||||||
7401 | // C++ [basic.start.main]p3 | ||||||
7402 | // A program that declares a variable main at global scope is ill-formed. | ||||||
7403 | if (getLangOpts().CPlusPlus) | ||||||
7404 | Diag(D.getBeginLoc(), diag::err_main_global_variable); | ||||||
7405 | |||||||
7406 | // In C, and external-linkage variable named main results in undefined | ||||||
7407 | // behavior. | ||||||
7408 | else if (NewVD->hasExternalFormalLinkage()) | ||||||
7409 | Diag(D.getBeginLoc(), diag::warn_main_redefined); | ||||||
7410 | } | ||||||
7411 | |||||||
7412 | if (D.isRedeclaration() && !Previous.empty()) { | ||||||
7413 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||||
7414 | checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, | ||||||
7415 | D.isFunctionDefinition()); | ||||||
7416 | } | ||||||
7417 | |||||||
7418 | if (NewTemplate) { | ||||||
7419 | if (NewVD->isInvalidDecl()) | ||||||
7420 | NewTemplate->setInvalidDecl(); | ||||||
7421 | ActOnDocumentableDecl(NewTemplate); | ||||||
7422 | return NewTemplate; | ||||||
7423 | } | ||||||
7424 | |||||||
7425 | if (IsMemberSpecialization && !NewVD->isInvalidDecl()) | ||||||
7426 | CompleteMemberSpecialization(NewVD, Previous); | ||||||
7427 | |||||||
7428 | return NewVD; | ||||||
7429 | } | ||||||
7430 | |||||||
7431 | /// Enum describing the %select options in diag::warn_decl_shadow. | ||||||
7432 | enum ShadowedDeclKind { | ||||||
7433 | SDK_Local, | ||||||
7434 | SDK_Global, | ||||||
7435 | SDK_StaticMember, | ||||||
7436 | SDK_Field, | ||||||
7437 | SDK_Typedef, | ||||||
7438 | SDK_Using | ||||||
7439 | }; | ||||||
7440 | |||||||
7441 | /// Determine what kind of declaration we're shadowing. | ||||||
7442 | static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, | ||||||
7443 | const DeclContext *OldDC) { | ||||||
7444 | if (isa<TypeAliasDecl>(ShadowedDecl)) | ||||||
7445 | return SDK_Using; | ||||||
7446 | else if (isa<TypedefDecl>(ShadowedDecl)) | ||||||
7447 | return SDK_Typedef; | ||||||
7448 | else if (isa<RecordDecl>(OldDC)) | ||||||
7449 | return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; | ||||||
7450 | |||||||
7451 | return OldDC->isFileContext() ? SDK_Global : SDK_Local; | ||||||
7452 | } | ||||||
7453 | |||||||
7454 | /// Return the location of the capture if the given lambda captures the given | ||||||
7455 | /// variable \p VD, or an invalid source location otherwise. | ||||||
7456 | static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, | ||||||
7457 | const VarDecl *VD) { | ||||||
7458 | for (const Capture &Capture : LSI->Captures) { | ||||||
7459 | if (Capture.isVariableCapture() && Capture.getVariable() == VD) | ||||||
7460 | return Capture.getLocation(); | ||||||
7461 | } | ||||||
7462 | return SourceLocation(); | ||||||
7463 | } | ||||||
7464 | |||||||
7465 | static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, | ||||||
7466 | const LookupResult &R) { | ||||||
7467 | // Only diagnose if we're shadowing an unambiguous field or variable. | ||||||
7468 | if (R.getResultKind() != LookupResult::Found) | ||||||
7469 | return false; | ||||||
7470 | |||||||
7471 | // Return false if warning is ignored. | ||||||
7472 | return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); | ||||||
7473 | } | ||||||
7474 | |||||||
7475 | /// Return the declaration shadowed by the given variable \p D, or null | ||||||
7476 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||||
7477 | NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, | ||||||
7478 | const LookupResult &R) { | ||||||
7479 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||||
7480 | return nullptr; | ||||||
7481 | |||||||
7482 | // Don't diagnose declarations at file scope. | ||||||
7483 | if (D->hasGlobalStorage()) | ||||||
7484 | return nullptr; | ||||||
7485 | |||||||
7486 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||||
7487 | return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) | ||||||
7488 | ? ShadowedDecl | ||||||
7489 | : nullptr; | ||||||
7490 | } | ||||||
7491 | |||||||
7492 | /// Return the declaration shadowed by the given typedef \p D, or null | ||||||
7493 | /// if it doesn't shadow any declaration or shadowing warnings are disabled. | ||||||
7494 | NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, | ||||||
7495 | const LookupResult &R) { | ||||||
7496 | // Don't warn if typedef declaration is part of a class | ||||||
7497 | if (D->getDeclContext()->isRecord()) | ||||||
7498 | return nullptr; | ||||||
7499 | |||||||
7500 | if (!shouldWarnIfShadowedDecl(Diags, R)) | ||||||
7501 | return nullptr; | ||||||
7502 | |||||||
7503 | NamedDecl *ShadowedDecl = R.getFoundDecl(); | ||||||
7504 | return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; | ||||||
7505 | } | ||||||
7506 | |||||||
7507 | /// Diagnose variable or built-in function shadowing. Implements | ||||||
7508 | /// -Wshadow. | ||||||
7509 | /// | ||||||
7510 | /// This method is called whenever a VarDecl is added to a "useful" | ||||||
7511 | /// scope. | ||||||
7512 | /// | ||||||
7513 | /// \param ShadowedDecl the declaration that is shadowed by the given variable | ||||||
7514 | /// \param R the lookup of the name | ||||||
7515 | /// | ||||||
7516 | void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, | ||||||
7517 | const LookupResult &R) { | ||||||
7518 | DeclContext *NewDC = D->getDeclContext(); | ||||||
7519 | |||||||
7520 | if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { | ||||||
7521 | // Fields are not shadowed by variables in C++ static methods. | ||||||
7522 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) | ||||||
7523 | if (MD->isStatic()) | ||||||
7524 | return; | ||||||
7525 | |||||||
7526 | // Fields shadowed by constructor parameters are a special case. Usually | ||||||
7527 | // the constructor initializes the field with the parameter. | ||||||
7528 | if (isa<CXXConstructorDecl>(NewDC)) | ||||||
7529 | if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { | ||||||
7530 | // Remember that this was shadowed so we can either warn about its | ||||||
7531 | // modification or its existence depending on warning settings. | ||||||
7532 | ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); | ||||||
7533 | return; | ||||||
7534 | } | ||||||
7535 | } | ||||||
7536 | |||||||
7537 | if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) | ||||||
7538 | if (shadowedVar->isExternC()) { | ||||||
7539 | // For shadowing external vars, make sure that we point to the global | ||||||
7540 | // declaration, not a locally scoped extern declaration. | ||||||
7541 | for (auto I : shadowedVar->redecls()) | ||||||
7542 | if (I->isFileVarDecl()) { | ||||||
7543 | ShadowedDecl = I; | ||||||
7544 | break; | ||||||
7545 | } | ||||||
7546 | } | ||||||
7547 | |||||||
7548 | DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); | ||||||
7549 | |||||||
7550 | unsigned WarningDiag = diag::warn_decl_shadow; | ||||||
7551 | SourceLocation CaptureLoc; | ||||||
7552 | if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && | ||||||
7553 | isa<CXXMethodDecl>(NewDC)) { | ||||||
7554 | if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { | ||||||
7555 | if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { | ||||||
7556 | if (RD->getLambdaCaptureDefault() == LCD_None) { | ||||||
7557 | // Try to avoid warnings for lambdas with an explicit capture list. | ||||||
7558 | const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); | ||||||
7559 | // Warn only when the lambda captures the shadowed decl explicitly. | ||||||
7560 | CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); | ||||||
7561 | if (CaptureLoc.isInvalid()) | ||||||
7562 | WarningDiag = diag::warn_decl_shadow_uncaptured_local; | ||||||
7563 | } else { | ||||||
7564 | // Remember that this was shadowed so we can avoid the warning if the | ||||||
7565 | // shadowed decl isn't captured and the warning settings allow it. | ||||||
7566 | cast<LambdaScopeInfo>(getCurFunction()) | ||||||
7567 | ->ShadowingDecls.push_back( | ||||||
7568 | {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); | ||||||
7569 | return; | ||||||
7570 | } | ||||||
7571 | } | ||||||
7572 | |||||||
7573 | if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { | ||||||
7574 | // A variable can't shadow a local variable in an enclosing scope, if | ||||||
7575 | // they are separated by a non-capturing declaration context. | ||||||
7576 | for (DeclContext *ParentDC = NewDC; | ||||||
7577 | ParentDC && !ParentDC->Equals(OldDC); | ||||||
7578 | ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { | ||||||
7579 | // Only block literals, captured statements, and lambda expressions | ||||||
7580 | // can capture; other scopes don't. | ||||||
7581 | if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && | ||||||
7582 | !isLambdaCallOperator(ParentDC)) { | ||||||
7583 | return; | ||||||
7584 | } | ||||||
7585 | } | ||||||
7586 | } | ||||||
7587 | } | ||||||
7588 | } | ||||||
7589 | |||||||
7590 | // Only warn about certain kinds of shadowing for class members. | ||||||
7591 | if (NewDC && NewDC->isRecord()) { | ||||||
7592 | // In particular, don't warn about shadowing non-class members. | ||||||
7593 | if (!OldDC->isRecord()) | ||||||
7594 | return; | ||||||
7595 | |||||||
7596 | // TODO: should we warn about static data members shadowing | ||||||
7597 | // static data members from base classes? | ||||||
7598 | |||||||
7599 | // TODO: don't diagnose for inaccessible shadowed members. | ||||||
7600 | // This is hard to do perfectly because we might friend the | ||||||
7601 | // shadowing context, but that's just a false negative. | ||||||
7602 | } | ||||||
7603 | |||||||
7604 | |||||||
7605 | DeclarationName Name = R.getLookupName(); | ||||||
7606 | |||||||
7607 | // Emit warning and note. | ||||||
7608 | if (getSourceManager().isInSystemMacro(R.getNameLoc())) | ||||||
7609 | return; | ||||||
7610 | ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); | ||||||
7611 | Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; | ||||||
7612 | if (!CaptureLoc.isInvalid()) | ||||||
7613 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||||
7614 | << Name << /*explicitly*/ 1; | ||||||
7615 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7616 | } | ||||||
7617 | |||||||
7618 | /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD | ||||||
7619 | /// when these variables are captured by the lambda. | ||||||
7620 | void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { | ||||||
7621 | for (const auto &Shadow : LSI->ShadowingDecls) { | ||||||
7622 | const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; | ||||||
7623 | // Try to avoid the warning when the shadowed decl isn't captured. | ||||||
7624 | SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); | ||||||
7625 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||||
7626 | Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() | ||||||
7627 | ? diag::warn_decl_shadow_uncaptured_local | ||||||
7628 | : diag::warn_decl_shadow) | ||||||
7629 | << Shadow.VD->getDeclName() | ||||||
7630 | << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; | ||||||
7631 | if (!CaptureLoc.isInvalid()) | ||||||
7632 | Diag(CaptureLoc, diag::note_var_explicitly_captured_here) | ||||||
7633 | << Shadow.VD->getDeclName() << /*explicitly*/ 0; | ||||||
7634 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7635 | } | ||||||
7636 | } | ||||||
7637 | |||||||
7638 | /// Check -Wshadow without the advantage of a previous lookup. | ||||||
7639 | void Sema::CheckShadow(Scope *S, VarDecl *D) { | ||||||
7640 | if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) | ||||||
7641 | return; | ||||||
7642 | |||||||
7643 | LookupResult R(*this, D->getDeclName(), D->getLocation(), | ||||||
7644 | Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); | ||||||
7645 | LookupName(R, S); | ||||||
7646 | if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) | ||||||
7647 | CheckShadow(D, ShadowedDecl, R); | ||||||
7648 | } | ||||||
7649 | |||||||
7650 | /// Check if 'E', which is an expression that is about to be modified, refers | ||||||
7651 | /// to a constructor parameter that shadows a field. | ||||||
7652 | void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { | ||||||
7653 | // Quickly ignore expressions that can't be shadowing ctor parameters. | ||||||
7654 | if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) | ||||||
7655 | return; | ||||||
7656 | E = E->IgnoreParenImpCasts(); | ||||||
7657 | auto *DRE = dyn_cast<DeclRefExpr>(E); | ||||||
7658 | if (!DRE) | ||||||
7659 | return; | ||||||
7660 | const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); | ||||||
7661 | auto I = ShadowingDecls.find(D); | ||||||
7662 | if (I == ShadowingDecls.end()) | ||||||
7663 | return; | ||||||
7664 | const NamedDecl *ShadowedDecl = I->second; | ||||||
7665 | const DeclContext *OldDC = ShadowedDecl->getDeclContext(); | ||||||
7666 | Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; | ||||||
7667 | Diag(D->getLocation(), diag::note_var_declared_here) << D; | ||||||
7668 | Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); | ||||||
7669 | |||||||
7670 | // Avoid issuing multiple warnings about the same decl. | ||||||
7671 | ShadowingDecls.erase(I); | ||||||
7672 | } | ||||||
7673 | |||||||
7674 | /// Check for conflict between this global or extern "C" declaration and | ||||||
7675 | /// previous global or extern "C" declarations. This is only used in C++. | ||||||
7676 | template<typename T> | ||||||
7677 | static bool checkGlobalOrExternCConflict( | ||||||
7678 | Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { | ||||||
7679 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 7679, __PRETTY_FUNCTION__)); | ||||||
7680 | NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); | ||||||
7681 | |||||||
7682 | if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { | ||||||
7683 | // The common case: this global doesn't conflict with any extern "C" | ||||||
7684 | // declaration. | ||||||
7685 | return false; | ||||||
7686 | } | ||||||
7687 | |||||||
7688 | if (Prev) { | ||||||
7689 | if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { | ||||||
7690 | // Both the old and new declarations have C language linkage. This is a | ||||||
7691 | // redeclaration. | ||||||
7692 | Previous.clear(); | ||||||
7693 | Previous.addDecl(Prev); | ||||||
7694 | return true; | ||||||
7695 | } | ||||||
7696 | |||||||
7697 | // This is a global, non-extern "C" declaration, and there is a previous | ||||||
7698 | // non-global extern "C" declaration. Diagnose if this is a variable | ||||||
7699 | // declaration. | ||||||
7700 | if (!isa<VarDecl>(ND)) | ||||||
7701 | return false; | ||||||
7702 | } else { | ||||||
7703 | // The declaration is extern "C". Check for any declaration in the | ||||||
7704 | // translation unit which might conflict. | ||||||
7705 | if (IsGlobal) { | ||||||
7706 | // We have already performed the lookup into the translation unit. | ||||||
7707 | IsGlobal = false; | ||||||
7708 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||||
7709 | I != E; ++I) { | ||||||
7710 | if (isa<VarDecl>(*I)) { | ||||||
7711 | Prev = *I; | ||||||
7712 | break; | ||||||
7713 | } | ||||||
7714 | } | ||||||
7715 | } else { | ||||||
7716 | DeclContext::lookup_result R = | ||||||
7717 | S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); | ||||||
7718 | for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); | ||||||
7719 | I != E; ++I) { | ||||||
7720 | if (isa<VarDecl>(*I)) { | ||||||
7721 | Prev = *I; | ||||||
7722 | break; | ||||||
7723 | } | ||||||
7724 | // FIXME: If we have any other entity with this name in global scope, | ||||||
7725 | // the declaration is ill-formed, but that is a defect: it breaks the | ||||||
7726 | // 'stat' hack, for instance. Only variables can have mangled name | ||||||
7727 | // clashes with extern "C" declarations, so only they deserve a | ||||||
7728 | // diagnostic. | ||||||
7729 | } | ||||||
7730 | } | ||||||
7731 | |||||||
7732 | if (!Prev) | ||||||
7733 | return false; | ||||||
7734 | } | ||||||
7735 | |||||||
7736 | // Use the first declaration's location to ensure we point at something which | ||||||
7737 | // is lexically inside an extern "C" linkage-spec. | ||||||
7738 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 7738, __PRETTY_FUNCTION__)); | ||||||
7739 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) | ||||||
7740 | Prev = FD->getFirstDecl(); | ||||||
7741 | else | ||||||
7742 | Prev = cast<VarDecl>(Prev)->getFirstDecl(); | ||||||
7743 | |||||||
7744 | S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) | ||||||
7745 | << IsGlobal << ND; | ||||||
7746 | S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) | ||||||
7747 | << IsGlobal; | ||||||
7748 | return false; | ||||||
7749 | } | ||||||
7750 | |||||||
7751 | /// Apply special rules for handling extern "C" declarations. Returns \c true | ||||||
7752 | /// if we have found that this is a redeclaration of some prior entity. | ||||||
7753 | /// | ||||||
7754 | /// Per C++ [dcl.link]p6: | ||||||
7755 | /// Two declarations [for a function or variable] with C language linkage | ||||||
7756 | /// with the same name that appear in different scopes refer to the same | ||||||
7757 | /// [entity]. An entity with C language linkage shall not be declared with | ||||||
7758 | /// the same name as an entity in global scope. | ||||||
7759 | template<typename T> | ||||||
7760 | static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, | ||||||
7761 | LookupResult &Previous) { | ||||||
7762 | if (!S.getLangOpts().CPlusPlus) { | ||||||
7763 | // In C, when declaring a global variable, look for a corresponding 'extern' | ||||||
7764 | // variable declared in function scope. We don't need this in C++, because | ||||||
7765 | // we find local extern decls in the surrounding file-scope DeclContext. | ||||||
7766 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
7767 | if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { | ||||||
7768 | Previous.clear(); | ||||||
7769 | Previous.addDecl(Prev); | ||||||
7770 | return true; | ||||||
7771 | } | ||||||
7772 | } | ||||||
7773 | return false; | ||||||
7774 | } | ||||||
7775 | |||||||
7776 | // A declaration in the translation unit can conflict with an extern "C" | ||||||
7777 | // declaration. | ||||||
7778 | if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) | ||||||
7779 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); | ||||||
7780 | |||||||
7781 | // An extern "C" declaration can conflict with a declaration in the | ||||||
7782 | // translation unit or can be a redeclaration of an extern "C" declaration | ||||||
7783 | // in another scope. | ||||||
7784 | if (isIncompleteDeclExternC(S,ND)) | ||||||
7785 | return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); | ||||||
7786 | |||||||
7787 | // Neither global nor extern "C": nothing to do. | ||||||
7788 | return false; | ||||||
7789 | } | ||||||
7790 | |||||||
7791 | void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { | ||||||
7792 | // If the decl is already known invalid, don't check it. | ||||||
7793 | if (NewVD->isInvalidDecl()) | ||||||
7794 | return; | ||||||
7795 | |||||||
7796 | QualType T = NewVD->getType(); | ||||||
7797 | |||||||
7798 | // Defer checking an 'auto' type until its initializer is attached. | ||||||
7799 | if (T->isUndeducedType()) | ||||||
7800 | return; | ||||||
7801 | |||||||
7802 | if (NewVD->hasAttrs()) | ||||||
7803 | CheckAlignasUnderalignment(NewVD); | ||||||
7804 | |||||||
7805 | if (T->isObjCObjectType()) { | ||||||
7806 | Diag(NewVD->getLocation(), diag::err_statically_allocated_object) | ||||||
7807 | << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); | ||||||
7808 | T = Context.getObjCObjectPointerType(T); | ||||||
7809 | NewVD->setType(T); | ||||||
7810 | } | ||||||
7811 | |||||||
7812 | // Emit an error if an address space was applied to decl with local storage. | ||||||
7813 | // This includes arrays of objects with address space qualifiers, but not | ||||||
7814 | // automatic variables that point to other address spaces. | ||||||
7815 | // ISO/IEC TR 18037 S5.1.2 | ||||||
7816 | if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && | ||||||
7817 | T.getAddressSpace() != LangAS::Default) { | ||||||
7818 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; | ||||||
7819 | NewVD->setInvalidDecl(); | ||||||
7820 | return; | ||||||
7821 | } | ||||||
7822 | |||||||
7823 | // OpenCL v1.2 s6.8 - The static qualifier is valid only in program | ||||||
7824 | // scope. | ||||||
7825 | if (getLangOpts().OpenCLVersion == 120 && | ||||||
7826 | !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && | ||||||
7827 | NewVD->isStaticLocal()) { | ||||||
7828 | Diag(NewVD->getLocation(), diag::err_static_function_scope); | ||||||
7829 | NewVD->setInvalidDecl(); | ||||||
7830 | return; | ||||||
7831 | } | ||||||
7832 | |||||||
7833 | if (getLangOpts().OpenCL) { | ||||||
7834 | // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. | ||||||
7835 | if (NewVD->hasAttr<BlocksAttr>()) { | ||||||
7836 | Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); | ||||||
7837 | return; | ||||||
7838 | } | ||||||
7839 | |||||||
7840 | if (T->isBlockPointerType()) { | ||||||
7841 | // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and | ||||||
7842 | // can't use 'extern' storage class. | ||||||
7843 | if (!T.isConstQualified()) { | ||||||
7844 | Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||||
7845 | << 0 /*const*/; | ||||||
7846 | NewVD->setInvalidDecl(); | ||||||
7847 | return; | ||||||
7848 | } | ||||||
7849 | if (NewVD->hasExternalStorage()) { | ||||||
7850 | Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); | ||||||
7851 | NewVD->setInvalidDecl(); | ||||||
7852 | return; | ||||||
7853 | } | ||||||
7854 | } | ||||||
7855 | // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the | ||||||
7856 | // __constant address space. | ||||||
7857 | // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static | ||||||
7858 | // variables inside a function can also be declared in the global | ||||||
7859 | // address space. | ||||||
7860 | // C++ for OpenCL inherits rule from OpenCL C v2.0. | ||||||
7861 | // FIXME: Adding local AS in C++ for OpenCL might make sense. | ||||||
7862 | if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || | ||||||
7863 | NewVD->hasExternalStorage()) { | ||||||
7864 | if (!T->isSamplerT() && | ||||||
7865 | !T->isDependentType() && | ||||||
7866 | !(T.getAddressSpace() == LangAS::opencl_constant || | ||||||
7867 | (T.getAddressSpace() == LangAS::opencl_global && | ||||||
7868 | (getLangOpts().OpenCLVersion == 200 || | ||||||
7869 | getLangOpts().OpenCLCPlusPlus)))) { | ||||||
7870 | int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; | ||||||
7871 | if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) | ||||||
7872 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||||
7873 | << Scope << "global or constant"; | ||||||
7874 | else | ||||||
7875 | Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) | ||||||
7876 | << Scope << "constant"; | ||||||
7877 | NewVD->setInvalidDecl(); | ||||||
7878 | return; | ||||||
7879 | } | ||||||
7880 | } else { | ||||||
7881 | if (T.getAddressSpace() == LangAS::opencl_global) { | ||||||
7882 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7883 | << 1 /*is any function*/ << "global"; | ||||||
7884 | NewVD->setInvalidDecl(); | ||||||
7885 | return; | ||||||
7886 | } | ||||||
7887 | if (T.getAddressSpace() == LangAS::opencl_constant || | ||||||
7888 | T.getAddressSpace() == LangAS::opencl_local) { | ||||||
7889 | FunctionDecl *FD = getCurFunctionDecl(); | ||||||
7890 | // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables | ||||||
7891 | // in functions. | ||||||
7892 | if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { | ||||||
7893 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||||
7894 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7895 | << 0 /*non-kernel only*/ << "constant"; | ||||||
7896 | else | ||||||
7897 | Diag(NewVD->getLocation(), diag::err_opencl_function_variable) | ||||||
7898 | << 0 /*non-kernel only*/ << "local"; | ||||||
7899 | NewVD->setInvalidDecl(); | ||||||
7900 | return; | ||||||
7901 | } | ||||||
7902 | // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be | ||||||
7903 | // in the outermost scope of a kernel function. | ||||||
7904 | if (FD && FD->hasAttr<OpenCLKernelAttr>()) { | ||||||
7905 | if (!getCurScope()->isFunctionScope()) { | ||||||
7906 | if (T.getAddressSpace() == LangAS::opencl_constant) | ||||||
7907 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||||
7908 | << "constant"; | ||||||
7909 | else | ||||||
7910 | Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) | ||||||
7911 | << "local"; | ||||||
7912 | NewVD->setInvalidDecl(); | ||||||
7913 | return; | ||||||
7914 | } | ||||||
7915 | } | ||||||
7916 | } else if (T.getAddressSpace() != LangAS::opencl_private && | ||||||
7917 | // If we are parsing a template we didn't deduce an addr | ||||||
7918 | // space yet. | ||||||
7919 | T.getAddressSpace() != LangAS::Default) { | ||||||
7920 | // Do not allow other address spaces on automatic variable. | ||||||
7921 | Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; | ||||||
7922 | NewVD->setInvalidDecl(); | ||||||
7923 | return; | ||||||
7924 | } | ||||||
7925 | } | ||||||
7926 | } | ||||||
7927 | |||||||
7928 | if (NewVD->hasLocalStorage() && T.isObjCGCWeak() | ||||||
7929 | && !NewVD->hasAttr<BlocksAttr>()) { | ||||||
7930 | if (getLangOpts().getGC() != LangOptions::NonGC) | ||||||
7931 | Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); | ||||||
7932 | else { | ||||||
7933 | assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> ( 0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 7933, __PRETTY_FUNCTION__)); | ||||||
7934 | Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); | ||||||
7935 | } | ||||||
7936 | } | ||||||
7937 | |||||||
7938 | bool isVM = T->isVariablyModifiedType(); | ||||||
7939 | if (isVM || NewVD->hasAttr<CleanupAttr>() || | ||||||
7940 | NewVD->hasAttr<BlocksAttr>()) | ||||||
7941 | setFunctionHasBranchProtectedScope(); | ||||||
7942 | |||||||
7943 | if ((isVM && NewVD->hasLinkage()) || | ||||||
7944 | (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { | ||||||
7945 | bool SizeIsNegative; | ||||||
7946 | llvm::APSInt Oversized; | ||||||
7947 | TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( | ||||||
7948 | NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); | ||||||
7949 | QualType FixedT; | ||||||
7950 | if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) | ||||||
7951 | FixedT = FixedTInfo->getType(); | ||||||
7952 | else if (FixedTInfo) { | ||||||
7953 | // Type and type-as-written are canonically different. We need to fix up | ||||||
7954 | // both types separately. | ||||||
7955 | FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, | ||||||
7956 | Oversized); | ||||||
7957 | } | ||||||
7958 | if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { | ||||||
7959 | const VariableArrayType *VAT = Context.getAsVariableArrayType(T); | ||||||
7960 | // FIXME: This won't give the correct result for | ||||||
7961 | // int a[10][n]; | ||||||
7962 | SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); | ||||||
7963 | |||||||
7964 | if (NewVD->isFileVarDecl()) | ||||||
7965 | Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) | ||||||
7966 | << SizeRange; | ||||||
7967 | else if (NewVD->isStaticLocal()) | ||||||
7968 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) | ||||||
7969 | << SizeRange; | ||||||
7970 | else | ||||||
7971 | Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) | ||||||
7972 | << SizeRange; | ||||||
7973 | NewVD->setInvalidDecl(); | ||||||
7974 | return; | ||||||
7975 | } | ||||||
7976 | |||||||
7977 | if (!FixedTInfo) { | ||||||
7978 | if (NewVD->isFileVarDecl()) | ||||||
7979 | Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); | ||||||
7980 | else | ||||||
7981 | Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); | ||||||
7982 | NewVD->setInvalidDecl(); | ||||||
7983 | return; | ||||||
7984 | } | ||||||
7985 | |||||||
7986 | Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); | ||||||
7987 | NewVD->setType(FixedT); | ||||||
7988 | NewVD->setTypeSourceInfo(FixedTInfo); | ||||||
7989 | } | ||||||
7990 | |||||||
7991 | if (T->isVoidType()) { | ||||||
7992 | // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names | ||||||
7993 | // of objects and functions. | ||||||
7994 | if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { | ||||||
7995 | Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) | ||||||
7996 | << T; | ||||||
7997 | NewVD->setInvalidDecl(); | ||||||
7998 | return; | ||||||
7999 | } | ||||||
8000 | } | ||||||
8001 | |||||||
8002 | if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { | ||||||
8003 | Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); | ||||||
8004 | NewVD->setInvalidDecl(); | ||||||
8005 | return; | ||||||
8006 | } | ||||||
8007 | |||||||
8008 | if (!NewVD->hasLocalStorage() && T->isSizelessType()) { | ||||||
8009 | Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T; | ||||||
8010 | NewVD->setInvalidDecl(); | ||||||
8011 | return; | ||||||
8012 | } | ||||||
8013 | |||||||
8014 | if (isVM && NewVD->hasAttr<BlocksAttr>()) { | ||||||
8015 | Diag(NewVD->getLocation(), diag::err_block_on_vm); | ||||||
8016 | NewVD->setInvalidDecl(); | ||||||
8017 | return; | ||||||
8018 | } | ||||||
8019 | |||||||
8020 | if (NewVD->isConstexpr() && !T->isDependentType() && | ||||||
8021 | RequireLiteralType(NewVD->getLocation(), T, | ||||||
8022 | diag::err_constexpr_var_non_literal)) { | ||||||
8023 | NewVD->setInvalidDecl(); | ||||||
8024 | return; | ||||||
8025 | } | ||||||
8026 | } | ||||||
8027 | |||||||
8028 | /// Perform semantic checking on a newly-created variable | ||||||
8029 | /// declaration. | ||||||
8030 | /// | ||||||
8031 | /// This routine performs all of the type-checking required for a | ||||||
8032 | /// variable declaration once it has been built. It is used both to | ||||||
8033 | /// check variables after they have been parsed and their declarators | ||||||
8034 | /// have been translated into a declaration, and to check variables | ||||||
8035 | /// that have been instantiated from a template. | ||||||
8036 | /// | ||||||
8037 | /// Sets NewVD->isInvalidDecl() if an error was encountered. | ||||||
8038 | /// | ||||||
8039 | /// Returns true if the variable declaration is a redeclaration. | ||||||
8040 | bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { | ||||||
8041 | CheckVariableDeclarationType(NewVD); | ||||||
8042 | |||||||
8043 | // If the decl is already known invalid, don't check it. | ||||||
8044 | if (NewVD->isInvalidDecl()) | ||||||
8045 | return false; | ||||||
8046 | |||||||
8047 | // If we did not find anything by this name, look for a non-visible | ||||||
8048 | // extern "C" declaration with the same name. | ||||||
8049 | if (Previous.empty() && | ||||||
8050 | checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) | ||||||
8051 | Previous.setShadowed(); | ||||||
8052 | |||||||
8053 | if (!Previous.empty()) { | ||||||
8054 | MergeVarDecl(NewVD, Previous); | ||||||
8055 | return true; | ||||||
8056 | } | ||||||
8057 | return false; | ||||||
8058 | } | ||||||
8059 | |||||||
8060 | namespace { | ||||||
8061 | struct FindOverriddenMethod { | ||||||
8062 | Sema *S; | ||||||
8063 | CXXMethodDecl *Method; | ||||||
8064 | |||||||
8065 | /// Member lookup function that determines whether a given C++ | ||||||
8066 | /// method overrides a method in a base class, to be used with | ||||||
8067 | /// CXXRecordDecl::lookupInBases(). | ||||||
8068 | bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { | ||||||
8069 | RecordDecl *BaseRecord = | ||||||
8070 | Specifier->getType()->castAs<RecordType>()->getDecl(); | ||||||
8071 | |||||||
8072 | DeclarationName Name = Method->getDeclName(); | ||||||
8073 | |||||||
8074 | // FIXME: Do we care about other names here too? | ||||||
8075 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
8076 | // We really want to find the base class destructor here. | ||||||
8077 | QualType T = S->Context.getTypeDeclType(BaseRecord); | ||||||
8078 | CanQualType CT = S->Context.getCanonicalType(T); | ||||||
8079 | |||||||
8080 | Name = S->Context.DeclarationNames.getCXXDestructorName(CT); | ||||||
8081 | } | ||||||
8082 | |||||||
8083 | for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); | ||||||
8084 | Path.Decls = Path.Decls.slice(1)) { | ||||||
8085 | NamedDecl *D = Path.Decls.front(); | ||||||
8086 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { | ||||||
8087 | if (MD->isVirtual() && | ||||||
8088 | !S->IsOverload( | ||||||
8089 | Method, MD, /*UseMemberUsingDeclRules=*/false, | ||||||
8090 | /*ConsiderCudaAttrs=*/true, | ||||||
8091 | // C++2a [class.virtual]p2 does not consider requires clauses | ||||||
8092 | // when overriding. | ||||||
8093 | /*ConsiderRequiresClauses=*/false)) | ||||||
8094 | return true; | ||||||
8095 | } | ||||||
8096 | } | ||||||
8097 | |||||||
8098 | return false; | ||||||
8099 | } | ||||||
8100 | }; | ||||||
8101 | } // end anonymous namespace | ||||||
8102 | |||||||
8103 | /// AddOverriddenMethods - See if a method overrides any in the base classes, | ||||||
8104 | /// and if so, check that it's a valid override and remember it. | ||||||
8105 | bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { | ||||||
8106 | // Look for methods in base classes that this method might override. | ||||||
8107 | CXXBasePaths Paths; | ||||||
8108 | FindOverriddenMethod FOM; | ||||||
8109 | FOM.Method = MD; | ||||||
8110 | FOM.S = this; | ||||||
8111 | bool AddedAny = false; | ||||||
8112 | if (DC->lookupInBases(FOM, Paths)) { | ||||||
8113 | for (auto *I : Paths.found_decls()) { | ||||||
8114 | if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { | ||||||
8115 | MD->addOverriddenMethod(OldMD->getCanonicalDecl()); | ||||||
8116 | if (!CheckOverridingFunctionReturnType(MD, OldMD) && | ||||||
8117 | !CheckOverridingFunctionAttributes(MD, OldMD) && | ||||||
8118 | !CheckOverridingFunctionExceptionSpec(MD, OldMD) && | ||||||
8119 | !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { | ||||||
8120 | AddedAny = true; | ||||||
8121 | } | ||||||
8122 | } | ||||||
8123 | } | ||||||
8124 | } | ||||||
8125 | |||||||
8126 | return AddedAny; | ||||||
8127 | } | ||||||
8128 | |||||||
8129 | namespace { | ||||||
8130 | // Struct for holding all of the extra arguments needed by | ||||||
8131 | // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. | ||||||
8132 | struct ActOnFDArgs { | ||||||
8133 | Scope *S; | ||||||
8134 | Declarator &D; | ||||||
8135 | MultiTemplateParamsArg TemplateParamLists; | ||||||
8136 | bool AddToScope; | ||||||
8137 | }; | ||||||
8138 | } // end anonymous namespace | ||||||
8139 | |||||||
8140 | namespace { | ||||||
8141 | |||||||
8142 | // Callback to only accept typo corrections that have a non-zero edit distance. | ||||||
8143 | // Also only accept corrections that have the same parent decl. | ||||||
8144 | class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { | ||||||
8145 | public: | ||||||
8146 | DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, | ||||||
8147 | CXXRecordDecl *Parent) | ||||||
8148 | : Context(Context), OriginalFD(TypoFD), | ||||||
8149 | ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} | ||||||
8150 | |||||||
8151 | bool ValidateCandidate(const TypoCorrection &candidate) override { | ||||||
8152 | if (candidate.getEditDistance() == 0) | ||||||
8153 | return false; | ||||||
8154 | |||||||
8155 | SmallVector<unsigned, 1> MismatchedParams; | ||||||
8156 | for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), | ||||||
8157 | CDeclEnd = candidate.end(); | ||||||
8158 | CDecl != CDeclEnd; ++CDecl) { | ||||||
8159 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||||
8160 | |||||||
8161 | if (FD && !FD->hasBody() && | ||||||
8162 | hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { | ||||||
8163 | if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
8164 | CXXRecordDecl *Parent = MD->getParent(); | ||||||
8165 | if (Parent && Parent->getCanonicalDecl() == ExpectedParent) | ||||||
8166 | return true; | ||||||
8167 | } else if (!ExpectedParent) { | ||||||
8168 | return true; | ||||||
8169 | } | ||||||
8170 | } | ||||||
8171 | } | ||||||
8172 | |||||||
8173 | return false; | ||||||
8174 | } | ||||||
8175 | |||||||
8176 | std::unique_ptr<CorrectionCandidateCallback> clone() override { | ||||||
8177 | return std::make_unique<DifferentNameValidatorCCC>(*this); | ||||||
8178 | } | ||||||
8179 | |||||||
8180 | private: | ||||||
8181 | ASTContext &Context; | ||||||
8182 | FunctionDecl *OriginalFD; | ||||||
8183 | CXXRecordDecl *ExpectedParent; | ||||||
8184 | }; | ||||||
8185 | |||||||
8186 | } // end anonymous namespace | ||||||
8187 | |||||||
8188 | void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { | ||||||
8189 | TypoCorrectedFunctionDefinitions.insert(F); | ||||||
8190 | } | ||||||
8191 | |||||||
8192 | /// Generate diagnostics for an invalid function redeclaration. | ||||||
8193 | /// | ||||||
8194 | /// This routine handles generating the diagnostic messages for an invalid | ||||||
8195 | /// function redeclaration, including finding possible similar declarations | ||||||
8196 | /// or performing typo correction if there are no previous declarations with | ||||||
8197 | /// the same name. | ||||||
8198 | /// | ||||||
8199 | /// Returns a NamedDecl iff typo correction was performed and substituting in | ||||||
8200 | /// the new declaration name does not cause new errors. | ||||||
8201 | static NamedDecl *DiagnoseInvalidRedeclaration( | ||||||
8202 | Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, | ||||||
8203 | ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { | ||||||
8204 | DeclarationName Name = NewFD->getDeclName(); | ||||||
8205 | DeclContext *NewDC = NewFD->getDeclContext(); | ||||||
8206 | SmallVector<unsigned, 1> MismatchedParams; | ||||||
8207 | SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; | ||||||
8208 | TypoCorrection Correction; | ||||||
8209 | bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); | ||||||
8210 | unsigned DiagMsg = | ||||||
8211 | IsLocalFriend ? diag::err_no_matching_local_friend : | ||||||
8212 | NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : | ||||||
8213 | diag::err_member_decl_does_not_match; | ||||||
8214 | LookupResult Prev(SemaRef, Name, NewFD->getLocation(), | ||||||
8215 | IsLocalFriend ? Sema::LookupLocalFriendName | ||||||
8216 | : Sema::LookupOrdinaryName, | ||||||
8217 | Sema::ForVisibleRedeclaration); | ||||||
8218 | |||||||
8219 | NewFD->setInvalidDecl(); | ||||||
8220 | if (IsLocalFriend) | ||||||
8221 | SemaRef.LookupName(Prev, S); | ||||||
8222 | else | ||||||
8223 | SemaRef.LookupQualifiedName(Prev, NewDC); | ||||||
8224 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8225, __PRETTY_FUNCTION__)) | ||||||
8225 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8225, __PRETTY_FUNCTION__)); | ||||||
8226 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||||
8227 | DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, | ||||||
8228 | MD ? MD->getParent() : nullptr); | ||||||
8229 | if (!Prev.empty()) { | ||||||
8230 | for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); | ||||||
8231 | Func != FuncEnd; ++Func) { | ||||||
8232 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); | ||||||
8233 | if (FD && | ||||||
8234 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||||
8235 | // Add 1 to the index so that 0 can mean the mismatch didn't | ||||||
8236 | // involve a parameter | ||||||
8237 | unsigned ParamNum = | ||||||
8238 | MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; | ||||||
8239 | NearMatches.push_back(std::make_pair(FD, ParamNum)); | ||||||
8240 | } | ||||||
8241 | } | ||||||
8242 | // If the qualified name lookup yielded nothing, try typo correction | ||||||
8243 | } else if ((Correction = SemaRef.CorrectTypo( | ||||||
8244 | Prev.getLookupNameInfo(), Prev.getLookupKind(), S, | ||||||
8245 | &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, | ||||||
8246 | IsLocalFriend ? nullptr : NewDC))) { | ||||||
8247 | // Set up everything for the call to ActOnFunctionDeclarator | ||||||
8248 | ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), | ||||||
8249 | ExtraArgs.D.getIdentifierLoc()); | ||||||
8250 | Previous.clear(); | ||||||
8251 | Previous.setLookupName(Correction.getCorrection()); | ||||||
8252 | for (TypoCorrection::decl_iterator CDecl = Correction.begin(), | ||||||
8253 | CDeclEnd = Correction.end(); | ||||||
8254 | CDecl != CDeclEnd; ++CDecl) { | ||||||
8255 | FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); | ||||||
8256 | if (FD && !FD->hasBody() && | ||||||
8257 | hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { | ||||||
8258 | Previous.addDecl(FD); | ||||||
8259 | } | ||||||
8260 | } | ||||||
8261 | bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); | ||||||
8262 | |||||||
8263 | NamedDecl *Result; | ||||||
8264 | // Retry building the function declaration with the new previous | ||||||
8265 | // declarations, and with errors suppressed. | ||||||
8266 | { | ||||||
8267 | // Trap errors. | ||||||
8268 | Sema::SFINAETrap Trap(SemaRef); | ||||||
8269 | |||||||
8270 | // TODO: Refactor ActOnFunctionDeclarator so that we can call only the | ||||||
8271 | // pieces need to verify the typo-corrected C++ declaration and hopefully | ||||||
8272 | // eliminate the need for the parameter pack ExtraArgs. | ||||||
8273 | Result = SemaRef.ActOnFunctionDeclarator( | ||||||
8274 | ExtraArgs.S, ExtraArgs.D, | ||||||
8275 | Correction.getCorrectionDecl()->getDeclContext(), | ||||||
8276 | NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, | ||||||
8277 | ExtraArgs.AddToScope); | ||||||
8278 | |||||||
8279 | if (Trap.hasErrorOccurred()) | ||||||
8280 | Result = nullptr; | ||||||
8281 | } | ||||||
8282 | |||||||
8283 | if (Result) { | ||||||
8284 | // Determine which correction we picked. | ||||||
8285 | Decl *Canonical = Result->getCanonicalDecl(); | ||||||
8286 | for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); | ||||||
8287 | I != E; ++I) | ||||||
8288 | if ((*I)->getCanonicalDecl() == Canonical) | ||||||
8289 | Correction.setCorrectionDecl(*I); | ||||||
8290 | |||||||
8291 | // Let Sema know about the correction. | ||||||
8292 | SemaRef.MarkTypoCorrectedFunctionDefinition(Result); | ||||||
8293 | SemaRef.diagnoseTypo( | ||||||
8294 | Correction, | ||||||
8295 | SemaRef.PDiag(IsLocalFriend | ||||||
8296 | ? diag::err_no_matching_local_friend_suggest | ||||||
8297 | : diag::err_member_decl_does_not_match_suggest) | ||||||
8298 | << Name << NewDC << IsDefinition); | ||||||
8299 | return Result; | ||||||
8300 | } | ||||||
8301 | |||||||
8302 | // Pretend the typo correction never occurred | ||||||
8303 | ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), | ||||||
8304 | ExtraArgs.D.getIdentifierLoc()); | ||||||
8305 | ExtraArgs.D.setRedeclaration(wasRedeclaration); | ||||||
8306 | Previous.clear(); | ||||||
8307 | Previous.setLookupName(Name); | ||||||
8308 | } | ||||||
8309 | |||||||
8310 | SemaRef.Diag(NewFD->getLocation(), DiagMsg) | ||||||
8311 | << Name << NewDC << IsDefinition << NewFD->getLocation(); | ||||||
8312 | |||||||
8313 | bool NewFDisConst = false; | ||||||
8314 | if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) | ||||||
8315 | NewFDisConst = NewMD->isConst(); | ||||||
8316 | |||||||
8317 | for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator | ||||||
8318 | NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); | ||||||
8319 | NearMatch != NearMatchEnd; ++NearMatch) { | ||||||
8320 | FunctionDecl *FD = NearMatch->first; | ||||||
8321 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); | ||||||
8322 | bool FDisConst = MD && MD->isConst(); | ||||||
8323 | bool IsMember = MD || !IsLocalFriend; | ||||||
8324 | |||||||
8325 | // FIXME: These notes are poorly worded for the local friend case. | ||||||
8326 | if (unsigned Idx = NearMatch->second) { | ||||||
8327 | ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); | ||||||
8328 | SourceLocation Loc = FDParam->getTypeSpecStartLoc(); | ||||||
8329 | if (Loc.isInvalid()) Loc = FD->getLocation(); | ||||||
8330 | SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match | ||||||
8331 | : diag::note_local_decl_close_param_match) | ||||||
8332 | << Idx << FDParam->getType() | ||||||
8333 | << NewFD->getParamDecl(Idx - 1)->getType(); | ||||||
8334 | } else if (FDisConst != NewFDisConst) { | ||||||
8335 | SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) | ||||||
8336 | << NewFDisConst << FD->getSourceRange().getEnd(); | ||||||
8337 | } else | ||||||
8338 | SemaRef.Diag(FD->getLocation(), | ||||||
8339 | IsMember ? diag::note_member_def_close_match | ||||||
8340 | : diag::note_local_decl_close_match); | ||||||
8341 | } | ||||||
8342 | return nullptr; | ||||||
8343 | } | ||||||
8344 | |||||||
8345 | static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { | ||||||
8346 | switch (D.getDeclSpec().getStorageClassSpec()) { | ||||||
8347 | default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8347); | ||||||
8348 | case DeclSpec::SCS_auto: | ||||||
8349 | case DeclSpec::SCS_register: | ||||||
8350 | case DeclSpec::SCS_mutable: | ||||||
8351 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
8352 | diag::err_typecheck_sclass_func); | ||||||
8353 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||||
8354 | D.setInvalidType(); | ||||||
8355 | break; | ||||||
8356 | case DeclSpec::SCS_unspecified: break; | ||||||
8357 | case DeclSpec::SCS_extern: | ||||||
8358 | if (D.getDeclSpec().isExternInLinkageSpec()) | ||||||
8359 | return SC_None; | ||||||
8360 | return SC_Extern; | ||||||
8361 | case DeclSpec::SCS_static: { | ||||||
8362 | if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { | ||||||
8363 | // C99 6.7.1p5: | ||||||
8364 | // The declaration of an identifier for a function that has | ||||||
8365 | // block scope shall have no explicit storage-class specifier | ||||||
8366 | // other than extern | ||||||
8367 | // See also (C++ [dcl.stc]p4). | ||||||
8368 | SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
8369 | diag::err_static_block_func); | ||||||
8370 | break; | ||||||
8371 | } else | ||||||
8372 | return SC_Static; | ||||||
8373 | } | ||||||
8374 | case DeclSpec::SCS_private_extern: return SC_PrivateExtern; | ||||||
8375 | } | ||||||
8376 | |||||||
8377 | // No explicit storage class has already been returned | ||||||
8378 | return SC_None; | ||||||
8379 | } | ||||||
8380 | |||||||
8381 | static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, | ||||||
8382 | DeclContext *DC, QualType &R, | ||||||
8383 | TypeSourceInfo *TInfo, | ||||||
8384 | StorageClass SC, | ||||||
8385 | bool &IsVirtualOkay) { | ||||||
8386 | DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); | ||||||
8387 | DeclarationName Name = NameInfo.getName(); | ||||||
8388 | |||||||
8389 | FunctionDecl *NewFD = nullptr; | ||||||
8390 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||||
8391 | |||||||
8392 | if (!SemaRef.getLangOpts().CPlusPlus) { | ||||||
8393 | // Determine whether the function was written with a | ||||||
8394 | // prototype. This true when: | ||||||
8395 | // - there is a prototype in the declarator, or | ||||||
8396 | // - the type R of the function is some kind of typedef or other non- | ||||||
8397 | // attributed reference to a type name (which eventually refers to a | ||||||
8398 | // function type). | ||||||
8399 | bool HasPrototype = | ||||||
8400 | (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || | ||||||
8401 | (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); | ||||||
8402 | |||||||
8403 | NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | ||||||
8404 | R, TInfo, SC, isInline, HasPrototype, | ||||||
8405 | CSK_unspecified, | ||||||
8406 | /*TrailingRequiresClause=*/nullptr); | ||||||
8407 | if (D.isInvalidType()) | ||||||
8408 | NewFD->setInvalidDecl(); | ||||||
8409 | |||||||
8410 | return NewFD; | ||||||
8411 | } | ||||||
8412 | |||||||
8413 | ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); | ||||||
8414 | |||||||
8415 | ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); | ||||||
8416 | if (ConstexprKind == CSK_constinit) { | ||||||
8417 | SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
8418 | diag::err_constexpr_wrong_decl_kind) | ||||||
8419 | << ConstexprKind; | ||||||
8420 | ConstexprKind = CSK_unspecified; | ||||||
8421 | D.getMutableDeclSpec().ClearConstexprSpec(); | ||||||
8422 | } | ||||||
8423 | Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); | ||||||
8424 | |||||||
8425 | // Check that the return type is not an abstract class type. | ||||||
8426 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||||
8427 | // the class has been completely parsed. | ||||||
8428 | if (!DC->isRecord() && | ||||||
8429 | SemaRef.RequireNonAbstractType( | ||||||
8430 | D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), | ||||||
8431 | diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) | ||||||
8432 | D.setInvalidType(); | ||||||
8433 | |||||||
8434 | if (Name.getNameKind() == DeclarationName::CXXConstructorName) { | ||||||
8435 | // This is a C++ constructor declaration. | ||||||
8436 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8437, __PRETTY_FUNCTION__)) | ||||||
8437 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8437, __PRETTY_FUNCTION__)); | ||||||
8438 | |||||||
8439 | R = SemaRef.CheckConstructorDeclarator(D, R, SC); | ||||||
8440 | return CXXConstructorDecl::Create( | ||||||
8441 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8442 | TInfo, ExplicitSpecifier, isInline, | ||||||
8443 | /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), | ||||||
8444 | TrailingRequiresClause); | ||||||
8445 | |||||||
8446 | } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
8447 | // This is a C++ destructor declaration. | ||||||
8448 | if (DC->isRecord()) { | ||||||
8449 | R = SemaRef.CheckDestructorDeclarator(D, R, SC); | ||||||
8450 | CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); | ||||||
8451 | CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( | ||||||
8452 | SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, | ||||||
8453 | isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, | ||||||
8454 | TrailingRequiresClause); | ||||||
8455 | |||||||
8456 | // If the destructor needs an implicit exception specification, set it | ||||||
8457 | // now. FIXME: It'd be nice to be able to create the right type to start | ||||||
8458 | // with, but the type needs to reference the destructor declaration. | ||||||
8459 | if (SemaRef.getLangOpts().CPlusPlus11) | ||||||
8460 | SemaRef.AdjustDestructorExceptionSpec(NewDD); | ||||||
8461 | |||||||
8462 | IsVirtualOkay = true; | ||||||
8463 | return NewDD; | ||||||
8464 | |||||||
8465 | } else { | ||||||
8466 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); | ||||||
8467 | D.setInvalidType(); | ||||||
8468 | |||||||
8469 | // Create a FunctionDecl to satisfy the function definition parsing | ||||||
8470 | // code path. | ||||||
8471 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||||
8472 | D.getIdentifierLoc(), Name, R, TInfo, SC, | ||||||
8473 | isInline, | ||||||
8474 | /*hasPrototype=*/true, ConstexprKind, | ||||||
8475 | TrailingRequiresClause); | ||||||
8476 | } | ||||||
8477 | |||||||
8478 | } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { | ||||||
8479 | if (!DC->isRecord()) { | ||||||
8480 | SemaRef.Diag(D.getIdentifierLoc(), | ||||||
8481 | diag::err_conv_function_not_member); | ||||||
8482 | return nullptr; | ||||||
8483 | } | ||||||
8484 | |||||||
8485 | SemaRef.CheckConversionDeclarator(D, R, SC); | ||||||
8486 | if (D.isInvalidType()) | ||||||
8487 | return nullptr; | ||||||
8488 | |||||||
8489 | IsVirtualOkay = true; | ||||||
8490 | return CXXConversionDecl::Create( | ||||||
8491 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8492 | TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), | ||||||
8493 | TrailingRequiresClause); | ||||||
8494 | |||||||
8495 | } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { | ||||||
8496 | if (TrailingRequiresClause) | ||||||
8497 | SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), | ||||||
8498 | diag::err_trailing_requires_clause_on_deduction_guide) | ||||||
8499 | << TrailingRequiresClause->getSourceRange(); | ||||||
8500 | SemaRef.CheckDeductionGuideDeclarator(D, R, SC); | ||||||
8501 | |||||||
8502 | return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), | ||||||
8503 | ExplicitSpecifier, NameInfo, R, TInfo, | ||||||
8504 | D.getEndLoc()); | ||||||
8505 | } else if (DC->isRecord()) { | ||||||
8506 | // If the name of the function is the same as the name of the record, | ||||||
8507 | // then this must be an invalid constructor that has a return type. | ||||||
8508 | // (The parser checks for a return type and makes the declarator a | ||||||
8509 | // constructor if it has no return type). | ||||||
8510 | if (Name.getAsIdentifierInfo() && | ||||||
8511 | Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ | ||||||
8512 | SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) | ||||||
8513 | << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) | ||||||
8514 | << SourceRange(D.getIdentifierLoc()); | ||||||
8515 | return nullptr; | ||||||
8516 | } | ||||||
8517 | |||||||
8518 | // This is a C++ method declaration. | ||||||
8519 | CXXMethodDecl *Ret = CXXMethodDecl::Create( | ||||||
8520 | SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, | ||||||
8521 | TInfo, SC, isInline, ConstexprKind, SourceLocation(), | ||||||
8522 | TrailingRequiresClause); | ||||||
8523 | IsVirtualOkay = !Ret->isStatic(); | ||||||
8524 | return Ret; | ||||||
8525 | } else { | ||||||
8526 | bool isFriend = | ||||||
8527 | SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); | ||||||
8528 | if (!isFriend && SemaRef.CurContext->isRecord()) | ||||||
8529 | return nullptr; | ||||||
8530 | |||||||
8531 | // Determine whether the function was written with a | ||||||
8532 | // prototype. This true when: | ||||||
8533 | // - we're in C++ (where every function has a prototype), | ||||||
8534 | return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, | ||||||
8535 | R, TInfo, SC, isInline, true /*HasPrototype*/, | ||||||
8536 | ConstexprKind, TrailingRequiresClause); | ||||||
8537 | } | ||||||
8538 | } | ||||||
8539 | |||||||
8540 | enum OpenCLParamType { | ||||||
8541 | ValidKernelParam, | ||||||
8542 | PtrPtrKernelParam, | ||||||
8543 | PtrKernelParam, | ||||||
8544 | InvalidAddrSpacePtrKernelParam, | ||||||
8545 | InvalidKernelParam, | ||||||
8546 | RecordKernelParam | ||||||
8547 | }; | ||||||
8548 | |||||||
8549 | static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { | ||||||
8550 | // Size dependent types are just typedefs to normal integer types | ||||||
8551 | // (e.g. unsigned long), so we cannot distinguish them from other typedefs to | ||||||
8552 | // integers other than by their names. | ||||||
8553 | StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; | ||||||
8554 | |||||||
8555 | // Remove typedefs one by one until we reach a typedef | ||||||
8556 | // for a size dependent type. | ||||||
8557 | QualType DesugaredTy = Ty; | ||||||
8558 | do { | ||||||
8559 | ArrayRef<StringRef> Names(SizeTypeNames); | ||||||
8560 | auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); | ||||||
8561 | if (Names.end() != Match) | ||||||
8562 | return true; | ||||||
8563 | |||||||
8564 | Ty = DesugaredTy; | ||||||
8565 | DesugaredTy = Ty.getSingleStepDesugaredType(C); | ||||||
8566 | } while (DesugaredTy != Ty); | ||||||
8567 | |||||||
8568 | return false; | ||||||
8569 | } | ||||||
8570 | |||||||
8571 | static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { | ||||||
8572 | if (PT->isPointerType()) { | ||||||
8573 | QualType PointeeType = PT->getPointeeType(); | ||||||
8574 | if (PointeeType->isPointerType()) | ||||||
8575 | return PtrPtrKernelParam; | ||||||
8576 | if (PointeeType.getAddressSpace() == LangAS::opencl_generic || | ||||||
8577 | PointeeType.getAddressSpace() == LangAS::opencl_private || | ||||||
8578 | PointeeType.getAddressSpace() == LangAS::Default) | ||||||
8579 | return InvalidAddrSpacePtrKernelParam; | ||||||
8580 | return PtrKernelParam; | ||||||
8581 | } | ||||||
8582 | |||||||
8583 | // OpenCL v1.2 s6.9.k: | ||||||
8584 | // Arguments to kernel functions in a program cannot be declared with the | ||||||
8585 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||||
8586 | // uintptr_t or a struct and/or union that contain fields declared to be one | ||||||
8587 | // of these built-in scalar types. | ||||||
8588 | if (isOpenCLSizeDependentType(S.getASTContext(), PT)) | ||||||
8589 | return InvalidKernelParam; | ||||||
8590 | |||||||
8591 | if (PT->isImageType()) | ||||||
8592 | return PtrKernelParam; | ||||||
8593 | |||||||
8594 | if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) | ||||||
8595 | return InvalidKernelParam; | ||||||
8596 | |||||||
8597 | // OpenCL extension spec v1.2 s9.5: | ||||||
8598 | // This extension adds support for half scalar and vector types as built-in | ||||||
8599 | // types that can be used for arithmetic operations, conversions etc. | ||||||
8600 | if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) | ||||||
8601 | return InvalidKernelParam; | ||||||
8602 | |||||||
8603 | if (PT->isRecordType()) | ||||||
8604 | return RecordKernelParam; | ||||||
8605 | |||||||
8606 | // Look into an array argument to check if it has a forbidden type. | ||||||
8607 | if (PT->isArrayType()) { | ||||||
8608 | const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); | ||||||
8609 | // Call ourself to check an underlying type of an array. Since the | ||||||
8610 | // getPointeeOrArrayElementType returns an innermost type which is not an | ||||||
8611 | // array, this recursive call only happens once. | ||||||
8612 | return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); | ||||||
8613 | } | ||||||
8614 | |||||||
8615 | return ValidKernelParam; | ||||||
8616 | } | ||||||
8617 | |||||||
8618 | static void checkIsValidOpenCLKernelParameter( | ||||||
8619 | Sema &S, | ||||||
8620 | Declarator &D, | ||||||
8621 | ParmVarDecl *Param, | ||||||
8622 | llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { | ||||||
8623 | QualType PT = Param->getType(); | ||||||
8624 | |||||||
8625 | // Cache the valid types we encounter to avoid rechecking structs that are | ||||||
8626 | // used again | ||||||
8627 | if (ValidTypes.count(PT.getTypePtr())) | ||||||
8628 | return; | ||||||
8629 | |||||||
8630 | switch (getOpenCLKernelParameterType(S, PT)) { | ||||||
8631 | case PtrPtrKernelParam: | ||||||
8632 | // OpenCL v1.2 s6.9.a: | ||||||
8633 | // A kernel function argument cannot be declared as a | ||||||
8634 | // pointer to a pointer type. | ||||||
8635 | S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); | ||||||
8636 | D.setInvalidType(); | ||||||
8637 | return; | ||||||
8638 | |||||||
8639 | case InvalidAddrSpacePtrKernelParam: | ||||||
8640 | // OpenCL v1.0 s6.5: | ||||||
8641 | // __kernel function arguments declared to be a pointer of a type can point | ||||||
8642 | // to one of the following address spaces only : __global, __local or | ||||||
8643 | // __constant. | ||||||
8644 | S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); | ||||||
8645 | D.setInvalidType(); | ||||||
8646 | return; | ||||||
8647 | |||||||
8648 | // OpenCL v1.2 s6.9.k: | ||||||
8649 | // Arguments to kernel functions in a program cannot be declared with the | ||||||
8650 | // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and | ||||||
8651 | // uintptr_t or a struct and/or union that contain fields declared to be | ||||||
8652 | // one of these built-in scalar types. | ||||||
8653 | |||||||
8654 | case InvalidKernelParam: | ||||||
8655 | // OpenCL v1.2 s6.8 n: | ||||||
8656 | // A kernel function argument cannot be declared | ||||||
8657 | // of event_t type. | ||||||
8658 | // Do not diagnose half type since it is diagnosed as invalid argument | ||||||
8659 | // type for any function elsewhere. | ||||||
8660 | if (!PT->isHalfType()) { | ||||||
8661 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||||
8662 | |||||||
8663 | // Explain what typedefs are involved. | ||||||
8664 | const TypedefType *Typedef = nullptr; | ||||||
8665 | while ((Typedef = PT->getAs<TypedefType>())) { | ||||||
8666 | SourceLocation Loc = Typedef->getDecl()->getLocation(); | ||||||
8667 | // SourceLocation may be invalid for a built-in type. | ||||||
8668 | if (Loc.isValid()) | ||||||
8669 | S.Diag(Loc, diag::note_entity_declared_at) << PT; | ||||||
8670 | PT = Typedef->desugar(); | ||||||
8671 | } | ||||||
8672 | } | ||||||
8673 | |||||||
8674 | D.setInvalidType(); | ||||||
8675 | return; | ||||||
8676 | |||||||
8677 | case PtrKernelParam: | ||||||
8678 | case ValidKernelParam: | ||||||
8679 | ValidTypes.insert(PT.getTypePtr()); | ||||||
8680 | return; | ||||||
8681 | |||||||
8682 | case RecordKernelParam: | ||||||
8683 | break; | ||||||
8684 | } | ||||||
8685 | |||||||
8686 | // Track nested structs we will inspect | ||||||
8687 | SmallVector<const Decl *, 4> VisitStack; | ||||||
8688 | |||||||
8689 | // Track where we are in the nested structs. Items will migrate from | ||||||
8690 | // VisitStack to HistoryStack as we do the DFS for bad field. | ||||||
8691 | SmallVector<const FieldDecl *, 4> HistoryStack; | ||||||
8692 | HistoryStack.push_back(nullptr); | ||||||
8693 | |||||||
8694 | // At this point we already handled everything except of a RecordType or | ||||||
8695 | // an ArrayType of a RecordType. | ||||||
8696 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8696, __PRETTY_FUNCTION__)); | ||||||
8697 | const RecordType *RecTy = | ||||||
8698 | PT->getPointeeOrArrayElementType()->getAs<RecordType>(); | ||||||
8699 | const RecordDecl *OrigRecDecl = RecTy->getDecl(); | ||||||
8700 | |||||||
8701 | VisitStack.push_back(RecTy->getDecl()); | ||||||
8702 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8702, __PRETTY_FUNCTION__)); | ||||||
8703 | |||||||
8704 | do { | ||||||
8705 | const Decl *Next = VisitStack.pop_back_val(); | ||||||
8706 | if (!Next) { | ||||||
8707 | assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8707, __PRETTY_FUNCTION__)); | ||||||
8708 | // Found a marker, we have gone up a level | ||||||
8709 | if (const FieldDecl *Hist = HistoryStack.pop_back_val()) | ||||||
8710 | ValidTypes.insert(Hist->getType().getTypePtr()); | ||||||
8711 | |||||||
8712 | continue; | ||||||
8713 | } | ||||||
8714 | |||||||
8715 | // Adds everything except the original parameter declaration (which is not a | ||||||
8716 | // field itself) to the history stack. | ||||||
8717 | const RecordDecl *RD; | ||||||
8718 | if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { | ||||||
8719 | HistoryStack.push_back(Field); | ||||||
8720 | |||||||
8721 | QualType FieldTy = Field->getType(); | ||||||
8722 | // Other field types (known to be valid or invalid) are handled while we | ||||||
8723 | // walk around RecordDecl::fields(). | ||||||
8724 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8725, __PRETTY_FUNCTION__)) | ||||||
8725 | "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) && "Unexpected type.") ? static_cast<void> (0) : __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8725, __PRETTY_FUNCTION__)); | ||||||
8726 | const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); | ||||||
8727 | |||||||
8728 | RD = FieldRecTy->castAs<RecordType>()->getDecl(); | ||||||
8729 | } else { | ||||||
8730 | RD = cast<RecordDecl>(Next); | ||||||
8731 | } | ||||||
8732 | |||||||
8733 | // Add a null marker so we know when we've gone back up a level | ||||||
8734 | VisitStack.push_back(nullptr); | ||||||
8735 | |||||||
8736 | for (const auto *FD : RD->fields()) { | ||||||
8737 | QualType QT = FD->getType(); | ||||||
8738 | |||||||
8739 | if (ValidTypes.count(QT.getTypePtr())) | ||||||
8740 | continue; | ||||||
8741 | |||||||
8742 | OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); | ||||||
8743 | if (ParamType == ValidKernelParam) | ||||||
8744 | continue; | ||||||
8745 | |||||||
8746 | if (ParamType == RecordKernelParam) { | ||||||
8747 | VisitStack.push_back(FD); | ||||||
8748 | continue; | ||||||
8749 | } | ||||||
8750 | |||||||
8751 | // OpenCL v1.2 s6.9.p: | ||||||
8752 | // Arguments to kernel functions that are declared to be a struct or union | ||||||
8753 | // do not allow OpenCL objects to be passed as elements of the struct or | ||||||
8754 | // union. | ||||||
8755 | if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || | ||||||
8756 | ParamType == InvalidAddrSpacePtrKernelParam) { | ||||||
8757 | S.Diag(Param->getLocation(), | ||||||
8758 | diag::err_record_with_pointers_kernel_param) | ||||||
8759 | << PT->isUnionType() | ||||||
8760 | << PT; | ||||||
8761 | } else { | ||||||
8762 | S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; | ||||||
8763 | } | ||||||
8764 | |||||||
8765 | S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) | ||||||
8766 | << OrigRecDecl->getDeclName(); | ||||||
8767 | |||||||
8768 | // We have an error, now let's go back up through history and show where | ||||||
8769 | // the offending field came from | ||||||
8770 | for (ArrayRef<const FieldDecl *>::const_iterator | ||||||
8771 | I = HistoryStack.begin() + 1, | ||||||
8772 | E = HistoryStack.end(); | ||||||
8773 | I != E; ++I) { | ||||||
8774 | const FieldDecl *OuterField = *I; | ||||||
8775 | S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) | ||||||
8776 | << OuterField->getType(); | ||||||
8777 | } | ||||||
8778 | |||||||
8779 | S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) | ||||||
8780 | << QT->isPointerType() | ||||||
8781 | << QT; | ||||||
8782 | D.setInvalidType(); | ||||||
8783 | return; | ||||||
8784 | } | ||||||
8785 | } while (!VisitStack.empty()); | ||||||
8786 | } | ||||||
8787 | |||||||
8788 | /// Find the DeclContext in which a tag is implicitly declared if we see an | ||||||
8789 | /// elaborated type specifier in the specified context, and lookup finds | ||||||
8790 | /// nothing. | ||||||
8791 | static DeclContext *getTagInjectionContext(DeclContext *DC) { | ||||||
8792 | while (!DC->isFileContext() && !DC->isFunctionOrMethod()) | ||||||
8793 | DC = DC->getParent(); | ||||||
8794 | return DC; | ||||||
8795 | } | ||||||
8796 | |||||||
8797 | /// Find the Scope in which a tag is implicitly declared if we see an | ||||||
8798 | /// elaborated type specifier in the specified context, and lookup finds | ||||||
8799 | /// nothing. | ||||||
8800 | static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { | ||||||
8801 | while (S->isClassScope() || | ||||||
8802 | (LangOpts.CPlusPlus && | ||||||
8803 | S->isFunctionPrototypeScope()) || | ||||||
8804 | ((S->getFlags() & Scope::DeclScope) == 0) || | ||||||
8805 | (S->getEntity() && S->getEntity()->isTransparentContext())) | ||||||
8806 | S = S->getParent(); | ||||||
8807 | return S; | ||||||
8808 | } | ||||||
8809 | |||||||
8810 | NamedDecl* | ||||||
8811 | Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, | ||||||
8812 | TypeSourceInfo *TInfo, LookupResult &Previous, | ||||||
8813 | MultiTemplateParamsArg TemplateParamListsRef, | ||||||
8814 | bool &AddToScope) { | ||||||
8815 | QualType R = TInfo->getType(); | ||||||
8816 | |||||||
8817 | assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail ("R->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 8817, __PRETTY_FUNCTION__)); | ||||||
8818 | if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr()) | ||||||
8819 | Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call); | ||||||
8820 | |||||||
8821 | SmallVector<TemplateParameterList *, 4> TemplateParamLists; | ||||||
8822 | for (TemplateParameterList *TPL : TemplateParamListsRef) | ||||||
8823 | TemplateParamLists.push_back(TPL); | ||||||
8824 | if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { | ||||||
8825 | if (!TemplateParamLists.empty() && | ||||||
8826 | Invented->getDepth() == TemplateParamLists.back()->getDepth()) | ||||||
8827 | TemplateParamLists.back() = Invented; | ||||||
8828 | else | ||||||
8829 | TemplateParamLists.push_back(Invented); | ||||||
8830 | } | ||||||
8831 | |||||||
8832 | // TODO: consider using NameInfo for diagnostic. | ||||||
8833 | DeclarationNameInfo NameInfo = GetNameForDeclarator(D); | ||||||
8834 | DeclarationName Name = NameInfo.getName(); | ||||||
8835 | StorageClass SC = getFunctionStorageClass(*this, D); | ||||||
8836 | |||||||
8837 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||||
8838 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
8839 | diag::err_invalid_thread) | ||||||
8840 | << DeclSpec::getSpecifierName(TSCS); | ||||||
8841 | |||||||
8842 | if (D.isFirstDeclarationOfMember()) | ||||||
8843 | adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), | ||||||
8844 | D.getIdentifierLoc()); | ||||||
8845 | |||||||
8846 | bool isFriend = false; | ||||||
8847 | FunctionTemplateDecl *FunctionTemplate = nullptr; | ||||||
8848 | bool isMemberSpecialization = false; | ||||||
8849 | bool isFunctionTemplateSpecialization = false; | ||||||
8850 | |||||||
8851 | bool isDependentClassScopeExplicitSpecialization = false; | ||||||
8852 | bool HasExplicitTemplateArgs = false; | ||||||
8853 | TemplateArgumentListInfo TemplateArgs; | ||||||
8854 | |||||||
8855 | bool isVirtualOkay = false; | ||||||
8856 | |||||||
8857 | DeclContext *OriginalDC = DC; | ||||||
8858 | bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); | ||||||
8859 | |||||||
8860 | FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, | ||||||
8861 | isVirtualOkay); | ||||||
8862 | if (!NewFD) return nullptr; | ||||||
8863 | |||||||
8864 | if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) | ||||||
8865 | NewFD->setTopLevelDeclInObjCContainer(); | ||||||
8866 | |||||||
8867 | // Set the lexical context. If this is a function-scope declaration, or has a | ||||||
8868 | // C++ scope specifier, or is the object of a friend declaration, the lexical | ||||||
8869 | // context will be different from the semantic context. | ||||||
8870 | NewFD->setLexicalDeclContext(CurContext); | ||||||
8871 | |||||||
8872 | if (IsLocalExternDecl) | ||||||
8873 | NewFD->setLocalExternDecl(); | ||||||
8874 | |||||||
8875 | if (getLangOpts().CPlusPlus) { | ||||||
8876 | bool isInline = D.getDeclSpec().isInlineSpecified(); | ||||||
8877 | bool isVirtual = D.getDeclSpec().isVirtualSpecified(); | ||||||
8878 | bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); | ||||||
8879 | isFriend = D.getDeclSpec().isFriendSpecified(); | ||||||
8880 | if (isFriend && !isInline && D.isFunctionDefinition()) { | ||||||
8881 | // C++ [class.friend]p5 | ||||||
8882 | // A function can be defined in a friend declaration of a | ||||||
8883 | // class . . . . Such a function is implicitly inline. | ||||||
8884 | NewFD->setImplicitlyInline(); | ||||||
8885 | } | ||||||
8886 | |||||||
8887 | // If this is a method defined in an __interface, and is not a constructor | ||||||
8888 | // or an overloaded operator, then set the pure flag (isVirtual will already | ||||||
8889 | // return true). | ||||||
8890 | if (const CXXRecordDecl *Parent = | ||||||
8891 | dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { | ||||||
8892 | if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) | ||||||
8893 | NewFD->setPure(true); | ||||||
8894 | |||||||
8895 | // C++ [class.union]p2 | ||||||
8896 | // A union can have member functions, but not virtual functions. | ||||||
8897 | if (isVirtual && Parent->isUnion()) | ||||||
8898 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); | ||||||
8899 | } | ||||||
8900 | |||||||
8901 | SetNestedNameSpecifier(*this, NewFD, D); | ||||||
8902 | isMemberSpecialization = false; | ||||||
8903 | isFunctionTemplateSpecialization = false; | ||||||
8904 | if (D.isInvalidType()) | ||||||
8905 | NewFD->setInvalidDecl(); | ||||||
8906 | |||||||
8907 | // Match up the template parameter lists with the scope specifier, then | ||||||
8908 | // determine whether we have a template or a template specialization. | ||||||
8909 | bool Invalid = false; | ||||||
8910 | TemplateParameterList *TemplateParams = | ||||||
8911 | MatchTemplateParametersToScopeSpecifier( | ||||||
8912 | D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), | ||||||
8913 | D.getCXXScopeSpec(), | ||||||
8914 | D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId | ||||||
8915 | ? D.getName().TemplateId | ||||||
8916 | : nullptr, | ||||||
8917 | TemplateParamLists, isFriend, isMemberSpecialization, | ||||||
8918 | Invalid); | ||||||
8919 | if (TemplateParams) { | ||||||
8920 | // Check that we can declare a template here. | ||||||
8921 | if (CheckTemplateDeclScope(S, TemplateParams)) | ||||||
8922 | NewFD->setInvalidDecl(); | ||||||
8923 | |||||||
8924 | if (TemplateParams->size() > 0) { | ||||||
8925 | // This is a function template | ||||||
8926 | |||||||
8927 | // A destructor cannot be a template. | ||||||
8928 | if (Name.getNameKind() == DeclarationName::CXXDestructorName) { | ||||||
8929 | Diag(NewFD->getLocation(), diag::err_destructor_template); | ||||||
8930 | NewFD->setInvalidDecl(); | ||||||
8931 | } | ||||||
8932 | |||||||
8933 | // If we're adding a template to a dependent context, we may need to | ||||||
8934 | // rebuilding some of the types used within the template parameter list, | ||||||
8935 | // now that we know what the current instantiation is. | ||||||
8936 | if (DC->isDependentContext()) { | ||||||
8937 | ContextRAII SavedContext(*this, DC); | ||||||
8938 | if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) | ||||||
8939 | Invalid = true; | ||||||
8940 | } | ||||||
8941 | |||||||
8942 | FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, | ||||||
8943 | NewFD->getLocation(), | ||||||
8944 | Name, TemplateParams, | ||||||
8945 | NewFD); | ||||||
8946 | FunctionTemplate->setLexicalDeclContext(CurContext); | ||||||
8947 | NewFD->setDescribedFunctionTemplate(FunctionTemplate); | ||||||
8948 | |||||||
8949 | // For source fidelity, store the other template param lists. | ||||||
8950 | if (TemplateParamLists.size() > 1) { | ||||||
8951 | NewFD->setTemplateParameterListsInfo(Context, | ||||||
8952 | ArrayRef<TemplateParameterList *>(TemplateParamLists) | ||||||
8953 | .drop_back(1)); | ||||||
8954 | } | ||||||
8955 | } else { | ||||||
8956 | // This is a function template specialization. | ||||||
8957 | isFunctionTemplateSpecialization = true; | ||||||
8958 | // For source fidelity, store all the template param lists. | ||||||
8959 | if (TemplateParamLists.size() > 0) | ||||||
8960 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||||
8961 | |||||||
8962 | // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". | ||||||
8963 | if (isFriend) { | ||||||
8964 | // We want to remove the "template<>", found here. | ||||||
8965 | SourceRange RemoveRange = TemplateParams->getSourceRange(); | ||||||
8966 | |||||||
8967 | // If we remove the template<> and the name is not a | ||||||
8968 | // template-id, we're actually silently creating a problem: | ||||||
8969 | // the friend declaration will refer to an untemplated decl, | ||||||
8970 | // and clearly the user wants a template specialization. So | ||||||
8971 | // we need to insert '<>' after the name. | ||||||
8972 | SourceLocation InsertLoc; | ||||||
8973 | if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { | ||||||
8974 | InsertLoc = D.getName().getSourceRange().getEnd(); | ||||||
8975 | InsertLoc = getLocForEndOfToken(InsertLoc); | ||||||
8976 | } | ||||||
8977 | |||||||
8978 | Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) | ||||||
8979 | << Name << RemoveRange | ||||||
8980 | << FixItHint::CreateRemoval(RemoveRange) | ||||||
8981 | << FixItHint::CreateInsertion(InsertLoc, "<>"); | ||||||
8982 | } | ||||||
8983 | } | ||||||
8984 | } else { | ||||||
8985 | // Check that we can declare a template here. | ||||||
8986 | if (!TemplateParamLists.empty() && isMemberSpecialization && | ||||||
8987 | CheckTemplateDeclScope(S, TemplateParamLists.back())) | ||||||
8988 | NewFD->setInvalidDecl(); | ||||||
8989 | |||||||
8990 | // All template param lists were matched against the scope specifier: | ||||||
8991 | // this is NOT (an explicit specialization of) a template. | ||||||
8992 | if (TemplateParamLists.size() > 0) | ||||||
8993 | // For source fidelity, store all the template param lists. | ||||||
8994 | NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); | ||||||
8995 | } | ||||||
8996 | |||||||
8997 | if (Invalid) { | ||||||
8998 | NewFD->setInvalidDecl(); | ||||||
8999 | if (FunctionTemplate) | ||||||
9000 | FunctionTemplate->setInvalidDecl(); | ||||||
9001 | } | ||||||
9002 | |||||||
9003 | // C++ [dcl.fct.spec]p5: | ||||||
9004 | // The virtual specifier shall only be used in declarations of | ||||||
9005 | // nonstatic class member functions that appear within a | ||||||
9006 | // member-specification of a class declaration; see 10.3. | ||||||
9007 | // | ||||||
9008 | if (isVirtual && !NewFD->isInvalidDecl()) { | ||||||
9009 | if (!isVirtualOkay) { | ||||||
9010 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
9011 | diag::err_virtual_non_function); | ||||||
9012 | } else if (!CurContext->isRecord()) { | ||||||
9013 | // 'virtual' was specified outside of the class. | ||||||
9014 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
9015 | diag::err_virtual_out_of_class) | ||||||
9016 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||||
9017 | } else if (NewFD->getDescribedFunctionTemplate()) { | ||||||
9018 | // C++ [temp.mem]p3: | ||||||
9019 | // A member function template shall not be virtual. | ||||||
9020 | Diag(D.getDeclSpec().getVirtualSpecLoc(), | ||||||
9021 | diag::err_virtual_member_function_template) | ||||||
9022 | << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); | ||||||
9023 | } else { | ||||||
9024 | // Okay: Add virtual to the method. | ||||||
9025 | NewFD->setVirtualAsWritten(true); | ||||||
9026 | } | ||||||
9027 | |||||||
9028 | if (getLangOpts().CPlusPlus14 && | ||||||
9029 | NewFD->getReturnType()->isUndeducedType()) | ||||||
9030 | Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); | ||||||
9031 | } | ||||||
9032 | |||||||
9033 | if (getLangOpts().CPlusPlus14 && | ||||||
9034 | (NewFD->isDependentContext() || | ||||||
9035 | (isFriend && CurContext->isDependentContext())) && | ||||||
9036 | NewFD->getReturnType()->isUndeducedType()) { | ||||||
9037 | // If the function template is referenced directly (for instance, as a | ||||||
9038 | // member of the current instantiation), pretend it has a dependent type. | ||||||
9039 | // This is not really justified by the standard, but is the only sane | ||||||
9040 | // thing to do. | ||||||
9041 | // FIXME: For a friend function, we have not marked the function as being | ||||||
9042 | // a friend yet, so 'isDependentContext' on the FD doesn't work. | ||||||
9043 | const FunctionProtoType *FPT = | ||||||
9044 | NewFD->getType()->castAs<FunctionProtoType>(); | ||||||
9045 | QualType Result = | ||||||
9046 | SubstAutoType(FPT->getReturnType(), Context.DependentTy); | ||||||
9047 | NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), | ||||||
9048 | FPT->getExtProtoInfo())); | ||||||
9049 | } | ||||||
9050 | |||||||
9051 | // C++ [dcl.fct.spec]p3: | ||||||
9052 | // The inline specifier shall not appear on a block scope function | ||||||
9053 | // declaration. | ||||||
9054 | if (isInline && !NewFD->isInvalidDecl()) { | ||||||
9055 | if (CurContext->isFunctionOrMethod()) { | ||||||
9056 | // 'inline' is not allowed on block scope function declaration. | ||||||
9057 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
9058 | diag::err_inline_declaration_block_scope) << Name | ||||||
9059 | << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); | ||||||
9060 | } | ||||||
9061 | } | ||||||
9062 | |||||||
9063 | // C++ [dcl.fct.spec]p6: | ||||||
9064 | // The explicit specifier shall be used only in the declaration of a | ||||||
9065 | // constructor or conversion function within its class definition; | ||||||
9066 | // see 12.3.1 and 12.3.2. | ||||||
9067 | if (hasExplicit && !NewFD->isInvalidDecl() && | ||||||
9068 | !isa<CXXDeductionGuideDecl>(NewFD)) { | ||||||
9069 | if (!CurContext->isRecord()) { | ||||||
9070 | // 'explicit' was specified outside of the class. | ||||||
9071 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||||
9072 | diag::err_explicit_out_of_class) | ||||||
9073 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||||
9074 | } else if (!isa<CXXConstructorDecl>(NewFD) && | ||||||
9075 | !isa<CXXConversionDecl>(NewFD)) { | ||||||
9076 | // 'explicit' was specified on a function that wasn't a constructor | ||||||
9077 | // or conversion function. | ||||||
9078 | Diag(D.getDeclSpec().getExplicitSpecLoc(), | ||||||
9079 | diag::err_explicit_non_ctor_or_conv_function) | ||||||
9080 | << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); | ||||||
9081 | } | ||||||
9082 | } | ||||||
9083 | |||||||
9084 | if (ConstexprSpecKind ConstexprKind = | ||||||
9085 | D.getDeclSpec().getConstexprSpecifier()) { | ||||||
9086 | // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors | ||||||
9087 | // are implicitly inline. | ||||||
9088 | NewFD->setImplicitlyInline(); | ||||||
9089 | |||||||
9090 | // C++11 [dcl.constexpr]p3: functions declared constexpr are required to | ||||||
9091 | // be either constructors or to return a literal type. Therefore, | ||||||
9092 | // destructors cannot be declared constexpr. | ||||||
9093 | if (isa<CXXDestructorDecl>(NewFD) && | ||||||
9094 | (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) { | ||||||
9095 | Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) | ||||||
9096 | << ConstexprKind; | ||||||
9097 | NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr); | ||||||
9098 | } | ||||||
9099 | // C++20 [dcl.constexpr]p2: An allocation function, or a | ||||||
9100 | // deallocation function shall not be declared with the consteval | ||||||
9101 | // specifier. | ||||||
9102 | if (ConstexprKind == CSK_consteval && | ||||||
9103 | (NewFD->getOverloadedOperator() == OO_New || | ||||||
9104 | NewFD->getOverloadedOperator() == OO_Array_New || | ||||||
9105 | NewFD->getOverloadedOperator() == OO_Delete || | ||||||
9106 | NewFD->getOverloadedOperator() == OO_Array_Delete)) { | ||||||
9107 | Diag(D.getDeclSpec().getConstexprSpecLoc(), | ||||||
9108 | diag::err_invalid_consteval_decl_kind) | ||||||
9109 | << NewFD; | ||||||
9110 | NewFD->setConstexprKind(CSK_constexpr); | ||||||
9111 | } | ||||||
9112 | } | ||||||
9113 | |||||||
9114 | // If __module_private__ was specified, mark the function accordingly. | ||||||
9115 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
9116 | if (isFunctionTemplateSpecialization) { | ||||||
9117 | SourceLocation ModulePrivateLoc | ||||||
9118 | = D.getDeclSpec().getModulePrivateSpecLoc(); | ||||||
9119 | Diag(ModulePrivateLoc, diag::err_module_private_specialization) | ||||||
9120 | << 0 | ||||||
9121 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||||
9122 | } else { | ||||||
9123 | NewFD->setModulePrivate(); | ||||||
9124 | if (FunctionTemplate) | ||||||
9125 | FunctionTemplate->setModulePrivate(); | ||||||
9126 | } | ||||||
9127 | } | ||||||
9128 | |||||||
9129 | if (isFriend) { | ||||||
9130 | if (FunctionTemplate) { | ||||||
9131 | FunctionTemplate->setObjectOfFriendDecl(); | ||||||
9132 | FunctionTemplate->setAccess(AS_public); | ||||||
9133 | } | ||||||
9134 | NewFD->setObjectOfFriendDecl(); | ||||||
9135 | NewFD->setAccess(AS_public); | ||||||
9136 | } | ||||||
9137 | |||||||
9138 | // If a function is defined as defaulted or deleted, mark it as such now. | ||||||
9139 | // We'll do the relevant checks on defaulted / deleted functions later. | ||||||
9140 | switch (D.getFunctionDefinitionKind()) { | ||||||
9141 | case FDK_Declaration: | ||||||
9142 | case FDK_Definition: | ||||||
9143 | break; | ||||||
9144 | |||||||
9145 | case FDK_Defaulted: | ||||||
9146 | NewFD->setDefaulted(); | ||||||
9147 | break; | ||||||
9148 | |||||||
9149 | case FDK_Deleted: | ||||||
9150 | NewFD->setDeletedAsWritten(); | ||||||
9151 | break; | ||||||
9152 | } | ||||||
9153 | |||||||
9154 | if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && | ||||||
9155 | D.isFunctionDefinition()) { | ||||||
9156 | // C++ [class.mfct]p2: | ||||||
9157 | // A member function may be defined (8.4) in its class definition, in | ||||||
9158 | // which case it is an inline member function (7.1.2) | ||||||
9159 | NewFD->setImplicitlyInline(); | ||||||
9160 | } | ||||||
9161 | |||||||
9162 | if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && | ||||||
9163 | !CurContext->isRecord()) { | ||||||
9164 | // C++ [class.static]p1: | ||||||
9165 | // A data or function member of a class may be declared static | ||||||
9166 | // in a class definition, in which case it is a static member of | ||||||
9167 | // the class. | ||||||
9168 | |||||||
9169 | // Complain about the 'static' specifier if it's on an out-of-line | ||||||
9170 | // member function definition. | ||||||
9171 | |||||||
9172 | // MSVC permits the use of a 'static' storage specifier on an out-of-line | ||||||
9173 | // member function template declaration and class member template | ||||||
9174 | // declaration (MSVC versions before 2015), warn about this. | ||||||
9175 | Diag(D.getDeclSpec().getStorageClassSpecLoc(), | ||||||
9176 | ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && | ||||||
9177 | cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || | ||||||
9178 | (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) | ||||||
9179 | ? diag::ext_static_out_of_line : diag::err_static_out_of_line) | ||||||
9180 | << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
9181 | } | ||||||
9182 | |||||||
9183 | // C++11 [except.spec]p15: | ||||||
9184 | // A deallocation function with no exception-specification is treated | ||||||
9185 | // as if it were specified with noexcept(true). | ||||||
9186 | const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); | ||||||
9187 | if ((Name.getCXXOverloadedOperator() == OO_Delete || | ||||||
9188 | Name.getCXXOverloadedOperator() == OO_Array_Delete) && | ||||||
9189 | getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) | ||||||
9190 | NewFD->setType(Context.getFunctionType( | ||||||
9191 | FPT->getReturnType(), FPT->getParamTypes(), | ||||||
9192 | FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); | ||||||
9193 | } | ||||||
9194 | |||||||
9195 | // Filter out previous declarations that don't match the scope. | ||||||
9196 | FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), | ||||||
9197 | D.getCXXScopeSpec().isNotEmpty() || | ||||||
9198 | isMemberSpecialization || | ||||||
9199 | isFunctionTemplateSpecialization); | ||||||
9200 | |||||||
9201 | // Handle GNU asm-label extension (encoded as an attribute). | ||||||
9202 | if (Expr *E = (Expr*) D.getAsmLabel()) { | ||||||
9203 | // The parser guarantees this is a string. | ||||||
9204 | StringLiteral *SE = cast<StringLiteral>(E); | ||||||
9205 | NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), | ||||||
9206 | /*IsLiteralLabel=*/true, | ||||||
9207 | SE->getStrTokenLoc(0))); | ||||||
9208 | } else if (!ExtnameUndeclaredIdentifiers.empty()) { | ||||||
9209 | llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = | ||||||
9210 | ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); | ||||||
9211 | if (I != ExtnameUndeclaredIdentifiers.end()) { | ||||||
9212 | if (isDeclExternC(NewFD)) { | ||||||
9213 | NewFD->addAttr(I->second); | ||||||
9214 | ExtnameUndeclaredIdentifiers.erase(I); | ||||||
9215 | } else | ||||||
9216 | Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
9217 | << /*Variable*/0 << NewFD; | ||||||
9218 | } | ||||||
9219 | } | ||||||
9220 | |||||||
9221 | // Copy the parameter declarations from the declarator D to the function | ||||||
9222 | // declaration NewFD, if they are available. First scavenge them into Params. | ||||||
9223 | SmallVector<ParmVarDecl*, 16> Params; | ||||||
9224 | unsigned FTIIdx; | ||||||
9225 | if (D.isFunctionDeclarator(FTIIdx)) { | ||||||
9226 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; | ||||||
9227 | |||||||
9228 | // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs | ||||||
9229 | // function that takes no arguments, not a function that takes a | ||||||
9230 | // single void argument. | ||||||
9231 | // We let through "const void" here because Sema::GetTypeForDeclarator | ||||||
9232 | // already checks for that case. | ||||||
9233 | if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { | ||||||
9234 | for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { | ||||||
9235 | ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); | ||||||
9236 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9236, __PRETTY_FUNCTION__)); | ||||||
9237 | Param->setDeclContext(NewFD); | ||||||
9238 | Params.push_back(Param); | ||||||
9239 | |||||||
9240 | if (Param->isInvalidDecl()) | ||||||
9241 | NewFD->setInvalidDecl(); | ||||||
9242 | } | ||||||
9243 | } | ||||||
9244 | |||||||
9245 | if (!getLangOpts().CPlusPlus) { | ||||||
9246 | // In C, find all the tag declarations from the prototype and move them | ||||||
9247 | // into the function DeclContext. Remove them from the surrounding tag | ||||||
9248 | // injection context of the function, which is typically but not always | ||||||
9249 | // the TU. | ||||||
9250 | DeclContext *PrototypeTagContext = | ||||||
9251 | getTagInjectionContext(NewFD->getLexicalDeclContext()); | ||||||
9252 | for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { | ||||||
9253 | auto *TD = dyn_cast<TagDecl>(NonParmDecl); | ||||||
9254 | |||||||
9255 | // We don't want to reparent enumerators. Look at their parent enum | ||||||
9256 | // instead. | ||||||
9257 | if (!TD) { | ||||||
9258 | if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) | ||||||
9259 | TD = cast<EnumDecl>(ECD->getDeclContext()); | ||||||
9260 | } | ||||||
9261 | if (!TD) | ||||||
9262 | continue; | ||||||
9263 | DeclContext *TagDC = TD->getLexicalDeclContext(); | ||||||
9264 | if (!TagDC->containsDecl(TD)) | ||||||
9265 | continue; | ||||||
9266 | TagDC->removeDecl(TD); | ||||||
9267 | TD->setDeclContext(NewFD); | ||||||
9268 | NewFD->addDecl(TD); | ||||||
9269 | |||||||
9270 | // Preserve the lexical DeclContext if it is not the surrounding tag | ||||||
9271 | // injection context of the FD. In this example, the semantic context of | ||||||
9272 | // E will be f and the lexical context will be S, while both the | ||||||
9273 | // semantic and lexical contexts of S will be f: | ||||||
9274 | // void f(struct S { enum E { a } f; } s); | ||||||
9275 | if (TagDC != PrototypeTagContext) | ||||||
9276 | TD->setLexicalDeclContext(TagDC); | ||||||
9277 | } | ||||||
9278 | } | ||||||
9279 | } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { | ||||||
9280 | // When we're declaring a function with a typedef, typeof, etc as in the | ||||||
9281 | // following example, we'll need to synthesize (unnamed) | ||||||
9282 | // parameters for use in the declaration. | ||||||
9283 | // | ||||||
9284 | // @code | ||||||
9285 | // typedef void fn(int); | ||||||
9286 | // fn f; | ||||||
9287 | // @endcode | ||||||
9288 | |||||||
9289 | // Synthesize a parameter for each argument type. | ||||||
9290 | for (const auto &AI : FT->param_types()) { | ||||||
9291 | ParmVarDecl *Param = | ||||||
9292 | BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); | ||||||
9293 | Param->setScopeInfo(0, Params.size()); | ||||||
9294 | Params.push_back(Param); | ||||||
9295 | } | ||||||
9296 | } else { | ||||||
9297 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9298, __PRETTY_FUNCTION__)) | ||||||
9298 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9298, __PRETTY_FUNCTION__)); | ||||||
9299 | } | ||||||
9300 | |||||||
9301 | // Finally, we know we have the right number of parameters, install them. | ||||||
9302 | NewFD->setParams(Params); | ||||||
9303 | |||||||
9304 | if (D.getDeclSpec().isNoreturnSpecified()) | ||||||
9305 | NewFD->addAttr(C11NoReturnAttr::Create(Context, | ||||||
9306 | D.getDeclSpec().getNoreturnSpecLoc(), | ||||||
9307 | AttributeCommonInfo::AS_Keyword)); | ||||||
9308 | |||||||
9309 | // Functions returning a variably modified type violate C99 6.7.5.2p2 | ||||||
9310 | // because all functions have linkage. | ||||||
9311 | if (!NewFD->isInvalidDecl() && | ||||||
9312 | NewFD->getReturnType()->isVariablyModifiedType()) { | ||||||
9313 | Diag(NewFD->getLocation(), diag::err_vm_func_decl); | ||||||
9314 | NewFD->setInvalidDecl(); | ||||||
9315 | } | ||||||
9316 | |||||||
9317 | // Apply an implicit SectionAttr if '#pragma clang section text' is active | ||||||
9318 | if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && | ||||||
9319 | !NewFD->hasAttr<SectionAttr>()) | ||||||
9320 | NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( | ||||||
9321 | Context, PragmaClangTextSection.SectionName, | ||||||
9322 | PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); | ||||||
9323 | |||||||
9324 | // Apply an implicit SectionAttr if #pragma code_seg is active. | ||||||
9325 | if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && | ||||||
9326 | !NewFD->hasAttr<SectionAttr>()) { | ||||||
9327 | NewFD->addAttr(SectionAttr::CreateImplicit( | ||||||
9328 | Context, CodeSegStack.CurrentValue->getString(), | ||||||
9329 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||||
9330 | SectionAttr::Declspec_allocate)); | ||||||
9331 | if (UnifySection(CodeSegStack.CurrentValue->getString(), | ||||||
9332 | ASTContext::PSF_Implicit | ASTContext::PSF_Execute | | ||||||
9333 | ASTContext::PSF_Read, | ||||||
9334 | NewFD)) | ||||||
9335 | NewFD->dropAttr<SectionAttr>(); | ||||||
9336 | } | ||||||
9337 | |||||||
9338 | // Apply an implicit CodeSegAttr from class declspec or | ||||||
9339 | // apply an implicit SectionAttr from #pragma code_seg if active. | ||||||
9340 | if (!NewFD->hasAttr<CodeSegAttr>()) { | ||||||
9341 | if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, | ||||||
9342 | D.isFunctionDefinition())) { | ||||||
9343 | NewFD->addAttr(SAttr); | ||||||
9344 | } | ||||||
9345 | } | ||||||
9346 | |||||||
9347 | // Handle attributes. | ||||||
9348 | ProcessDeclAttributes(S, NewFD, D); | ||||||
9349 | |||||||
9350 | if (getLangOpts().OpenCL) { | ||||||
9351 | // OpenCL v1.1 s6.5: Using an address space qualifier in a function return | ||||||
9352 | // type declaration will generate a compilation error. | ||||||
9353 | LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); | ||||||
9354 | if (AddressSpace != LangAS::Default) { | ||||||
9355 | Diag(NewFD->getLocation(), | ||||||
9356 | diag::err_opencl_return_value_with_address_space); | ||||||
9357 | NewFD->setInvalidDecl(); | ||||||
9358 | } | ||||||
9359 | } | ||||||
9360 | |||||||
9361 | if (!getLangOpts().CPlusPlus) { | ||||||
9362 | // Perform semantic checking on the function declaration. | ||||||
9363 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||||
9364 | CheckMain(NewFD, D.getDeclSpec()); | ||||||
9365 | |||||||
9366 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||||
9367 | CheckMSVCRTEntryPoint(NewFD); | ||||||
9368 | |||||||
9369 | if (!NewFD->isInvalidDecl()) | ||||||
9370 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||||
9371 | isMemberSpecialization)); | ||||||
9372 | else if (!Previous.empty()) | ||||||
9373 | // Recover gracefully from an invalid redeclaration. | ||||||
9374 | D.setRedeclaration(true); | ||||||
9375 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9377, __PRETTY_FUNCTION__)) | ||||||
9376 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9377, __PRETTY_FUNCTION__)) | ||||||
9377 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9377, __PRETTY_FUNCTION__)); | ||||||
9378 | |||||||
9379 | // Diagnose no-prototype function declarations with calling conventions that | ||||||
9380 | // don't support variadic calls. Only do this in C and do it after merging | ||||||
9381 | // possibly prototyped redeclarations. | ||||||
9382 | const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); | ||||||
9383 | if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { | ||||||
9384 | CallingConv CC = FT->getExtInfo().getCC(); | ||||||
9385 | if (!supportsVariadicCall(CC)) { | ||||||
9386 | // Windows system headers sometimes accidentally use stdcall without | ||||||
9387 | // (void) parameters, so we relax this to a warning. | ||||||
9388 | int DiagID = | ||||||
9389 | CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; | ||||||
9390 | Diag(NewFD->getLocation(), DiagID) | ||||||
9391 | << FunctionType::getNameForCallConv(CC); | ||||||
9392 | } | ||||||
9393 | } | ||||||
9394 | |||||||
9395 | if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||||
9396 | NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
9397 | checkNonTrivialCUnion(NewFD->getReturnType(), | ||||||
9398 | NewFD->getReturnTypeSourceRange().getBegin(), | ||||||
9399 | NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); | ||||||
9400 | } else { | ||||||
9401 | // C++11 [replacement.functions]p3: | ||||||
9402 | // The program's definitions shall not be specified as inline. | ||||||
9403 | // | ||||||
9404 | // N.B. We diagnose declarations instead of definitions per LWG issue 2340. | ||||||
9405 | // | ||||||
9406 | // Suppress the diagnostic if the function is __attribute__((used)), since | ||||||
9407 | // that forces an external definition to be emitted. | ||||||
9408 | if (D.getDeclSpec().isInlineSpecified() && | ||||||
9409 | NewFD->isReplaceableGlobalAllocationFunction() && | ||||||
9410 | !NewFD->hasAttr<UsedAttr>()) | ||||||
9411 | Diag(D.getDeclSpec().getInlineSpecLoc(), | ||||||
9412 | diag::ext_operator_new_delete_declared_inline) | ||||||
9413 | << NewFD->getDeclName(); | ||||||
9414 | |||||||
9415 | // If the declarator is a template-id, translate the parser's template | ||||||
9416 | // argument list into our AST format. | ||||||
9417 | if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { | ||||||
9418 | TemplateIdAnnotation *TemplateId = D.getName().TemplateId; | ||||||
9419 | TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); | ||||||
9420 | TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); | ||||||
9421 | ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), | ||||||
9422 | TemplateId->NumArgs); | ||||||
9423 | translateTemplateArguments(TemplateArgsPtr, | ||||||
9424 | TemplateArgs); | ||||||
9425 | |||||||
9426 | HasExplicitTemplateArgs = true; | ||||||
9427 | |||||||
9428 | if (NewFD->isInvalidDecl()) { | ||||||
9429 | HasExplicitTemplateArgs = false; | ||||||
9430 | } else if (FunctionTemplate) { | ||||||
9431 | // Function template with explicit template arguments. | ||||||
9432 | Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) | ||||||
9433 | << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); | ||||||
9434 | |||||||
9435 | HasExplicitTemplateArgs = false; | ||||||
9436 | } else { | ||||||
9437 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9439, __PRETTY_FUNCTION__)) | ||||||
9438 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9439, __PRETTY_FUNCTION__)) | ||||||
9439 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9439, __PRETTY_FUNCTION__)); | ||||||
9440 | // "friend void foo<>(int);" is an implicit specialization decl. | ||||||
9441 | isFunctionTemplateSpecialization = true; | ||||||
9442 | } | ||||||
9443 | } else if (isFriend && isFunctionTemplateSpecialization) { | ||||||
9444 | // This combination is only possible in a recovery case; the user | ||||||
9445 | // wrote something like: | ||||||
9446 | // template <> friend void foo(int); | ||||||
9447 | // which we're recovering from as if the user had written: | ||||||
9448 | // friend void foo<>(int); | ||||||
9449 | // Go ahead and fake up a template id. | ||||||
9450 | HasExplicitTemplateArgs = true; | ||||||
9451 | TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); | ||||||
9452 | TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); | ||||||
9453 | } | ||||||
9454 | |||||||
9455 | // We do not add HD attributes to specializations here because | ||||||
9456 | // they may have different constexpr-ness compared to their | ||||||
9457 | // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, | ||||||
9458 | // may end up with different effective targets. Instead, a | ||||||
9459 | // specialization inherits its target attributes from its template | ||||||
9460 | // in the CheckFunctionTemplateSpecialization() call below. | ||||||
9461 | if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) | ||||||
9462 | maybeAddCUDAHostDeviceAttrs(NewFD, Previous); | ||||||
9463 | |||||||
9464 | // If it's a friend (and only if it's a friend), it's possible | ||||||
9465 | // that either the specialized function type or the specialized | ||||||
9466 | // template is dependent, and therefore matching will fail. In | ||||||
9467 | // this case, don't check the specialization yet. | ||||||
9468 | bool InstantiationDependent = false; | ||||||
9469 | if (isFunctionTemplateSpecialization && isFriend && | ||||||
9470 | (NewFD->getType()->isDependentType() || DC->isDependentContext() || | ||||||
9471 | TemplateSpecializationType::anyDependentTemplateArguments( | ||||||
9472 | TemplateArgs, | ||||||
9473 | InstantiationDependent))) { | ||||||
9474 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9475, __PRETTY_FUNCTION__)) | ||||||
9475 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9475, __PRETTY_FUNCTION__)); | ||||||
9476 | if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, | ||||||
9477 | Previous)) | ||||||
9478 | NewFD->setInvalidDecl(); | ||||||
9479 | } else if (isFunctionTemplateSpecialization) { | ||||||
9480 | if (CurContext->isDependentContext() && CurContext->isRecord() | ||||||
9481 | && !isFriend) { | ||||||
9482 | isDependentClassScopeExplicitSpecialization = true; | ||||||
9483 | } else if (!NewFD->isInvalidDecl() && | ||||||
9484 | CheckFunctionTemplateSpecialization( | ||||||
9485 | NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), | ||||||
9486 | Previous)) | ||||||
9487 | NewFD->setInvalidDecl(); | ||||||
9488 | |||||||
9489 | // C++ [dcl.stc]p1: | ||||||
9490 | // A storage-class-specifier shall not be specified in an explicit | ||||||
9491 | // specialization (14.7.3) | ||||||
9492 | FunctionTemplateSpecializationInfo *Info = | ||||||
9493 | NewFD->getTemplateSpecializationInfo(); | ||||||
9494 | if (Info && SC != SC_None) { | ||||||
9495 | if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) | ||||||
9496 | Diag(NewFD->getLocation(), | ||||||
9497 | diag::err_explicit_specialization_inconsistent_storage_class) | ||||||
9498 | << SC | ||||||
9499 | << FixItHint::CreateRemoval( | ||||||
9500 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
9501 | |||||||
9502 | else | ||||||
9503 | Diag(NewFD->getLocation(), | ||||||
9504 | diag::ext_explicit_specialization_storage_class) | ||||||
9505 | << FixItHint::CreateRemoval( | ||||||
9506 | D.getDeclSpec().getStorageClassSpecLoc()); | ||||||
9507 | } | ||||||
9508 | } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { | ||||||
9509 | if (CheckMemberSpecialization(NewFD, Previous)) | ||||||
9510 | NewFD->setInvalidDecl(); | ||||||
9511 | } | ||||||
9512 | |||||||
9513 | // Perform semantic checking on the function declaration. | ||||||
9514 | if (!isDependentClassScopeExplicitSpecialization) { | ||||||
9515 | if (!NewFD->isInvalidDecl() && NewFD->isMain()) | ||||||
9516 | CheckMain(NewFD, D.getDeclSpec()); | ||||||
9517 | |||||||
9518 | if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) | ||||||
9519 | CheckMSVCRTEntryPoint(NewFD); | ||||||
9520 | |||||||
9521 | if (!NewFD->isInvalidDecl()) | ||||||
9522 | D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, | ||||||
9523 | isMemberSpecialization)); | ||||||
9524 | else if (!Previous.empty()) | ||||||
9525 | // Recover gracefully from an invalid redeclaration. | ||||||
9526 | D.setRedeclaration(true); | ||||||
9527 | } | ||||||
9528 | |||||||
9529 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9531, __PRETTY_FUNCTION__)) | ||||||
9530 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9531, __PRETTY_FUNCTION__)) | ||||||
9531 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 9531, __PRETTY_FUNCTION__)); | ||||||
9532 | |||||||
9533 | NamedDecl *PrincipalDecl = (FunctionTemplate | ||||||
9534 | ? cast<NamedDecl>(FunctionTemplate) | ||||||
9535 | : NewFD); | ||||||
9536 | |||||||
9537 | if (isFriend && NewFD->getPreviousDecl()) { | ||||||
9538 | AccessSpecifier Access = AS_public; | ||||||
9539 | if (!NewFD->isInvalidDecl()) | ||||||
9540 | Access = NewFD->getPreviousDecl()->getAccess(); | ||||||
9541 | |||||||
9542 | NewFD->setAccess(Access); | ||||||
9543 | if (FunctionTemplate) FunctionTemplate->setAccess(Access); | ||||||
9544 | } | ||||||
9545 | |||||||
9546 | if (NewFD->isOverloadedOperator() && !DC->isRecord() && | ||||||
9547 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) | ||||||
9548 | PrincipalDecl->setNonMemberOperator(); | ||||||
9549 | |||||||
9550 | // If we have a function template, check the template parameter | ||||||
9551 | // list. This will check and merge default template arguments. | ||||||
9552 | if (FunctionTemplate) { | ||||||
9553 | FunctionTemplateDecl *PrevTemplate = | ||||||
9554 | FunctionTemplate->getPreviousDecl(); | ||||||
9555 | CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), | ||||||
9556 | PrevTemplate ? PrevTemplate->getTemplateParameters() | ||||||
9557 | : nullptr, | ||||||
9558 | D.getDeclSpec().isFriendSpecified() | ||||||
9559 | ? (D.isFunctionDefinition() | ||||||
9560 | ? TPC_FriendFunctionTemplateDefinition | ||||||
9561 | : TPC_FriendFunctionTemplate) | ||||||
9562 | : (D.getCXXScopeSpec().isSet() && | ||||||
9563 | DC && DC->isRecord() && | ||||||
9564 | DC->isDependentContext()) | ||||||
9565 | ? TPC_ClassTemplateMember | ||||||
9566 | : TPC_FunctionTemplate); | ||||||
9567 | } | ||||||
9568 | |||||||
9569 | if (NewFD->isInvalidDecl()) { | ||||||
9570 | // Ignore all the rest of this. | ||||||
9571 | } else if (!D.isRedeclaration()) { | ||||||
9572 | struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, | ||||||
9573 | AddToScope }; | ||||||
9574 | // Fake up an access specifier if it's supposed to be a class member. | ||||||
9575 | if (isa<CXXRecordDecl>(NewFD->getDeclContext())) | ||||||
9576 | NewFD->setAccess(AS_public); | ||||||
9577 | |||||||
9578 | // Qualified decls generally require a previous declaration. | ||||||
9579 | if (D.getCXXScopeSpec().isSet()) { | ||||||
9580 | // ...with the major exception of templated-scope or | ||||||
9581 | // dependent-scope friend declarations. | ||||||
9582 | |||||||
9583 | // TODO: we currently also suppress this check in dependent | ||||||
9584 | // contexts because (1) the parameter depth will be off when | ||||||
9585 | // matching friend templates and (2) we might actually be | ||||||
9586 | // selecting a friend based on a dependent factor. But there | ||||||
9587 | // are situations where these conditions don't apply and we | ||||||
9588 | // can actually do this check immediately. | ||||||
9589 | // | ||||||
9590 | // Unless the scope is dependent, it's always an error if qualified | ||||||
9591 | // redeclaration lookup found nothing at all. Diagnose that now; | ||||||
9592 | // nothing will diagnose that error later. | ||||||
9593 | if (isFriend && | ||||||
9594 | (D.getCXXScopeSpec().getScopeRep()->isDependent() || | ||||||
9595 | (!Previous.empty() && CurContext->isDependentContext()))) { | ||||||
9596 | // ignore these | ||||||
9597 | } else { | ||||||
9598 | // The user tried to provide an out-of-line definition for a | ||||||
9599 | // function that is a member of a class or namespace, but there | ||||||
9600 | // was no such member function declared (C++ [class.mfct]p2, | ||||||
9601 | // C++ [namespace.memdef]p2). For example: | ||||||
9602 | // | ||||||
9603 | // class X { | ||||||
9604 | // void f() const; | ||||||
9605 | // }; | ||||||
9606 | // | ||||||
9607 | // void X::f() { } // ill-formed | ||||||
9608 | // | ||||||
9609 | // Complain about this problem, and attempt to suggest close | ||||||
9610 | // matches (e.g., those that differ only in cv-qualifiers and | ||||||
9611 | // whether the parameter types are references). | ||||||
9612 | |||||||
9613 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | ||||||
9614 | *this, Previous, NewFD, ExtraArgs, false, nullptr)) { | ||||||
9615 | AddToScope = ExtraArgs.AddToScope; | ||||||
9616 | return Result; | ||||||
9617 | } | ||||||
9618 | } | ||||||
9619 | |||||||
9620 | // Unqualified local friend declarations are required to resolve | ||||||
9621 | // to something. | ||||||
9622 | } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { | ||||||
9623 | if (NamedDecl *Result = DiagnoseInvalidRedeclaration( | ||||||
9624 | *this, Previous, NewFD, ExtraArgs, true, S)) { | ||||||
9625 | AddToScope = ExtraArgs.AddToScope; | ||||||
9626 | return Result; | ||||||
9627 | } | ||||||
9628 | } | ||||||
9629 | } else if (!D.isFunctionDefinition() && | ||||||
9630 | isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && | ||||||
9631 | !isFriend && !isFunctionTemplateSpecialization && | ||||||
9632 | !isMemberSpecialization) { | ||||||
9633 | // An out-of-line member function declaration must also be a | ||||||
9634 | // definition (C++ [class.mfct]p2). | ||||||
9635 | // Note that this is not the case for explicit specializations of | ||||||
9636 | // function templates or member functions of class templates, per | ||||||
9637 | // C++ [temp.expl.spec]p2. We also allow these declarations as an | ||||||
9638 | // extension for compatibility with old SWIG code which likes to | ||||||
9639 | // generate them. | ||||||
9640 | Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) | ||||||
9641 | << D.getCXXScopeSpec().getRange(); | ||||||
9642 | } | ||||||
9643 | } | ||||||
9644 | |||||||
9645 | // In C builtins get merged with implicitly lazily created declarations. | ||||||
9646 | // In C++ we need to check if it's a builtin and add the BuiltinAttr here. | ||||||
9647 | if (getLangOpts().CPlusPlus) { | ||||||
9648 | if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) { | ||||||
9649 | if (unsigned BuiltinID = II->getBuiltinID()) { | ||||||
9650 | if (NewFD->getLanguageLinkage() == CLanguageLinkage) { | ||||||
9651 | // Declarations for builtins with custom typechecking by definition | ||||||
9652 | // don't make sense. Don't attempt typechecking and simply add the | ||||||
9653 | // attribute. | ||||||
9654 | if (Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) { | ||||||
9655 | NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); | ||||||
9656 | } else { | ||||||
9657 | ASTContext::GetBuiltinTypeError Error; | ||||||
9658 | LookupNecessaryTypesForBuiltin(S, BuiltinID); | ||||||
9659 | QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error); | ||||||
9660 | |||||||
9661 | if (!Error && !BuiltinType.isNull() && | ||||||
9662 | Context.hasSameFunctionTypeIgnoringExceptionSpec( | ||||||
9663 | NewFD->getType(), BuiltinType)) | ||||||
9664 | NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); | ||||||
9665 | } | ||||||
9666 | } else if (BuiltinID == Builtin::BI__GetExceptionInfo && | ||||||
9667 | Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||||
9668 | // FIXME: We should consider this a builtin only in the std namespace. | ||||||
9669 | NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID)); | ||||||
9670 | } | ||||||
9671 | } | ||||||
9672 | } | ||||||
9673 | } | ||||||
9674 | |||||||
9675 | ProcessPragmaWeak(S, NewFD); | ||||||
9676 | checkAttributesAfterMerging(*this, *NewFD); | ||||||
9677 | |||||||
9678 | AddKnownFunctionAttributes(NewFD); | ||||||
9679 | |||||||
9680 | if (NewFD->hasAttr<OverloadableAttr>() && | ||||||
9681 | !NewFD->getType()->getAs<FunctionProtoType>()) { | ||||||
9682 | Diag(NewFD->getLocation(), | ||||||
9683 | diag::err_attribute_overloadable_no_prototype) | ||||||
9684 | << NewFD; | ||||||
9685 | |||||||
9686 | // Turn this into a variadic function with no parameters. | ||||||
9687 | const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); | ||||||
9688 | FunctionProtoType::ExtProtoInfo EPI( | ||||||
9689 | Context.getDefaultCallingConvention(true, false)); | ||||||
9690 | EPI.Variadic = true; | ||||||
9691 | EPI.ExtInfo = FT->getExtInfo(); | ||||||
9692 | |||||||
9693 | QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); | ||||||
9694 | NewFD->setType(R); | ||||||
9695 | } | ||||||
9696 | |||||||
9697 | // If there's a #pragma GCC visibility in scope, and this isn't a class | ||||||
9698 | // member, set the visibility of this function. | ||||||
9699 | if (!DC->isRecord() && NewFD->isExternallyVisible()) | ||||||
9700 | AddPushedVisibilityAttribute(NewFD); | ||||||
9701 | |||||||
9702 | // If there's a #pragma clang arc_cf_code_audited in scope, consider | ||||||
9703 | // marking the function. | ||||||
9704 | AddCFAuditedAttribute(NewFD); | ||||||
9705 | |||||||
9706 | // If this is a function definition, check if we have to apply optnone due to | ||||||
9707 | // a pragma. | ||||||
9708 | if(D.isFunctionDefinition()) | ||||||
9709 | AddRangeBasedOptnone(NewFD); | ||||||
9710 | |||||||
9711 | // If this is the first declaration of an extern C variable, update | ||||||
9712 | // the map of such variables. | ||||||
9713 | if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && | ||||||
9714 | isIncompleteDeclExternC(*this, NewFD)) | ||||||
9715 | RegisterLocallyScopedExternCDecl(NewFD, S); | ||||||
9716 | |||||||
9717 | // Set this FunctionDecl's range up to the right paren. | ||||||
9718 | NewFD->setRangeEnd(D.getSourceRange().getEnd()); | ||||||
9719 | |||||||
9720 | if (D.isRedeclaration() && !Previous.empty()) { | ||||||
9721 | NamedDecl *Prev = Previous.getRepresentativeDecl(); | ||||||
9722 | checkDLLAttributeRedeclaration(*this, Prev, NewFD, | ||||||
9723 | isMemberSpecialization || | ||||||
9724 | isFunctionTemplateSpecialization, | ||||||
9725 | D.isFunctionDefinition()); | ||||||
9726 | } | ||||||
9727 | |||||||
9728 | if (getLangOpts().CUDA) { | ||||||
9729 | IdentifierInfo *II = NewFD->getIdentifier(); | ||||||
9730 | if (II && II->isStr(getCudaConfigureFuncName()) && | ||||||
9731 | !NewFD->isInvalidDecl() && | ||||||
9732 | NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { | ||||||
9733 | if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) | ||||||
9734 | Diag(NewFD->getLocation(), diag::err_config_scalar_return) | ||||||
9735 | << getCudaConfigureFuncName(); | ||||||
9736 | Context.setcudaConfigureCallDecl(NewFD); | ||||||
9737 | } | ||||||
9738 | |||||||
9739 | // Variadic functions, other than a *declaration* of printf, are not allowed | ||||||
9740 | // in device-side CUDA code, unless someone passed | ||||||
9741 | // -fcuda-allow-variadic-functions. | ||||||
9742 | if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && | ||||||
9743 | (NewFD->hasAttr<CUDADeviceAttr>() || | ||||||
9744 | NewFD->hasAttr<CUDAGlobalAttr>()) && | ||||||
9745 | !(II && II->isStr("printf") && NewFD->isExternC() && | ||||||
9746 | !D.isFunctionDefinition())) { | ||||||
9747 | Diag(NewFD->getLocation(), diag::err_variadic_device_fn); | ||||||
9748 | } | ||||||
9749 | } | ||||||
9750 | |||||||
9751 | MarkUnusedFileScopedDecl(NewFD); | ||||||
9752 | |||||||
9753 | |||||||
9754 | |||||||
9755 | if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { | ||||||
9756 | // OpenCL v1.2 s6.8 static is invalid for kernel functions. | ||||||
9757 | if ((getLangOpts().OpenCLVersion >= 120) | ||||||
9758 | && (SC == SC_Static)) { | ||||||
9759 | Diag(D.getIdentifierLoc(), diag::err_static_kernel); | ||||||
9760 | D.setInvalidType(); | ||||||
9761 | } | ||||||
9762 | |||||||
9763 | // OpenCL v1.2, s6.9 -- Kernels can only have return type void. | ||||||
9764 | if (!NewFD->getReturnType()->isVoidType()) { | ||||||
9765 | SourceRange RTRange = NewFD->getReturnTypeSourceRange(); | ||||||
9766 | Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) | ||||||
9767 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") | ||||||
9768 | : FixItHint()); | ||||||
9769 | D.setInvalidType(); | ||||||
9770 | } | ||||||
9771 | |||||||
9772 | llvm::SmallPtrSet<const Type *, 16> ValidTypes; | ||||||
9773 | for (auto Param : NewFD->parameters()) | ||||||
9774 | checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); | ||||||
9775 | |||||||
9776 | if (getLangOpts().OpenCLCPlusPlus) { | ||||||
9777 | if (DC->isRecord()) { | ||||||
9778 | Diag(D.getIdentifierLoc(), diag::err_method_kernel); | ||||||
9779 | D.setInvalidType(); | ||||||
9780 | } | ||||||
9781 | if (FunctionTemplate) { | ||||||
9782 | Diag(D.getIdentifierLoc(), diag::err_template_kernel); | ||||||
9783 | D.setInvalidType(); | ||||||
9784 | } | ||||||
9785 | } | ||||||
9786 | } | ||||||
9787 | |||||||
9788 | if (getLangOpts().CPlusPlus) { | ||||||
9789 | if (FunctionTemplate) { | ||||||
9790 | if (NewFD->isInvalidDecl()) | ||||||
9791 | FunctionTemplate->setInvalidDecl(); | ||||||
9792 | return FunctionTemplate; | ||||||
9793 | } | ||||||
9794 | |||||||
9795 | if (isMemberSpecialization && !NewFD->isInvalidDecl()) | ||||||
9796 | CompleteMemberSpecialization(NewFD, Previous); | ||||||
9797 | } | ||||||
9798 | |||||||
9799 | for (const ParmVarDecl *Param : NewFD->parameters()) { | ||||||
9800 | QualType PT = Param->getType(); | ||||||
9801 | |||||||
9802 | // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value | ||||||
9803 | // types. | ||||||
9804 | if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { | ||||||
9805 | if(const PipeType *PipeTy = PT->getAs<PipeType>()) { | ||||||
9806 | QualType ElemTy = PipeTy->getElementType(); | ||||||
9807 | if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { | ||||||
9808 | Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); | ||||||
9809 | D.setInvalidType(); | ||||||
9810 | } | ||||||
9811 | } | ||||||
9812 | } | ||||||
9813 | } | ||||||
9814 | |||||||
9815 | // Here we have an function template explicit specialization at class scope. | ||||||
9816 | // The actual specialization will be postponed to template instatiation | ||||||
9817 | // time via the ClassScopeFunctionSpecializationDecl node. | ||||||
9818 | if (isDependentClassScopeExplicitSpecialization) { | ||||||
9819 | ClassScopeFunctionSpecializationDecl *NewSpec = | ||||||
9820 | ClassScopeFunctionSpecializationDecl::Create( | ||||||
9821 | Context, CurContext, NewFD->getLocation(), | ||||||
9822 | cast<CXXMethodDecl>(NewFD), | ||||||
9823 | HasExplicitTemplateArgs, TemplateArgs); | ||||||
9824 | CurContext->addDecl(NewSpec); | ||||||
9825 | AddToScope = false; | ||||||
9826 | } | ||||||
9827 | |||||||
9828 | // Diagnose availability attributes. Availability cannot be used on functions | ||||||
9829 | // that are run during load/unload. | ||||||
9830 | if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { | ||||||
9831 | if (NewFD->hasAttr<ConstructorAttr>()) { | ||||||
9832 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | ||||||
9833 | << 1; | ||||||
9834 | NewFD->dropAttr<AvailabilityAttr>(); | ||||||
9835 | } | ||||||
9836 | if (NewFD->hasAttr<DestructorAttr>()) { | ||||||
9837 | Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) | ||||||
9838 | << 2; | ||||||
9839 | NewFD->dropAttr<AvailabilityAttr>(); | ||||||
9840 | } | ||||||
9841 | } | ||||||
9842 | |||||||
9843 | // Diagnose no_builtin attribute on function declaration that are not a | ||||||
9844 | // definition. | ||||||
9845 | // FIXME: We should really be doing this in | ||||||
9846 | // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to | ||||||
9847 | // the FunctionDecl and at this point of the code | ||||||
9848 | // FunctionDecl::isThisDeclarationADefinition() which always returns `false` | ||||||
9849 | // because Sema::ActOnStartOfFunctionDef has not been called yet. | ||||||
9850 | if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) | ||||||
9851 | switch (D.getFunctionDefinitionKind()) { | ||||||
9852 | case FDK_Defaulted: | ||||||
9853 | case FDK_Deleted: | ||||||
9854 | Diag(NBA->getLocation(), | ||||||
9855 | diag::err_attribute_no_builtin_on_defaulted_deleted_function) | ||||||
9856 | << NBA->getSpelling(); | ||||||
9857 | break; | ||||||
9858 | case FDK_Declaration: | ||||||
9859 | Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) | ||||||
9860 | << NBA->getSpelling(); | ||||||
9861 | break; | ||||||
9862 | case FDK_Definition: | ||||||
9863 | break; | ||||||
9864 | } | ||||||
9865 | |||||||
9866 | return NewFD; | ||||||
9867 | } | ||||||
9868 | |||||||
9869 | /// Return a CodeSegAttr from a containing class. The Microsoft docs say | ||||||
9870 | /// when __declspec(code_seg) "is applied to a class, all member functions of | ||||||
9871 | /// the class and nested classes -- this includes compiler-generated special | ||||||
9872 | /// member functions -- are put in the specified segment." | ||||||
9873 | /// The actual behavior is a little more complicated. The Microsoft compiler | ||||||
9874 | /// won't check outer classes if there is an active value from #pragma code_seg. | ||||||
9875 | /// The CodeSeg is always applied from the direct parent but only from outer | ||||||
9876 | /// classes when the #pragma code_seg stack is empty. See: | ||||||
9877 | /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer | ||||||
9878 | /// available since MS has removed the page. | ||||||
9879 | static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { | ||||||
9880 | const auto *Method = dyn_cast<CXXMethodDecl>(FD); | ||||||
9881 | if (!Method) | ||||||
9882 | return nullptr; | ||||||
9883 | const CXXRecordDecl *Parent = Method->getParent(); | ||||||
9884 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | ||||||
9885 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | ||||||
9886 | NewAttr->setImplicit(true); | ||||||
9887 | return NewAttr; | ||||||
9888 | } | ||||||
9889 | |||||||
9890 | // The Microsoft compiler won't check outer classes for the CodeSeg | ||||||
9891 | // when the #pragma code_seg stack is active. | ||||||
9892 | if (S.CodeSegStack.CurrentValue) | ||||||
9893 | return nullptr; | ||||||
9894 | |||||||
9895 | while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { | ||||||
9896 | if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { | ||||||
9897 | Attr *NewAttr = SAttr->clone(S.getASTContext()); | ||||||
9898 | NewAttr->setImplicit(true); | ||||||
9899 | return NewAttr; | ||||||
9900 | } | ||||||
9901 | } | ||||||
9902 | return nullptr; | ||||||
9903 | } | ||||||
9904 | |||||||
9905 | /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a | ||||||
9906 | /// containing class. Otherwise it will return implicit SectionAttr if the | ||||||
9907 | /// function is a definition and there is an active value on CodeSegStack | ||||||
9908 | /// (from the current #pragma code-seg value). | ||||||
9909 | /// | ||||||
9910 | /// \param FD Function being declared. | ||||||
9911 | /// \param IsDefinition Whether it is a definition or just a declarartion. | ||||||
9912 | /// \returns A CodeSegAttr or SectionAttr to apply to the function or | ||||||
9913 | /// nullptr if no attribute should be added. | ||||||
9914 | Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, | ||||||
9915 | bool IsDefinition) { | ||||||
9916 | if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) | ||||||
9917 | return A; | ||||||
9918 | if (!FD->hasAttr<SectionAttr>() && IsDefinition && | ||||||
9919 | CodeSegStack.CurrentValue) | ||||||
9920 | return SectionAttr::CreateImplicit( | ||||||
9921 | getASTContext(), CodeSegStack.CurrentValue->getString(), | ||||||
9922 | CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, | ||||||
9923 | SectionAttr::Declspec_allocate); | ||||||
9924 | return nullptr; | ||||||
9925 | } | ||||||
9926 | |||||||
9927 | /// Determines if we can perform a correct type check for \p D as a | ||||||
9928 | /// redeclaration of \p PrevDecl. If not, we can generally still perform a | ||||||
9929 | /// best-effort check. | ||||||
9930 | /// | ||||||
9931 | /// \param NewD The new declaration. | ||||||
9932 | /// \param OldD The old declaration. | ||||||
9933 | /// \param NewT The portion of the type of the new declaration to check. | ||||||
9934 | /// \param OldT The portion of the type of the old declaration to check. | ||||||
9935 | bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, | ||||||
9936 | QualType NewT, QualType OldT) { | ||||||
9937 | if (!NewD->getLexicalDeclContext()->isDependentContext()) | ||||||
9938 | return true; | ||||||
9939 | |||||||
9940 | // For dependently-typed local extern declarations and friends, we can't | ||||||
9941 | // perform a correct type check in general until instantiation: | ||||||
9942 | // | ||||||
9943 | // int f(); | ||||||
9944 | // template<typename T> void g() { T f(); } | ||||||
9945 | // | ||||||
9946 | // (valid if g() is only instantiated with T = int). | ||||||
9947 | if (NewT->isDependentType() && | ||||||
9948 | (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) | ||||||
9949 | return false; | ||||||
9950 | |||||||
9951 | // Similarly, if the previous declaration was a dependent local extern | ||||||
9952 | // declaration, we don't really know its type yet. | ||||||
9953 | if (OldT->isDependentType() && OldD->isLocalExternDecl()) | ||||||
9954 | return false; | ||||||
9955 | |||||||
9956 | return true; | ||||||
9957 | } | ||||||
9958 | |||||||
9959 | /// Checks if the new declaration declared in dependent context must be | ||||||
9960 | /// put in the same redeclaration chain as the specified declaration. | ||||||
9961 | /// | ||||||
9962 | /// \param D Declaration that is checked. | ||||||
9963 | /// \param PrevDecl Previous declaration found with proper lookup method for the | ||||||
9964 | /// same declaration name. | ||||||
9965 | /// \returns True if D must be added to the redeclaration chain which PrevDecl | ||||||
9966 | /// belongs to. | ||||||
9967 | /// | ||||||
9968 | bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { | ||||||
9969 | if (!D->getLexicalDeclContext()->isDependentContext()) | ||||||
9970 | return true; | ||||||
9971 | |||||||
9972 | // Don't chain dependent friend function definitions until instantiation, to | ||||||
9973 | // permit cases like | ||||||
9974 | // | ||||||
9975 | // void func(); | ||||||
9976 | // template<typename T> class C1 { friend void func() {} }; | ||||||
9977 | // template<typename T> class C2 { friend void func() {} }; | ||||||
9978 | // | ||||||
9979 | // ... which is valid if only one of C1 and C2 is ever instantiated. | ||||||
9980 | // | ||||||
9981 | // FIXME: This need only apply to function definitions. For now, we proxy | ||||||
9982 | // this by checking for a file-scope function. We do not want this to apply | ||||||
9983 | // to friend declarations nominating member functions, because that gets in | ||||||
9984 | // the way of access checks. | ||||||
9985 | if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) | ||||||
9986 | return false; | ||||||
9987 | |||||||
9988 | auto *VD = dyn_cast<ValueDecl>(D); | ||||||
9989 | auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); | ||||||
9990 | return !VD || !PrevVD || | ||||||
9991 | canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), | ||||||
9992 | PrevVD->getType()); | ||||||
9993 | } | ||||||
9994 | |||||||
9995 | /// Check the target attribute of the function for MultiVersion | ||||||
9996 | /// validity. | ||||||
9997 | /// | ||||||
9998 | /// Returns true if there was an error, false otherwise. | ||||||
9999 | static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { | ||||||
10000 | const auto *TA = FD->getAttr<TargetAttr>(); | ||||||
10001 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10001, __PRETTY_FUNCTION__)); | ||||||
10002 | ParsedTargetAttr ParseInfo = TA->parse(); | ||||||
10003 | const TargetInfo &TargetInfo = S.Context.getTargetInfo(); | ||||||
10004 | enum ErrType { Feature = 0, Architecture = 1 }; | ||||||
10005 | |||||||
10006 | if (!ParseInfo.Architecture.empty() && | ||||||
10007 | !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { | ||||||
10008 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
10009 | << Architecture << ParseInfo.Architecture; | ||||||
10010 | return true; | ||||||
10011 | } | ||||||
10012 | |||||||
10013 | for (const auto &Feat : ParseInfo.Features) { | ||||||
10014 | auto BareFeat = StringRef{Feat}.substr(1); | ||||||
10015 | if (Feat[0] == '-') { | ||||||
10016 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
10017 | << Feature << ("no-" + BareFeat).str(); | ||||||
10018 | return true; | ||||||
10019 | } | ||||||
10020 | |||||||
10021 | if (!TargetInfo.validateCpuSupports(BareFeat) || | ||||||
10022 | !TargetInfo.isValidFeatureName(BareFeat)) { | ||||||
10023 | S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) | ||||||
10024 | << Feature << BareFeat; | ||||||
10025 | return true; | ||||||
10026 | } | ||||||
10027 | } | ||||||
10028 | return false; | ||||||
10029 | } | ||||||
10030 | |||||||
10031 | // Provide a white-list of attributes that are allowed to be combined with | ||||||
10032 | // multiversion functions. | ||||||
10033 | static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, | ||||||
10034 | MultiVersionKind MVType) { | ||||||
10035 | // Note: this list/diagnosis must match the list in | ||||||
10036 | // checkMultiversionAttributesAllSame. | ||||||
10037 | switch (Kind) { | ||||||
10038 | default: | ||||||
10039 | return false; | ||||||
10040 | case attr::Used: | ||||||
10041 | return MVType == MultiVersionKind::Target; | ||||||
10042 | case attr::NonNull: | ||||||
10043 | case attr::NoThrow: | ||||||
10044 | return true; | ||||||
10045 | } | ||||||
10046 | } | ||||||
10047 | |||||||
10048 | static bool checkNonMultiVersionCompatAttributes(Sema &S, | ||||||
10049 | const FunctionDecl *FD, | ||||||
10050 | const FunctionDecl *CausedFD, | ||||||
10051 | MultiVersionKind MVType) { | ||||||
10052 | bool IsCPUSpecificCPUDispatchMVType = | ||||||
10053 | MVType == MultiVersionKind::CPUDispatch || | ||||||
10054 | MVType == MultiVersionKind::CPUSpecific; | ||||||
10055 | const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType]( | ||||||
10056 | Sema &S, const Attr *A) { | ||||||
10057 | S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr) | ||||||
10058 | << IsCPUSpecificCPUDispatchMVType << A; | ||||||
10059 | if (CausedFD) | ||||||
10060 | S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
10061 | return true; | ||||||
10062 | }; | ||||||
10063 | |||||||
10064 | for (const Attr *A : FD->attrs()) { | ||||||
10065 | switch (A->getKind()) { | ||||||
10066 | case attr::CPUDispatch: | ||||||
10067 | case attr::CPUSpecific: | ||||||
10068 | if (MVType != MultiVersionKind::CPUDispatch && | ||||||
10069 | MVType != MultiVersionKind::CPUSpecific) | ||||||
10070 | return Diagnose(S, A); | ||||||
10071 | break; | ||||||
10072 | case attr::Target: | ||||||
10073 | if (MVType != MultiVersionKind::Target) | ||||||
10074 | return Diagnose(S, A); | ||||||
10075 | break; | ||||||
10076 | default: | ||||||
10077 | if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType)) | ||||||
10078 | return Diagnose(S, A); | ||||||
10079 | break; | ||||||
10080 | } | ||||||
10081 | } | ||||||
10082 | return false; | ||||||
10083 | } | ||||||
10084 | |||||||
10085 | bool Sema::areMultiversionVariantFunctionsCompatible( | ||||||
10086 | const FunctionDecl *OldFD, const FunctionDecl *NewFD, | ||||||
10087 | const PartialDiagnostic &NoProtoDiagID, | ||||||
10088 | const PartialDiagnosticAt &NoteCausedDiagIDAt, | ||||||
10089 | const PartialDiagnosticAt &NoSupportDiagIDAt, | ||||||
10090 | const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, | ||||||
10091 | bool ConstexprSupported, bool CLinkageMayDiffer) { | ||||||
10092 | enum DoesntSupport { | ||||||
10093 | FuncTemplates = 0, | ||||||
10094 | VirtFuncs = 1, | ||||||
10095 | DeducedReturn = 2, | ||||||
10096 | Constructors = 3, | ||||||
10097 | Destructors = 4, | ||||||
10098 | DeletedFuncs = 5, | ||||||
10099 | DefaultedFuncs = 6, | ||||||
10100 | ConstexprFuncs = 7, | ||||||
10101 | ConstevalFuncs = 8, | ||||||
10102 | }; | ||||||
10103 | enum Different { | ||||||
10104 | CallingConv = 0, | ||||||
10105 | ReturnType = 1, | ||||||
10106 | ConstexprSpec = 2, | ||||||
10107 | InlineSpec = 3, | ||||||
10108 | StorageClass = 4, | ||||||
10109 | Linkage = 5, | ||||||
10110 | }; | ||||||
10111 | |||||||
10112 | if (NoProtoDiagID.getDiagID() != 0 && OldFD && | ||||||
10113 | !OldFD->getType()->getAs<FunctionProtoType>()) { | ||||||
10114 | Diag(OldFD->getLocation(), NoProtoDiagID); | ||||||
10115 | Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); | ||||||
10116 | return true; | ||||||
10117 | } | ||||||
10118 | |||||||
10119 | if (NoProtoDiagID.getDiagID() != 0 && | ||||||
10120 | !NewFD->getType()->getAs<FunctionProtoType>()) | ||||||
10121 | return Diag(NewFD->getLocation(), NoProtoDiagID); | ||||||
10122 | |||||||
10123 | if (!TemplatesSupported && | ||||||
10124 | NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) | ||||||
10125 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
10126 | << FuncTemplates; | ||||||
10127 | |||||||
10128 | if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { | ||||||
10129 | if (NewCXXFD->isVirtual()) | ||||||
10130 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
10131 | << VirtFuncs; | ||||||
10132 | |||||||
10133 | if (isa<CXXConstructorDecl>(NewCXXFD)) | ||||||
10134 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
10135 | << Constructors; | ||||||
10136 | |||||||
10137 | if (isa<CXXDestructorDecl>(NewCXXFD)) | ||||||
10138 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
10139 | << Destructors; | ||||||
10140 | } | ||||||
10141 | |||||||
10142 | if (NewFD->isDeleted()) | ||||||
10143 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
10144 | << DeletedFuncs; | ||||||
10145 | |||||||
10146 | if (NewFD->isDefaulted()) | ||||||
10147 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
10148 | << DefaultedFuncs; | ||||||
10149 | |||||||
10150 | if (!ConstexprSupported && NewFD->isConstexpr()) | ||||||
10151 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
10152 | << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); | ||||||
10153 | |||||||
10154 | QualType NewQType = Context.getCanonicalType(NewFD->getType()); | ||||||
10155 | const auto *NewType = cast<FunctionType>(NewQType); | ||||||
10156 | QualType NewReturnType = NewType->getReturnType(); | ||||||
10157 | |||||||
10158 | if (NewReturnType->isUndeducedType()) | ||||||
10159 | return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) | ||||||
10160 | << DeducedReturn; | ||||||
10161 | |||||||
10162 | // Ensure the return type is identical. | ||||||
10163 | if (OldFD) { | ||||||
10164 | QualType OldQType = Context.getCanonicalType(OldFD->getType()); | ||||||
10165 | const auto *OldType = cast<FunctionType>(OldQType); | ||||||
10166 | FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); | ||||||
10167 | FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); | ||||||
10168 | |||||||
10169 | if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) | ||||||
10170 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; | ||||||
10171 | |||||||
10172 | QualType OldReturnType = OldType->getReturnType(); | ||||||
10173 | |||||||
10174 | if (OldReturnType != NewReturnType) | ||||||
10175 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; | ||||||
10176 | |||||||
10177 | if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) | ||||||
10178 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; | ||||||
10179 | |||||||
10180 | if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) | ||||||
10181 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; | ||||||
10182 | |||||||
10183 | if (OldFD->getStorageClass() != NewFD->getStorageClass()) | ||||||
10184 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; | ||||||
10185 | |||||||
10186 | if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) | ||||||
10187 | return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; | ||||||
10188 | |||||||
10189 | if (CheckEquivalentExceptionSpec( | ||||||
10190 | OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), | ||||||
10191 | NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) | ||||||
10192 | return true; | ||||||
10193 | } | ||||||
10194 | return false; | ||||||
10195 | } | ||||||
10196 | |||||||
10197 | static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, | ||||||
10198 | const FunctionDecl *NewFD, | ||||||
10199 | bool CausesMV, | ||||||
10200 | MultiVersionKind MVType) { | ||||||
10201 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | ||||||
10202 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | ||||||
10203 | if (OldFD) | ||||||
10204 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10205 | return true; | ||||||
10206 | } | ||||||
10207 | |||||||
10208 | bool IsCPUSpecificCPUDispatchMVType = | ||||||
10209 | MVType == MultiVersionKind::CPUDispatch || | ||||||
10210 | MVType == MultiVersionKind::CPUSpecific; | ||||||
10211 | |||||||
10212 | if (CausesMV && OldFD && | ||||||
10213 | checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType)) | ||||||
10214 | return true; | ||||||
10215 | |||||||
10216 | if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType)) | ||||||
10217 | return true; | ||||||
10218 | |||||||
10219 | // Only allow transition to MultiVersion if it hasn't been used. | ||||||
10220 | if (OldFD && CausesMV && OldFD->isUsed(false)) | ||||||
10221 | return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); | ||||||
10222 | |||||||
10223 | return S.areMultiversionVariantFunctionsCompatible( | ||||||
10224 | OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), | ||||||
10225 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
10226 | S.PDiag(diag::note_multiversioning_caused_here)), | ||||||
10227 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
10228 | S.PDiag(diag::err_multiversion_doesnt_support) | ||||||
10229 | << IsCPUSpecificCPUDispatchMVType), | ||||||
10230 | PartialDiagnosticAt(NewFD->getLocation(), | ||||||
10231 | S.PDiag(diag::err_multiversion_diff)), | ||||||
10232 | /*TemplatesSupported=*/false, | ||||||
10233 | /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, | ||||||
10234 | /*CLinkageMayDiffer=*/false); | ||||||
10235 | } | ||||||
10236 | |||||||
10237 | /// Check the validity of a multiversion function declaration that is the | ||||||
10238 | /// first of its kind. Also sets the multiversion'ness' of the function itself. | ||||||
10239 | /// | ||||||
10240 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
10241 | /// | ||||||
10242 | /// Returns true if there was an error, false otherwise. | ||||||
10243 | static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, | ||||||
10244 | MultiVersionKind MVType, | ||||||
10245 | const TargetAttr *TA) { | ||||||
10246 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10247, __PRETTY_FUNCTION__)) | ||||||
10247 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10247, __PRETTY_FUNCTION__)); | ||||||
10248 | |||||||
10249 | // Target only causes MV if it is default, otherwise this is a normal | ||||||
10250 | // function. | ||||||
10251 | if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) | ||||||
10252 | return false; | ||||||
10253 | |||||||
10254 | if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { | ||||||
10255 | FD->setInvalidDecl(); | ||||||
10256 | return true; | ||||||
10257 | } | ||||||
10258 | |||||||
10259 | if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { | ||||||
10260 | FD->setInvalidDecl(); | ||||||
10261 | return true; | ||||||
10262 | } | ||||||
10263 | |||||||
10264 | FD->setIsMultiVersion(); | ||||||
10265 | return false; | ||||||
10266 | } | ||||||
10267 | |||||||
10268 | static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { | ||||||
10269 | for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { | ||||||
10270 | if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) | ||||||
10271 | return true; | ||||||
10272 | } | ||||||
10273 | |||||||
10274 | return false; | ||||||
10275 | } | ||||||
10276 | |||||||
10277 | static bool CheckTargetCausesMultiVersioning( | ||||||
10278 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, | ||||||
10279 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | ||||||
10280 | LookupResult &Previous) { | ||||||
10281 | const auto *OldTA = OldFD->getAttr<TargetAttr>(); | ||||||
10282 | ParsedTargetAttr NewParsed = NewTA->parse(); | ||||||
10283 | // Sort order doesn't matter, it just needs to be consistent. | ||||||
10284 | llvm::sort(NewParsed.Features); | ||||||
10285 | |||||||
10286 | // If the old decl is NOT MultiVersioned yet, and we don't cause that | ||||||
10287 | // to change, this is a simple redeclaration. | ||||||
10288 | if (!NewTA->isDefaultVersion() && | ||||||
10289 | (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) | ||||||
10290 | return false; | ||||||
10291 | |||||||
10292 | // Otherwise, this decl causes MultiVersioning. | ||||||
10293 | if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { | ||||||
10294 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); | ||||||
10295 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10296 | NewFD->setInvalidDecl(); | ||||||
10297 | return true; | ||||||
10298 | } | ||||||
10299 | |||||||
10300 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, | ||||||
10301 | MultiVersionKind::Target)) { | ||||||
10302 | NewFD->setInvalidDecl(); | ||||||
10303 | return true; | ||||||
10304 | } | ||||||
10305 | |||||||
10306 | if (CheckMultiVersionValue(S, NewFD)) { | ||||||
10307 | NewFD->setInvalidDecl(); | ||||||
10308 | return true; | ||||||
10309 | } | ||||||
10310 | |||||||
10311 | // If this is 'default', permit the forward declaration. | ||||||
10312 | if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { | ||||||
10313 | Redeclaration = true; | ||||||
10314 | OldDecl = OldFD; | ||||||
10315 | OldFD->setIsMultiVersion(); | ||||||
10316 | NewFD->setIsMultiVersion(); | ||||||
10317 | return false; | ||||||
10318 | } | ||||||
10319 | |||||||
10320 | if (CheckMultiVersionValue(S, OldFD)) { | ||||||
10321 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
10322 | NewFD->setInvalidDecl(); | ||||||
10323 | return true; | ||||||
10324 | } | ||||||
10325 | |||||||
10326 | ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); | ||||||
10327 | |||||||
10328 | if (OldParsed == NewParsed) { | ||||||
10329 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | ||||||
10330 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10331 | NewFD->setInvalidDecl(); | ||||||
10332 | return true; | ||||||
10333 | } | ||||||
10334 | |||||||
10335 | for (const auto *FD : OldFD->redecls()) { | ||||||
10336 | const auto *CurTA = FD->getAttr<TargetAttr>(); | ||||||
10337 | // We allow forward declarations before ANY multiversioning attributes, but | ||||||
10338 | // nothing after the fact. | ||||||
10339 | if (PreviousDeclsHaveMultiVersionAttribute(FD) && | ||||||
10340 | (!CurTA || CurTA->isInherited())) { | ||||||
10341 | S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) | ||||||
10342 | << 0; | ||||||
10343 | S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); | ||||||
10344 | NewFD->setInvalidDecl(); | ||||||
10345 | return true; | ||||||
10346 | } | ||||||
10347 | } | ||||||
10348 | |||||||
10349 | OldFD->setIsMultiVersion(); | ||||||
10350 | NewFD->setIsMultiVersion(); | ||||||
10351 | Redeclaration = false; | ||||||
10352 | MergeTypeWithPrevious = false; | ||||||
10353 | OldDecl = nullptr; | ||||||
10354 | Previous.clear(); | ||||||
10355 | return false; | ||||||
10356 | } | ||||||
10357 | |||||||
10358 | /// Check the validity of a new function declaration being added to an existing | ||||||
10359 | /// multiversioned declaration collection. | ||||||
10360 | static bool CheckMultiVersionAdditionalDecl( | ||||||
10361 | Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, | ||||||
10362 | MultiVersionKind NewMVType, const TargetAttr *NewTA, | ||||||
10363 | const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, | ||||||
10364 | bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, | ||||||
10365 | LookupResult &Previous) { | ||||||
10366 | |||||||
10367 | MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); | ||||||
10368 | // Disallow mixing of multiversioning types. | ||||||
10369 | if ((OldMVType == MultiVersionKind::Target && | ||||||
10370 | NewMVType != MultiVersionKind::Target) || | ||||||
10371 | (NewMVType == MultiVersionKind::Target && | ||||||
10372 | OldMVType != MultiVersionKind::Target)) { | ||||||
10373 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | ||||||
10374 | S.Diag(OldFD->getLocation(), diag::note_previous_declaration); | ||||||
10375 | NewFD->setInvalidDecl(); | ||||||
10376 | return true; | ||||||
10377 | } | ||||||
10378 | |||||||
10379 | ParsedTargetAttr NewParsed; | ||||||
10380 | if (NewTA) { | ||||||
10381 | NewParsed = NewTA->parse(); | ||||||
10382 | llvm::sort(NewParsed.Features); | ||||||
10383 | } | ||||||
10384 | |||||||
10385 | bool UseMemberUsingDeclRules = | ||||||
10386 | S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); | ||||||
10387 | |||||||
10388 | // Next, check ALL non-overloads to see if this is a redeclaration of a | ||||||
10389 | // previous member of the MultiVersion set. | ||||||
10390 | for (NamedDecl *ND : Previous) { | ||||||
10391 | FunctionDecl *CurFD = ND->getAsFunction(); | ||||||
10392 | if (!CurFD) | ||||||
10393 | continue; | ||||||
10394 | if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) | ||||||
10395 | continue; | ||||||
10396 | |||||||
10397 | if (NewMVType == MultiVersionKind::Target) { | ||||||
10398 | const auto *CurTA = CurFD->getAttr<TargetAttr>(); | ||||||
10399 | if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { | ||||||
10400 | NewFD->setIsMultiVersion(); | ||||||
10401 | Redeclaration = true; | ||||||
10402 | OldDecl = ND; | ||||||
10403 | return false; | ||||||
10404 | } | ||||||
10405 | |||||||
10406 | ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); | ||||||
10407 | if (CurParsed == NewParsed) { | ||||||
10408 | S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); | ||||||
10409 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10410 | NewFD->setInvalidDecl(); | ||||||
10411 | return true; | ||||||
10412 | } | ||||||
10413 | } else { | ||||||
10414 | const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); | ||||||
10415 | const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); | ||||||
10416 | // Handle CPUDispatch/CPUSpecific versions. | ||||||
10417 | // Only 1 CPUDispatch function is allowed, this will make it go through | ||||||
10418 | // the redeclaration errors. | ||||||
10419 | if (NewMVType == MultiVersionKind::CPUDispatch && | ||||||
10420 | CurFD->hasAttr<CPUDispatchAttr>()) { | ||||||
10421 | if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && | ||||||
10422 | std::equal( | ||||||
10423 | CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), | ||||||
10424 | NewCPUDisp->cpus_begin(), | ||||||
10425 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | ||||||
10426 | return Cur->getName() == New->getName(); | ||||||
10427 | })) { | ||||||
10428 | NewFD->setIsMultiVersion(); | ||||||
10429 | Redeclaration = true; | ||||||
10430 | OldDecl = ND; | ||||||
10431 | return false; | ||||||
10432 | } | ||||||
10433 | |||||||
10434 | // If the declarations don't match, this is an error condition. | ||||||
10435 | S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); | ||||||
10436 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10437 | NewFD->setInvalidDecl(); | ||||||
10438 | return true; | ||||||
10439 | } | ||||||
10440 | if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { | ||||||
10441 | |||||||
10442 | if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && | ||||||
10443 | std::equal( | ||||||
10444 | CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), | ||||||
10445 | NewCPUSpec->cpus_begin(), | ||||||
10446 | [](const IdentifierInfo *Cur, const IdentifierInfo *New) { | ||||||
10447 | return Cur->getName() == New->getName(); | ||||||
10448 | })) { | ||||||
10449 | NewFD->setIsMultiVersion(); | ||||||
10450 | Redeclaration = true; | ||||||
10451 | OldDecl = ND; | ||||||
10452 | return false; | ||||||
10453 | } | ||||||
10454 | |||||||
10455 | // Only 1 version of CPUSpecific is allowed for each CPU. | ||||||
10456 | for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { | ||||||
10457 | for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { | ||||||
10458 | if (CurII == NewII) { | ||||||
10459 | S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) | ||||||
10460 | << NewII; | ||||||
10461 | S.Diag(CurFD->getLocation(), diag::note_previous_declaration); | ||||||
10462 | NewFD->setInvalidDecl(); | ||||||
10463 | return true; | ||||||
10464 | } | ||||||
10465 | } | ||||||
10466 | } | ||||||
10467 | } | ||||||
10468 | // If the two decls aren't the same MVType, there is no possible error | ||||||
10469 | // condition. | ||||||
10470 | } | ||||||
10471 | } | ||||||
10472 | |||||||
10473 | // Else, this is simply a non-redecl case. Checking the 'value' is only | ||||||
10474 | // necessary in the Target case, since The CPUSpecific/Dispatch cases are | ||||||
10475 | // handled in the attribute adding step. | ||||||
10476 | if (NewMVType == MultiVersionKind::Target && | ||||||
10477 | CheckMultiVersionValue(S, NewFD)) { | ||||||
10478 | NewFD->setInvalidDecl(); | ||||||
10479 | return true; | ||||||
10480 | } | ||||||
10481 | |||||||
10482 | if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, | ||||||
10483 | !OldFD->isMultiVersion(), NewMVType)) { | ||||||
10484 | NewFD->setInvalidDecl(); | ||||||
10485 | return true; | ||||||
10486 | } | ||||||
10487 | |||||||
10488 | // Permit forward declarations in the case where these two are compatible. | ||||||
10489 | if (!OldFD->isMultiVersion()) { | ||||||
10490 | OldFD->setIsMultiVersion(); | ||||||
10491 | NewFD->setIsMultiVersion(); | ||||||
10492 | Redeclaration = true; | ||||||
10493 | OldDecl = OldFD; | ||||||
10494 | return false; | ||||||
10495 | } | ||||||
10496 | |||||||
10497 | NewFD->setIsMultiVersion(); | ||||||
10498 | Redeclaration = false; | ||||||
10499 | MergeTypeWithPrevious = false; | ||||||
10500 | OldDecl = nullptr; | ||||||
10501 | Previous.clear(); | ||||||
10502 | return false; | ||||||
10503 | } | ||||||
10504 | |||||||
10505 | |||||||
10506 | /// Check the validity of a mulitversion function declaration. | ||||||
10507 | /// Also sets the multiversion'ness' of the function itself. | ||||||
10508 | /// | ||||||
10509 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
10510 | /// | ||||||
10511 | /// Returns true if there was an error, false otherwise. | ||||||
10512 | static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, | ||||||
10513 | bool &Redeclaration, NamedDecl *&OldDecl, | ||||||
10514 | bool &MergeTypeWithPrevious, | ||||||
10515 | LookupResult &Previous) { | ||||||
10516 | const auto *NewTA = NewFD->getAttr<TargetAttr>(); | ||||||
10517 | const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); | ||||||
10518 | const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); | ||||||
10519 | |||||||
10520 | // Mixing Multiversioning types is prohibited. | ||||||
10521 | if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || | ||||||
10522 | (NewCPUDisp && NewCPUSpec)) { | ||||||
10523 | S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); | ||||||
10524 | NewFD->setInvalidDecl(); | ||||||
10525 | return true; | ||||||
10526 | } | ||||||
10527 | |||||||
10528 | MultiVersionKind MVType = NewFD->getMultiVersionKind(); | ||||||
10529 | |||||||
10530 | // Main isn't allowed to become a multiversion function, however it IS | ||||||
10531 | // permitted to have 'main' be marked with the 'target' optimization hint. | ||||||
10532 | if (NewFD->isMain()) { | ||||||
10533 | if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || | ||||||
10534 | MVType == MultiVersionKind::CPUDispatch || | ||||||
10535 | MVType == MultiVersionKind::CPUSpecific) { | ||||||
10536 | S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); | ||||||
10537 | NewFD->setInvalidDecl(); | ||||||
10538 | return true; | ||||||
10539 | } | ||||||
10540 | return false; | ||||||
10541 | } | ||||||
10542 | |||||||
10543 | if (!OldDecl || !OldDecl->getAsFunction() || | ||||||
10544 | OldDecl->getDeclContext()->getRedeclContext() != | ||||||
10545 | NewFD->getDeclContext()->getRedeclContext()) { | ||||||
10546 | // If there's no previous declaration, AND this isn't attempting to cause | ||||||
10547 | // multiversioning, this isn't an error condition. | ||||||
10548 | if (MVType == MultiVersionKind::None) | ||||||
10549 | return false; | ||||||
10550 | return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); | ||||||
10551 | } | ||||||
10552 | |||||||
10553 | FunctionDecl *OldFD = OldDecl->getAsFunction(); | ||||||
10554 | |||||||
10555 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) | ||||||
10556 | return false; | ||||||
10557 | |||||||
10558 | if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { | ||||||
10559 | S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) | ||||||
10560 | << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); | ||||||
10561 | NewFD->setInvalidDecl(); | ||||||
10562 | return true; | ||||||
10563 | } | ||||||
10564 | |||||||
10565 | // Handle the target potentially causes multiversioning case. | ||||||
10566 | if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) | ||||||
10567 | return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, | ||||||
10568 | Redeclaration, OldDecl, | ||||||
10569 | MergeTypeWithPrevious, Previous); | ||||||
10570 | |||||||
10571 | // At this point, we have a multiversion function decl (in OldFD) AND an | ||||||
10572 | // appropriate attribute in the current function decl. Resolve that these are | ||||||
10573 | // still compatible with previous declarations. | ||||||
10574 | return CheckMultiVersionAdditionalDecl( | ||||||
10575 | S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, | ||||||
10576 | OldDecl, MergeTypeWithPrevious, Previous); | ||||||
10577 | } | ||||||
10578 | |||||||
10579 | /// Perform semantic checking of a new function declaration. | ||||||
10580 | /// | ||||||
10581 | /// Performs semantic analysis of the new function declaration | ||||||
10582 | /// NewFD. This routine performs all semantic checking that does not | ||||||
10583 | /// require the actual declarator involved in the declaration, and is | ||||||
10584 | /// used both for the declaration of functions as they are parsed | ||||||
10585 | /// (called via ActOnDeclarator) and for the declaration of functions | ||||||
10586 | /// that have been instantiated via C++ template instantiation (called | ||||||
10587 | /// via InstantiateDecl). | ||||||
10588 | /// | ||||||
10589 | /// \param IsMemberSpecialization whether this new function declaration is | ||||||
10590 | /// a member specialization (that replaces any definition provided by the | ||||||
10591 | /// previous declaration). | ||||||
10592 | /// | ||||||
10593 | /// This sets NewFD->isInvalidDecl() to true if there was an error. | ||||||
10594 | /// | ||||||
10595 | /// \returns true if the function declaration is a redeclaration. | ||||||
10596 | bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, | ||||||
10597 | LookupResult &Previous, | ||||||
10598 | bool IsMemberSpecialization) { | ||||||
10599 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10600, __PRETTY_FUNCTION__)) | ||||||
10600 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10600, __PRETTY_FUNCTION__)); | ||||||
10601 | |||||||
10602 | // Determine whether the type of this function should be merged with | ||||||
10603 | // a previous visible declaration. This never happens for functions in C++, | ||||||
10604 | // and always happens in C if the previous declaration was visible. | ||||||
10605 | bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && | ||||||
10606 | !Previous.isShadowed(); | ||||||
10607 | |||||||
10608 | bool Redeclaration = false; | ||||||
10609 | NamedDecl *OldDecl = nullptr; | ||||||
10610 | bool MayNeedOverloadableChecks = false; | ||||||
10611 | |||||||
10612 | // Merge or overload the declaration with an existing declaration of | ||||||
10613 | // the same name, if appropriate. | ||||||
10614 | if (!Previous.empty()) { | ||||||
10615 | // Determine whether NewFD is an overload of PrevDecl or | ||||||
10616 | // a declaration that requires merging. If it's an overload, | ||||||
10617 | // there's no more work to do here; we'll just add the new | ||||||
10618 | // function to the scope. | ||||||
10619 | if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { | ||||||
10620 | NamedDecl *Candidate = Previous.getRepresentativeDecl(); | ||||||
10621 | if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { | ||||||
10622 | Redeclaration = true; | ||||||
10623 | OldDecl = Candidate; | ||||||
10624 | } | ||||||
10625 | } else { | ||||||
10626 | MayNeedOverloadableChecks = true; | ||||||
10627 | switch (CheckOverload(S, NewFD, Previous, OldDecl, | ||||||
10628 | /*NewIsUsingDecl*/ false)) { | ||||||
10629 | case Ovl_Match: | ||||||
10630 | Redeclaration = true; | ||||||
10631 | break; | ||||||
10632 | |||||||
10633 | case Ovl_NonFunction: | ||||||
10634 | Redeclaration = true; | ||||||
10635 | break; | ||||||
10636 | |||||||
10637 | case Ovl_Overload: | ||||||
10638 | Redeclaration = false; | ||||||
10639 | break; | ||||||
10640 | } | ||||||
10641 | } | ||||||
10642 | } | ||||||
10643 | |||||||
10644 | // Check for a previous extern "C" declaration with this name. | ||||||
10645 | if (!Redeclaration && | ||||||
10646 | checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { | ||||||
10647 | if (!Previous.empty()) { | ||||||
10648 | // This is an extern "C" declaration with the same name as a previous | ||||||
10649 | // declaration, and thus redeclares that entity... | ||||||
10650 | Redeclaration = true; | ||||||
10651 | OldDecl = Previous.getFoundDecl(); | ||||||
10652 | MergeTypeWithPrevious = false; | ||||||
10653 | |||||||
10654 | // ... except in the presence of __attribute__((overloadable)). | ||||||
10655 | if (OldDecl->hasAttr<OverloadableAttr>() || | ||||||
10656 | NewFD->hasAttr<OverloadableAttr>()) { | ||||||
10657 | if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { | ||||||
10658 | MayNeedOverloadableChecks = true; | ||||||
10659 | Redeclaration = false; | ||||||
10660 | OldDecl = nullptr; | ||||||
10661 | } | ||||||
10662 | } | ||||||
10663 | } | ||||||
10664 | } | ||||||
10665 | |||||||
10666 | if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, | ||||||
10667 | MergeTypeWithPrevious, Previous)) | ||||||
10668 | return Redeclaration; | ||||||
10669 | |||||||
10670 | // C++11 [dcl.constexpr]p8: | ||||||
10671 | // A constexpr specifier for a non-static member function that is not | ||||||
10672 | // a constructor declares that member function to be const. | ||||||
10673 | // | ||||||
10674 | // This needs to be delayed until we know whether this is an out-of-line | ||||||
10675 | // definition of a static member function. | ||||||
10676 | // | ||||||
10677 | // This rule is not present in C++1y, so we produce a backwards | ||||||
10678 | // compatibility warning whenever it happens in C++11. | ||||||
10679 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); | ||||||
10680 | if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && | ||||||
10681 | !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && | ||||||
10682 | !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { | ||||||
10683 | CXXMethodDecl *OldMD = nullptr; | ||||||
10684 | if (OldDecl) | ||||||
10685 | OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); | ||||||
10686 | if (!OldMD || !OldMD->isStatic()) { | ||||||
10687 | const FunctionProtoType *FPT = | ||||||
10688 | MD->getType()->castAs<FunctionProtoType>(); | ||||||
10689 | FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); | ||||||
10690 | EPI.TypeQuals.addConst(); | ||||||
10691 | MD->setType(Context.getFunctionType(FPT->getReturnType(), | ||||||
10692 | FPT->getParamTypes(), EPI)); | ||||||
10693 | |||||||
10694 | // Warn that we did this, if we're not performing template instantiation. | ||||||
10695 | // In that case, we'll have warned already when the template was defined. | ||||||
10696 | if (!inTemplateInstantiation()) { | ||||||
10697 | SourceLocation AddConstLoc; | ||||||
10698 | if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() | ||||||
10699 | .IgnoreParens().getAs<FunctionTypeLoc>()) | ||||||
10700 | AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); | ||||||
10701 | |||||||
10702 | Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) | ||||||
10703 | << FixItHint::CreateInsertion(AddConstLoc, " const"); | ||||||
10704 | } | ||||||
10705 | } | ||||||
10706 | } | ||||||
10707 | |||||||
10708 | if (Redeclaration) { | ||||||
10709 | // NewFD and OldDecl represent declarations that need to be | ||||||
10710 | // merged. | ||||||
10711 | if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { | ||||||
10712 | NewFD->setInvalidDecl(); | ||||||
10713 | return Redeclaration; | ||||||
10714 | } | ||||||
10715 | |||||||
10716 | Previous.clear(); | ||||||
10717 | Previous.addDecl(OldDecl); | ||||||
10718 | |||||||
10719 | if (FunctionTemplateDecl *OldTemplateDecl = | ||||||
10720 | dyn_cast<FunctionTemplateDecl>(OldDecl)) { | ||||||
10721 | auto *OldFD = OldTemplateDecl->getTemplatedDecl(); | ||||||
10722 | FunctionTemplateDecl *NewTemplateDecl | ||||||
10723 | = NewFD->getDescribedFunctionTemplate(); | ||||||
10724 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10724, __PRETTY_FUNCTION__)); | ||||||
10725 | |||||||
10726 | // The call to MergeFunctionDecl above may have created some state in | ||||||
10727 | // NewTemplateDecl that needs to be merged with OldTemplateDecl before we | ||||||
10728 | // can add it as a redeclaration. | ||||||
10729 | NewTemplateDecl->mergePrevDecl(OldTemplateDecl); | ||||||
10730 | |||||||
10731 | NewFD->setPreviousDeclaration(OldFD); | ||||||
10732 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | ||||||
10733 | if (NewFD->isCXXClassMember()) { | ||||||
10734 | NewFD->setAccess(OldTemplateDecl->getAccess()); | ||||||
10735 | NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); | ||||||
10736 | } | ||||||
10737 | |||||||
10738 | // If this is an explicit specialization of a member that is a function | ||||||
10739 | // template, mark it as a member specialization. | ||||||
10740 | if (IsMemberSpecialization && | ||||||
10741 | NewTemplateDecl->getInstantiatedFromMemberTemplate()) { | ||||||
10742 | NewTemplateDecl->setMemberSpecialization(); | ||||||
10743 | assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast <void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10743, __PRETTY_FUNCTION__)); | ||||||
10744 | // Explicit specializations of a member template do not inherit deleted | ||||||
10745 | // status from the parent member template that they are specializing. | ||||||
10746 | if (OldFD->isDeleted()) { | ||||||
10747 | // FIXME: This assert will not hold in the presence of modules. | ||||||
10748 | assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void > (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10748, __PRETTY_FUNCTION__)); | ||||||
10749 | // FIXME: We need an update record for this AST mutation. | ||||||
10750 | OldFD->setDeletedAsWritten(false); | ||||||
10751 | } | ||||||
10752 | } | ||||||
10753 | |||||||
10754 | } else { | ||||||
10755 | if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { | ||||||
10756 | auto *OldFD = cast<FunctionDecl>(OldDecl); | ||||||
10757 | // This needs to happen first so that 'inline' propagates. | ||||||
10758 | NewFD->setPreviousDeclaration(OldFD); | ||||||
10759 | adjustDeclContextForDeclaratorDecl(NewFD, OldFD); | ||||||
10760 | if (NewFD->isCXXClassMember()) | ||||||
10761 | NewFD->setAccess(OldFD->getAccess()); | ||||||
10762 | } | ||||||
10763 | } | ||||||
10764 | } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && | ||||||
10765 | !NewFD->getAttr<OverloadableAttr>()) { | ||||||
10766 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10771, __PRETTY_FUNCTION__)) | ||||||
10767 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10771, __PRETTY_FUNCTION__)) | ||||||
10768 | [](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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10771, __PRETTY_FUNCTION__)) | ||||||
10769 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10771, __PRETTY_FUNCTION__)) | ||||||
10770 | })) &&(((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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10771, __PRETTY_FUNCTION__)) | ||||||
10771 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10771, __PRETTY_FUNCTION__)); | ||||||
10772 | |||||||
10773 | auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { | ||||||
10774 | const auto *FD = dyn_cast<FunctionDecl>(ND); | ||||||
10775 | return FD && !FD->hasAttr<OverloadableAttr>(); | ||||||
10776 | }); | ||||||
10777 | |||||||
10778 | if (OtherUnmarkedIter != Previous.end()) { | ||||||
10779 | Diag(NewFD->getLocation(), | ||||||
10780 | diag::err_attribute_overloadable_multiple_unmarked_overloads); | ||||||
10781 | Diag((*OtherUnmarkedIter)->getLocation(), | ||||||
10782 | diag::note_attribute_overloadable_prev_overload) | ||||||
10783 | << false; | ||||||
10784 | |||||||
10785 | NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); | ||||||
10786 | } | ||||||
10787 | } | ||||||
10788 | |||||||
10789 | // Semantic checking for this function declaration (in isolation). | ||||||
10790 | |||||||
10791 | if (getLangOpts().CPlusPlus) { | ||||||
10792 | // C++-specific checks. | ||||||
10793 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { | ||||||
10794 | CheckConstructor(Constructor); | ||||||
10795 | } else if (CXXDestructorDecl *Destructor = | ||||||
10796 | dyn_cast<CXXDestructorDecl>(NewFD)) { | ||||||
10797 | CXXRecordDecl *Record = Destructor->getParent(); | ||||||
10798 | QualType ClassType = Context.getTypeDeclType(Record); | ||||||
10799 | |||||||
10800 | // FIXME: Shouldn't we be able to perform this check even when the class | ||||||
10801 | // type is dependent? Both gcc and edg can handle that. | ||||||
10802 | if (!ClassType->isDependentType()) { | ||||||
10803 | DeclarationName Name | ||||||
10804 | = Context.DeclarationNames.getCXXDestructorName( | ||||||
10805 | Context.getCanonicalType(ClassType)); | ||||||
10806 | if (NewFD->getDeclName() != Name) { | ||||||
10807 | Diag(NewFD->getLocation(), diag::err_destructor_name); | ||||||
10808 | NewFD->setInvalidDecl(); | ||||||
10809 | return Redeclaration; | ||||||
10810 | } | ||||||
10811 | } | ||||||
10812 | } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { | ||||||
10813 | if (auto *TD = Guide->getDescribedFunctionTemplate()) | ||||||
10814 | CheckDeductionGuideTemplate(TD); | ||||||
10815 | |||||||
10816 | // A deduction guide is not on the list of entities that can be | ||||||
10817 | // explicitly specialized. | ||||||
10818 | if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) | ||||||
10819 | Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) | ||||||
10820 | << /*explicit specialization*/ 1; | ||||||
10821 | } | ||||||
10822 | |||||||
10823 | // Find any virtual functions that this function overrides. | ||||||
10824 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { | ||||||
10825 | if (!Method->isFunctionTemplateSpecialization() && | ||||||
10826 | !Method->getDescribedFunctionTemplate() && | ||||||
10827 | Method->isCanonicalDecl()) { | ||||||
10828 | AddOverriddenMethods(Method->getParent(), Method); | ||||||
10829 | } | ||||||
10830 | if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) | ||||||
10831 | // C++2a [class.virtual]p6 | ||||||
10832 | // A virtual method shall not have a requires-clause. | ||||||
10833 | Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), | ||||||
10834 | diag::err_constrained_virtual_method); | ||||||
10835 | |||||||
10836 | if (Method->isStatic()) | ||||||
10837 | checkThisInStaticMemberFunctionType(Method); | ||||||
10838 | } | ||||||
10839 | |||||||
10840 | if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD)) | ||||||
10841 | ActOnConversionDeclarator(Conversion); | ||||||
10842 | |||||||
10843 | // Extra checking for C++ overloaded operators (C++ [over.oper]). | ||||||
10844 | if (NewFD->isOverloadedOperator() && | ||||||
10845 | CheckOverloadedOperatorDeclaration(NewFD)) { | ||||||
10846 | NewFD->setInvalidDecl(); | ||||||
10847 | return Redeclaration; | ||||||
10848 | } | ||||||
10849 | |||||||
10850 | // Extra checking for C++0x literal operators (C++0x [over.literal]). | ||||||
10851 | if (NewFD->getLiteralIdentifier() && | ||||||
10852 | CheckLiteralOperatorDeclaration(NewFD)) { | ||||||
10853 | NewFD->setInvalidDecl(); | ||||||
10854 | return Redeclaration; | ||||||
10855 | } | ||||||
10856 | |||||||
10857 | // In C++, check default arguments now that we have merged decls. Unless | ||||||
10858 | // the lexical context is the class, because in this case this is done | ||||||
10859 | // during delayed parsing anyway. | ||||||
10860 | if (!CurContext->isRecord()) | ||||||
10861 | CheckCXXDefaultArguments(NewFD); | ||||||
10862 | |||||||
10863 | // If this function declares a builtin function, check the type of this | ||||||
10864 | // declaration against the expected type for the builtin. | ||||||
10865 | if (unsigned BuiltinID = NewFD->getBuiltinID()) { | ||||||
10866 | ASTContext::GetBuiltinTypeError Error; | ||||||
10867 | LookupNecessaryTypesForBuiltin(S, BuiltinID); | ||||||
10868 | QualType T = Context.GetBuiltinType(BuiltinID, Error); | ||||||
10869 | // If the type of the builtin differs only in its exception | ||||||
10870 | // specification, that's OK. | ||||||
10871 | // FIXME: If the types do differ in this way, it would be better to | ||||||
10872 | // retain the 'noexcept' form of the type. | ||||||
10873 | if (!T.isNull() && | ||||||
10874 | !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, | ||||||
10875 | NewFD->getType())) | ||||||
10876 | // The type of this function differs from the type of the builtin, | ||||||
10877 | // so forget about the builtin entirely. | ||||||
10878 | Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); | ||||||
10879 | } | ||||||
10880 | |||||||
10881 | // If this function is declared as being extern "C", then check to see if | ||||||
10882 | // the function returns a UDT (class, struct, or union type) that is not C | ||||||
10883 | // compatible, and if it does, warn the user. | ||||||
10884 | // But, issue any diagnostic on the first declaration only. | ||||||
10885 | if (Previous.empty() && NewFD->isExternC()) { | ||||||
10886 | QualType R = NewFD->getReturnType(); | ||||||
10887 | if (R->isIncompleteType() && !R->isVoidType()) | ||||||
10888 | Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) | ||||||
10889 | << NewFD << R; | ||||||
10890 | else if (!R.isPODType(Context) && !R->isVoidType() && | ||||||
10891 | !R->isObjCObjectPointerType()) | ||||||
10892 | Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; | ||||||
10893 | } | ||||||
10894 | |||||||
10895 | // C++1z [dcl.fct]p6: | ||||||
10896 | // [...] whether the function has a non-throwing exception-specification | ||||||
10897 | // [is] part of the function type | ||||||
10898 | // | ||||||
10899 | // This results in an ABI break between C++14 and C++17 for functions whose | ||||||
10900 | // declared type includes an exception-specification in a parameter or | ||||||
10901 | // return type. (Exception specifications on the function itself are OK in | ||||||
10902 | // most cases, and exception specifications are not permitted in most other | ||||||
10903 | // contexts where they could make it into a mangling.) | ||||||
10904 | if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { | ||||||
10905 | auto HasNoexcept = [&](QualType T) -> bool { | ||||||
10906 | // Strip off declarator chunks that could be between us and a function | ||||||
10907 | // type. We don't need to look far, exception specifications are very | ||||||
10908 | // restricted prior to C++17. | ||||||
10909 | if (auto *RT = T->getAs<ReferenceType>()) | ||||||
10910 | T = RT->getPointeeType(); | ||||||
10911 | else if (T->isAnyPointerType()) | ||||||
10912 | T = T->getPointeeType(); | ||||||
10913 | else if (auto *MPT = T->getAs<MemberPointerType>()) | ||||||
10914 | T = MPT->getPointeeType(); | ||||||
10915 | if (auto *FPT = T->getAs<FunctionProtoType>()) | ||||||
10916 | if (FPT->isNothrow()) | ||||||
10917 | return true; | ||||||
10918 | return false; | ||||||
10919 | }; | ||||||
10920 | |||||||
10921 | auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); | ||||||
10922 | bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); | ||||||
10923 | for (QualType T : FPT->param_types()) | ||||||
10924 | AnyNoexcept |= HasNoexcept(T); | ||||||
10925 | if (AnyNoexcept) | ||||||
10926 | Diag(NewFD->getLocation(), | ||||||
10927 | diag::warn_cxx17_compat_exception_spec_in_signature) | ||||||
10928 | << NewFD; | ||||||
10929 | } | ||||||
10930 | |||||||
10931 | if (!Redeclaration && LangOpts.CUDA) | ||||||
10932 | checkCUDATargetOverload(NewFD, Previous); | ||||||
10933 | } | ||||||
10934 | return Redeclaration; | ||||||
10935 | } | ||||||
10936 | |||||||
10937 | void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { | ||||||
10938 | // C++11 [basic.start.main]p3: | ||||||
10939 | // A program that [...] declares main to be inline, static or | ||||||
10940 | // constexpr is ill-formed. | ||||||
10941 | // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall | ||||||
10942 | // appear in a declaration of main. | ||||||
10943 | // static main is not an error under C99, but we should warn about it. | ||||||
10944 | // We accept _Noreturn main as an extension. | ||||||
10945 | if (FD->getStorageClass() == SC_Static) | ||||||
10946 | Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus | ||||||
10947 | ? diag::err_static_main : diag::warn_static_main) | ||||||
10948 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
10949 | if (FD->isInlineSpecified()) | ||||||
10950 | Diag(DS.getInlineSpecLoc(), diag::err_inline_main) | ||||||
10951 | << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); | ||||||
10952 | if (DS.isNoreturnSpecified()) { | ||||||
10953 | SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); | ||||||
10954 | SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); | ||||||
10955 | Diag(NoreturnLoc, diag::ext_noreturn_main); | ||||||
10956 | Diag(NoreturnLoc, diag::note_main_remove_noreturn) | ||||||
10957 | << FixItHint::CreateRemoval(NoreturnRange); | ||||||
10958 | } | ||||||
10959 | if (FD->isConstexpr()) { | ||||||
10960 | Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) | ||||||
10961 | << FD->isConsteval() | ||||||
10962 | << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); | ||||||
10963 | FD->setConstexprKind(CSK_unspecified); | ||||||
10964 | } | ||||||
10965 | |||||||
10966 | if (getLangOpts().OpenCL) { | ||||||
10967 | Diag(FD->getLocation(), diag::err_opencl_no_main) | ||||||
10968 | << FD->hasAttr<OpenCLKernelAttr>(); | ||||||
10969 | FD->setInvalidDecl(); | ||||||
10970 | return; | ||||||
10971 | } | ||||||
10972 | |||||||
10973 | QualType T = FD->getType(); | ||||||
10974 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 10974, __PRETTY_FUNCTION__)); | ||||||
10975 | const FunctionType* FT = T->castAs<FunctionType>(); | ||||||
10976 | |||||||
10977 | // Set default calling convention for main() | ||||||
10978 | if (FT->getCallConv() != CC_C) { | ||||||
10979 | FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); | ||||||
10980 | FD->setType(QualType(FT, 0)); | ||||||
10981 | T = Context.getCanonicalType(FD->getType()); | ||||||
10982 | } | ||||||
10983 | |||||||
10984 | if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { | ||||||
10985 | // In C with GNU extensions we allow main() to have non-integer return | ||||||
10986 | // type, but we should warn about the extension, and we disable the | ||||||
10987 | // implicit-return-zero rule. | ||||||
10988 | |||||||
10989 | // GCC in C mode accepts qualified 'int'. | ||||||
10990 | if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) | ||||||
10991 | FD->setHasImplicitReturnZero(true); | ||||||
10992 | else { | ||||||
10993 | Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); | ||||||
10994 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | ||||||
10995 | if (RTRange.isValid()) | ||||||
10996 | Diag(RTRange.getBegin(), diag::note_main_change_return_type) | ||||||
10997 | << FixItHint::CreateReplacement(RTRange, "int"); | ||||||
10998 | } | ||||||
10999 | } else { | ||||||
11000 | // In C and C++, main magically returns 0 if you fall off the end; | ||||||
11001 | // set the flag which tells us that. | ||||||
11002 | // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. | ||||||
11003 | |||||||
11004 | // All the standards say that main() should return 'int'. | ||||||
11005 | if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) | ||||||
11006 | FD->setHasImplicitReturnZero(true); | ||||||
11007 | else { | ||||||
11008 | // Otherwise, this is just a flat-out error. | ||||||
11009 | SourceRange RTRange = FD->getReturnTypeSourceRange(); | ||||||
11010 | Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) | ||||||
11011 | << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") | ||||||
11012 | : FixItHint()); | ||||||
11013 | FD->setInvalidDecl(true); | ||||||
11014 | } | ||||||
11015 | } | ||||||
11016 | |||||||
11017 | // Treat protoless main() as nullary. | ||||||
11018 | if (isa<FunctionNoProtoType>(FT)) return; | ||||||
11019 | |||||||
11020 | const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); | ||||||
11021 | unsigned nparams = FTP->getNumParams(); | ||||||
11022 | assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11022, __PRETTY_FUNCTION__)); | ||||||
11023 | |||||||
11024 | bool HasExtraParameters = (nparams > 3); | ||||||
11025 | |||||||
11026 | if (FTP->isVariadic()) { | ||||||
11027 | Diag(FD->getLocation(), diag::ext_variadic_main); | ||||||
11028 | // FIXME: if we had information about the location of the ellipsis, we | ||||||
11029 | // could add a FixIt hint to remove it as a parameter. | ||||||
11030 | } | ||||||
11031 | |||||||
11032 | // Darwin passes an undocumented fourth argument of type char**. If | ||||||
11033 | // other platforms start sprouting these, the logic below will start | ||||||
11034 | // getting shifty. | ||||||
11035 | if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) | ||||||
11036 | HasExtraParameters = false; | ||||||
11037 | |||||||
11038 | if (HasExtraParameters) { | ||||||
11039 | Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; | ||||||
11040 | FD->setInvalidDecl(true); | ||||||
11041 | nparams = 3; | ||||||
11042 | } | ||||||
11043 | |||||||
11044 | // FIXME: a lot of the following diagnostics would be improved | ||||||
11045 | // if we had some location information about types. | ||||||
11046 | |||||||
11047 | QualType CharPP = | ||||||
11048 | Context.getPointerType(Context.getPointerType(Context.CharTy)); | ||||||
11049 | QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; | ||||||
11050 | |||||||
11051 | for (unsigned i = 0; i < nparams; ++i) { | ||||||
11052 | QualType AT = FTP->getParamType(i); | ||||||
11053 | |||||||
11054 | bool mismatch = true; | ||||||
11055 | |||||||
11056 | if (Context.hasSameUnqualifiedType(AT, Expected[i])) | ||||||
11057 | mismatch = false; | ||||||
11058 | else if (Expected[i] == CharPP) { | ||||||
11059 | // As an extension, the following forms are okay: | ||||||
11060 | // char const ** | ||||||
11061 | // char const * const * | ||||||
11062 | // char * const * | ||||||
11063 | |||||||
11064 | QualifierCollector qs; | ||||||
11065 | const PointerType* PT; | ||||||
11066 | if ((PT = qs.strip(AT)->getAs<PointerType>()) && | ||||||
11067 | (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && | ||||||
11068 | Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), | ||||||
11069 | Context.CharTy)) { | ||||||
11070 | qs.removeConst(); | ||||||
11071 | mismatch = !qs.empty(); | ||||||
11072 | } | ||||||
11073 | } | ||||||
11074 | |||||||
11075 | if (mismatch) { | ||||||
11076 | Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; | ||||||
11077 | // TODO: suggest replacing given type with expected type | ||||||
11078 | FD->setInvalidDecl(true); | ||||||
11079 | } | ||||||
11080 | } | ||||||
11081 | |||||||
11082 | if (nparams == 1 && !FD->isInvalidDecl()) { | ||||||
11083 | Diag(FD->getLocation(), diag::warn_main_one_arg); | ||||||
11084 | } | ||||||
11085 | |||||||
11086 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | ||||||
11087 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | ||||||
11088 | FD->setInvalidDecl(); | ||||||
11089 | } | ||||||
11090 | } | ||||||
11091 | |||||||
11092 | void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { | ||||||
11093 | QualType T = FD->getType(); | ||||||
11094 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11094, __PRETTY_FUNCTION__)); | ||||||
11095 | const FunctionType *FT = T->castAs<FunctionType>(); | ||||||
11096 | |||||||
11097 | // Set an implicit return of 'zero' if the function can return some integral, | ||||||
11098 | // enumeration, pointer or nullptr type. | ||||||
11099 | if (FT->getReturnType()->isIntegralOrEnumerationType() || | ||||||
11100 | FT->getReturnType()->isAnyPointerType() || | ||||||
11101 | FT->getReturnType()->isNullPtrType()) | ||||||
11102 | // DllMain is exempt because a return value of zero means it failed. | ||||||
11103 | if (FD->getName() != "DllMain") | ||||||
11104 | FD->setHasImplicitReturnZero(true); | ||||||
11105 | |||||||
11106 | if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { | ||||||
11107 | Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; | ||||||
11108 | FD->setInvalidDecl(); | ||||||
11109 | } | ||||||
11110 | } | ||||||
11111 | |||||||
11112 | bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { | ||||||
11113 | // FIXME: Need strict checking. In C89, we need to check for | ||||||
11114 | // any assignment, increment, decrement, function-calls, or | ||||||
11115 | // commas outside of a sizeof. In C99, it's the same list, | ||||||
11116 | // except that the aforementioned are allowed in unevaluated | ||||||
11117 | // expressions. Everything else falls under the | ||||||
11118 | // "may accept other forms of constant expressions" exception. | ||||||
11119 | // | ||||||
11120 | // Regular C++ code will not end up here (exceptions: language extensions, | ||||||
11121 | // OpenCL C++ etc), so the constant expression rules there don't matter. | ||||||
11122 | if (Init->isValueDependent()) { | ||||||
11123 | assert(Init->containsErrors() &&((Init->containsErrors() && "Dependent code should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11124, __PRETTY_FUNCTION__)) | ||||||
11124 | "Dependent code should only occur in error-recovery path.")((Init->containsErrors() && "Dependent code should only occur in error-recovery path." ) ? static_cast<void> (0) : __assert_fail ("Init->containsErrors() && \"Dependent code should only occur in error-recovery path.\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11124, __PRETTY_FUNCTION__)); | ||||||
11125 | return true; | ||||||
11126 | } | ||||||
11127 | const Expr *Culprit; | ||||||
11128 | if (Init->isConstantInitializer(Context, false, &Culprit)) | ||||||
11129 | return false; | ||||||
11130 | Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) | ||||||
11131 | << Culprit->getSourceRange(); | ||||||
11132 | return true; | ||||||
11133 | } | ||||||
11134 | |||||||
11135 | namespace { | ||||||
11136 | // Visits an initialization expression to see if OrigDecl is evaluated in | ||||||
11137 | // its own initialization and throws a warning if it does. | ||||||
11138 | class SelfReferenceChecker | ||||||
11139 | : public EvaluatedExprVisitor<SelfReferenceChecker> { | ||||||
11140 | Sema &S; | ||||||
11141 | Decl *OrigDecl; | ||||||
11142 | bool isRecordType; | ||||||
11143 | bool isPODType; | ||||||
11144 | bool isReferenceType; | ||||||
11145 | |||||||
11146 | bool isInitList; | ||||||
11147 | llvm::SmallVector<unsigned, 4> InitFieldIndex; | ||||||
11148 | |||||||
11149 | public: | ||||||
11150 | typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; | ||||||
11151 | |||||||
11152 | SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), | ||||||
11153 | S(S), OrigDecl(OrigDecl) { | ||||||
11154 | isPODType = false; | ||||||
11155 | isRecordType = false; | ||||||
11156 | isReferenceType = false; | ||||||
11157 | isInitList = false; | ||||||
11158 | if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { | ||||||
11159 | isPODType = VD->getType().isPODType(S.Context); | ||||||
11160 | isRecordType = VD->getType()->isRecordType(); | ||||||
11161 | isReferenceType = VD->getType()->isReferenceType(); | ||||||
11162 | } | ||||||
11163 | } | ||||||
11164 | |||||||
11165 | // For most expressions, just call the visitor. For initializer lists, | ||||||
11166 | // track the index of the field being initialized since fields are | ||||||
11167 | // initialized in order allowing use of previously initialized fields. | ||||||
11168 | void CheckExpr(Expr *E) { | ||||||
11169 | InitListExpr *InitList = dyn_cast<InitListExpr>(E); | ||||||
11170 | if (!InitList) { | ||||||
11171 | Visit(E); | ||||||
11172 | return; | ||||||
11173 | } | ||||||
11174 | |||||||
11175 | // Track and increment the index here. | ||||||
11176 | isInitList = true; | ||||||
11177 | InitFieldIndex.push_back(0); | ||||||
11178 | for (auto Child : InitList->children()) { | ||||||
11179 | CheckExpr(cast<Expr>(Child)); | ||||||
11180 | ++InitFieldIndex.back(); | ||||||
11181 | } | ||||||
11182 | InitFieldIndex.pop_back(); | ||||||
11183 | } | ||||||
11184 | |||||||
11185 | // Returns true if MemberExpr is checked and no further checking is needed. | ||||||
11186 | // Returns false if additional checking is required. | ||||||
11187 | bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { | ||||||
11188 | llvm::SmallVector<FieldDecl*, 4> Fields; | ||||||
11189 | Expr *Base = E; | ||||||
11190 | bool ReferenceField = false; | ||||||
11191 | |||||||
11192 | // Get the field members used. | ||||||
11193 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
11194 | FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); | ||||||
11195 | if (!FD) | ||||||
11196 | return false; | ||||||
11197 | Fields.push_back(FD); | ||||||
11198 | if (FD->getType()->isReferenceType()) | ||||||
11199 | ReferenceField = true; | ||||||
11200 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
11201 | } | ||||||
11202 | |||||||
11203 | // Keep checking only if the base Decl is the same. | ||||||
11204 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); | ||||||
11205 | if (!DRE || DRE->getDecl() != OrigDecl) | ||||||
11206 | return false; | ||||||
11207 | |||||||
11208 | // A reference field can be bound to an unininitialized field. | ||||||
11209 | if (CheckReference && !ReferenceField) | ||||||
11210 | return true; | ||||||
11211 | |||||||
11212 | // Convert FieldDecls to their index number. | ||||||
11213 | llvm::SmallVector<unsigned, 4> UsedFieldIndex; | ||||||
11214 | for (const FieldDecl *I : llvm::reverse(Fields)) | ||||||
11215 | UsedFieldIndex.push_back(I->getFieldIndex()); | ||||||
11216 | |||||||
11217 | // See if a warning is needed by checking the first difference in index | ||||||
11218 | // numbers. If field being used has index less than the field being | ||||||
11219 | // initialized, then the use is safe. | ||||||
11220 | for (auto UsedIter = UsedFieldIndex.begin(), | ||||||
11221 | UsedEnd = UsedFieldIndex.end(), | ||||||
11222 | OrigIter = InitFieldIndex.begin(), | ||||||
11223 | OrigEnd = InitFieldIndex.end(); | ||||||
11224 | UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { | ||||||
11225 | if (*UsedIter < *OrigIter) | ||||||
11226 | return true; | ||||||
11227 | if (*UsedIter > *OrigIter) | ||||||
11228 | break; | ||||||
11229 | } | ||||||
11230 | |||||||
11231 | // TODO: Add a different warning which will print the field names. | ||||||
11232 | HandleDeclRefExpr(DRE); | ||||||
11233 | return true; | ||||||
11234 | } | ||||||
11235 | |||||||
11236 | // For most expressions, the cast is directly above the DeclRefExpr. | ||||||
11237 | // For conditional operators, the cast can be outside the conditional | ||||||
11238 | // operator if both expressions are DeclRefExpr's. | ||||||
11239 | void HandleValue(Expr *E) { | ||||||
11240 | E = E->IgnoreParens(); | ||||||
11241 | if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { | ||||||
11242 | HandleDeclRefExpr(DRE); | ||||||
11243 | return; | ||||||
11244 | } | ||||||
11245 | |||||||
11246 | if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { | ||||||
11247 | Visit(CO->getCond()); | ||||||
11248 | HandleValue(CO->getTrueExpr()); | ||||||
11249 | HandleValue(CO->getFalseExpr()); | ||||||
11250 | return; | ||||||
11251 | } | ||||||
11252 | |||||||
11253 | if (BinaryConditionalOperator *BCO = | ||||||
11254 | dyn_cast<BinaryConditionalOperator>(E)) { | ||||||
11255 | Visit(BCO->getCond()); | ||||||
11256 | HandleValue(BCO->getFalseExpr()); | ||||||
11257 | return; | ||||||
11258 | } | ||||||
11259 | |||||||
11260 | if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { | ||||||
11261 | HandleValue(OVE->getSourceExpr()); | ||||||
11262 | return; | ||||||
11263 | } | ||||||
11264 | |||||||
11265 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { | ||||||
11266 | if (BO->getOpcode() == BO_Comma) { | ||||||
11267 | Visit(BO->getLHS()); | ||||||
11268 | HandleValue(BO->getRHS()); | ||||||
11269 | return; | ||||||
11270 | } | ||||||
11271 | } | ||||||
11272 | |||||||
11273 | if (isa<MemberExpr>(E)) { | ||||||
11274 | if (isInitList) { | ||||||
11275 | if (CheckInitListMemberExpr(cast<MemberExpr>(E), | ||||||
11276 | false /*CheckReference*/)) | ||||||
11277 | return; | ||||||
11278 | } | ||||||
11279 | |||||||
11280 | Expr *Base = E->IgnoreParenImpCasts(); | ||||||
11281 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
11282 | // Check for static member variables and don't warn on them. | ||||||
11283 | if (!isa<FieldDecl>(ME->getMemberDecl())) | ||||||
11284 | return; | ||||||
11285 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
11286 | } | ||||||
11287 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) | ||||||
11288 | HandleDeclRefExpr(DRE); | ||||||
11289 | return; | ||||||
11290 | } | ||||||
11291 | |||||||
11292 | Visit(E); | ||||||
11293 | } | ||||||
11294 | |||||||
11295 | // Reference types not handled in HandleValue are handled here since all | ||||||
11296 | // uses of references are bad, not just r-value uses. | ||||||
11297 | void VisitDeclRefExpr(DeclRefExpr *E) { | ||||||
11298 | if (isReferenceType) | ||||||
11299 | HandleDeclRefExpr(E); | ||||||
11300 | } | ||||||
11301 | |||||||
11302 | void VisitImplicitCastExpr(ImplicitCastExpr *E) { | ||||||
11303 | if (E->getCastKind() == CK_LValueToRValue) { | ||||||
11304 | HandleValue(E->getSubExpr()); | ||||||
11305 | return; | ||||||
11306 | } | ||||||
11307 | |||||||
11308 | Inherited::VisitImplicitCastExpr(E); | ||||||
11309 | } | ||||||
11310 | |||||||
11311 | void VisitMemberExpr(MemberExpr *E) { | ||||||
11312 | if (isInitList) { | ||||||
11313 | if (CheckInitListMemberExpr(E, true /*CheckReference*/)) | ||||||
11314 | return; | ||||||
11315 | } | ||||||
11316 | |||||||
11317 | // Don't warn on arrays since they can be treated as pointers. | ||||||
11318 | if (E->getType()->canDecayToPointerType()) return; | ||||||
11319 | |||||||
11320 | // Warn when a non-static method call is followed by non-static member | ||||||
11321 | // field accesses, which is followed by a DeclRefExpr. | ||||||
11322 | CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); | ||||||
11323 | bool Warn = (MD && !MD->isStatic()); | ||||||
11324 | Expr *Base = E->getBase()->IgnoreParenImpCasts(); | ||||||
11325 | while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { | ||||||
11326 | if (!isa<FieldDecl>(ME->getMemberDecl())) | ||||||
11327 | Warn = false; | ||||||
11328 | Base = ME->getBase()->IgnoreParenImpCasts(); | ||||||
11329 | } | ||||||
11330 | |||||||
11331 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { | ||||||
11332 | if (Warn) | ||||||
11333 | HandleDeclRefExpr(DRE); | ||||||
11334 | return; | ||||||
11335 | } | ||||||
11336 | |||||||
11337 | // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. | ||||||
11338 | // Visit that expression. | ||||||
11339 | Visit(Base); | ||||||
11340 | } | ||||||
11341 | |||||||
11342 | void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { | ||||||
11343 | Expr *Callee = E->getCallee(); | ||||||
11344 | |||||||
11345 | if (isa<UnresolvedLookupExpr>(Callee)) | ||||||
11346 | return Inherited::VisitCXXOperatorCallExpr(E); | ||||||
11347 | |||||||
11348 | Visit(Callee); | ||||||
11349 | for (auto Arg: E->arguments()) | ||||||
11350 | HandleValue(Arg->IgnoreParenImpCasts()); | ||||||
11351 | } | ||||||
11352 | |||||||
11353 | void VisitUnaryOperator(UnaryOperator *E) { | ||||||
11354 | // For POD record types, addresses of its own members are well-defined. | ||||||
11355 | if (E->getOpcode() == UO_AddrOf && isRecordType && | ||||||
11356 | isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { | ||||||
11357 | if (!isPODType) | ||||||
11358 | HandleValue(E->getSubExpr()); | ||||||
11359 | return; | ||||||
11360 | } | ||||||
11361 | |||||||
11362 | if (E->isIncrementDecrementOp()) { | ||||||
11363 | HandleValue(E->getSubExpr()); | ||||||
11364 | return; | ||||||
11365 | } | ||||||
11366 | |||||||
11367 | Inherited::VisitUnaryOperator(E); | ||||||
11368 | } | ||||||
11369 | |||||||
11370 | void VisitObjCMessageExpr(ObjCMessageExpr *E) {} | ||||||
11371 | |||||||
11372 | void VisitCXXConstructExpr(CXXConstructExpr *E) { | ||||||
11373 | if (E->getConstructor()->isCopyConstructor()) { | ||||||
11374 | Expr *ArgExpr = E->getArg(0); | ||||||
11375 | if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) | ||||||
11376 | if (ILE->getNumInits() == 1) | ||||||
11377 | ArgExpr = ILE->getInit(0); | ||||||
11378 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) | ||||||
11379 | if (ICE->getCastKind() == CK_NoOp) | ||||||
11380 | ArgExpr = ICE->getSubExpr(); | ||||||
11381 | HandleValue(ArgExpr); | ||||||
11382 | return; | ||||||
11383 | } | ||||||
11384 | Inherited::VisitCXXConstructExpr(E); | ||||||
11385 | } | ||||||
11386 | |||||||
11387 | void VisitCallExpr(CallExpr *E) { | ||||||
11388 | // Treat std::move as a use. | ||||||
11389 | if (E->isCallToStdMove()) { | ||||||
11390 | HandleValue(E->getArg(0)); | ||||||
11391 | return; | ||||||
11392 | } | ||||||
11393 | |||||||
11394 | Inherited::VisitCallExpr(E); | ||||||
11395 | } | ||||||
11396 | |||||||
11397 | void VisitBinaryOperator(BinaryOperator *E) { | ||||||
11398 | if (E->isCompoundAssignmentOp()) { | ||||||
11399 | HandleValue(E->getLHS()); | ||||||
11400 | Visit(E->getRHS()); | ||||||
11401 | return; | ||||||
11402 | } | ||||||
11403 | |||||||
11404 | Inherited::VisitBinaryOperator(E); | ||||||
11405 | } | ||||||
11406 | |||||||
11407 | // A custom visitor for BinaryConditionalOperator is needed because the | ||||||
11408 | // regular visitor would check the condition and true expression separately | ||||||
11409 | // but both point to the same place giving duplicate diagnostics. | ||||||
11410 | void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { | ||||||
11411 | Visit(E->getCond()); | ||||||
11412 | Visit(E->getFalseExpr()); | ||||||
11413 | } | ||||||
11414 | |||||||
11415 | void HandleDeclRefExpr(DeclRefExpr *DRE) { | ||||||
11416 | Decl* ReferenceDecl = DRE->getDecl(); | ||||||
11417 | if (OrigDecl != ReferenceDecl) return; | ||||||
11418 | unsigned diag; | ||||||
11419 | if (isReferenceType) { | ||||||
11420 | diag = diag::warn_uninit_self_reference_in_reference_init; | ||||||
11421 | } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { | ||||||
11422 | diag = diag::warn_static_self_reference_in_init; | ||||||
11423 | } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || | ||||||
11424 | isa<NamespaceDecl>(OrigDecl->getDeclContext()) || | ||||||
11425 | DRE->getDecl()->getType()->isRecordType()) { | ||||||
11426 | diag = diag::warn_uninit_self_reference_in_init; | ||||||
11427 | } else { | ||||||
11428 | // Local variables will be handled by the CFG analysis. | ||||||
11429 | return; | ||||||
11430 | } | ||||||
11431 | |||||||
11432 | S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, | ||||||
11433 | S.PDiag(diag) | ||||||
11434 | << DRE->getDecl() << OrigDecl->getLocation() | ||||||
11435 | << DRE->getSourceRange()); | ||||||
11436 | } | ||||||
11437 | }; | ||||||
11438 | |||||||
11439 | /// CheckSelfReference - Warns if OrigDecl is used in expression E. | ||||||
11440 | static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, | ||||||
11441 | bool DirectInit) { | ||||||
11442 | // Parameters arguments are occassionially constructed with itself, | ||||||
11443 | // for instance, in recursive functions. Skip them. | ||||||
11444 | if (isa<ParmVarDecl>(OrigDecl)) | ||||||
11445 | return; | ||||||
11446 | |||||||
11447 | E = E->IgnoreParens(); | ||||||
11448 | |||||||
11449 | // Skip checking T a = a where T is not a record or reference type. | ||||||
11450 | // Doing so is a way to silence uninitialized warnings. | ||||||
11451 | if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) | ||||||
11452 | if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) | ||||||
11453 | if (ICE->getCastKind() == CK_LValueToRValue) | ||||||
11454 | if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) | ||||||
11455 | if (DRE->getDecl() == OrigDecl) | ||||||
11456 | return; | ||||||
11457 | |||||||
11458 | SelfReferenceChecker(S, OrigDecl).CheckExpr(E); | ||||||
11459 | } | ||||||
11460 | } // end anonymous namespace | ||||||
11461 | |||||||
11462 | namespace { | ||||||
11463 | // Simple wrapper to add the name of a variable or (if no variable is | ||||||
11464 | // available) a DeclarationName into a diagnostic. | ||||||
11465 | struct VarDeclOrName { | ||||||
11466 | VarDecl *VDecl; | ||||||
11467 | DeclarationName Name; | ||||||
11468 | |||||||
11469 | friend const Sema::SemaDiagnosticBuilder & | ||||||
11470 | operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { | ||||||
11471 | return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; | ||||||
11472 | } | ||||||
11473 | }; | ||||||
11474 | } // end anonymous namespace | ||||||
11475 | |||||||
11476 | QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, | ||||||
11477 | DeclarationName Name, QualType Type, | ||||||
11478 | TypeSourceInfo *TSI, | ||||||
11479 | SourceRange Range, bool DirectInit, | ||||||
11480 | Expr *Init) { | ||||||
11481 | bool IsInitCapture = !VDecl; | ||||||
11482 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11483, __PRETTY_FUNCTION__)) | ||||||
11483 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11483, __PRETTY_FUNCTION__)); | ||||||
11484 | |||||||
11485 | VarDeclOrName VN{VDecl, Name}; | ||||||
11486 | |||||||
11487 | DeducedType *Deduced = Type->getContainedDeducedType(); | ||||||
11488 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11488, __PRETTY_FUNCTION__)); | ||||||
11489 | |||||||
11490 | // C++11 [dcl.spec.auto]p3 | ||||||
11491 | if (!Init) { | ||||||
11492 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11492, __PRETTY_FUNCTION__)); | ||||||
11493 | |||||||
11494 | // Except for class argument deduction, and then for an initializing | ||||||
11495 | // declaration only, i.e. no static at class scope or extern. | ||||||
11496 | if (!isa<DeducedTemplateSpecializationType>(Deduced) || | ||||||
11497 | VDecl->hasExternalStorage() || | ||||||
11498 | VDecl->isStaticDataMember()) { | ||||||
11499 | Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) | ||||||
11500 | << VDecl->getDeclName() << Type; | ||||||
11501 | return QualType(); | ||||||
11502 | } | ||||||
11503 | } | ||||||
11504 | |||||||
11505 | ArrayRef<Expr*> DeduceInits; | ||||||
11506 | if (Init) | ||||||
11507 | DeduceInits = Init; | ||||||
11508 | |||||||
11509 | if (DirectInit) { | ||||||
11510 | if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) | ||||||
11511 | DeduceInits = PL->exprs(); | ||||||
11512 | } | ||||||
11513 | |||||||
11514 | if (isa<DeducedTemplateSpecializationType>(Deduced)) { | ||||||
11515 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11515, __PRETTY_FUNCTION__)); | ||||||
11516 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | ||||||
11517 | InitializationKind Kind = InitializationKind::CreateForInit( | ||||||
11518 | VDecl->getLocation(), DirectInit, Init); | ||||||
11519 | // FIXME: Initialization should not be taking a mutable list of inits. | ||||||
11520 | SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); | ||||||
11521 | return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, | ||||||
11522 | InitsCopy); | ||||||
11523 | } | ||||||
11524 | |||||||
11525 | if (DirectInit) { | ||||||
11526 | if (auto *IL = dyn_cast<InitListExpr>(Init)) | ||||||
11527 | DeduceInits = IL->inits(); | ||||||
11528 | } | ||||||
11529 | |||||||
11530 | // Deduction only works if we have exactly one source expression. | ||||||
11531 | if (DeduceInits.empty()) { | ||||||
11532 | // It isn't possible to write this directly, but it is possible to | ||||||
11533 | // end up in this situation with "auto x(some_pack...);" | ||||||
11534 | Diag(Init->getBeginLoc(), IsInitCapture | ||||||
11535 | ? diag::err_init_capture_no_expression | ||||||
11536 | : diag::err_auto_var_init_no_expression) | ||||||
11537 | << VN << Type << Range; | ||||||
11538 | return QualType(); | ||||||
11539 | } | ||||||
11540 | |||||||
11541 | if (DeduceInits.size() > 1) { | ||||||
11542 | Diag(DeduceInits[1]->getBeginLoc(), | ||||||
11543 | IsInitCapture ? diag::err_init_capture_multiple_expressions | ||||||
11544 | : diag::err_auto_var_init_multiple_expressions) | ||||||
11545 | << VN << Type << Range; | ||||||
11546 | return QualType(); | ||||||
11547 | } | ||||||
11548 | |||||||
11549 | Expr *DeduceInit = DeduceInits[0]; | ||||||
11550 | if (DirectInit && isa<InitListExpr>(DeduceInit)) { | ||||||
11551 | Diag(Init->getBeginLoc(), IsInitCapture | ||||||
11552 | ? diag::err_init_capture_paren_braces | ||||||
11553 | : diag::err_auto_var_init_paren_braces) | ||||||
11554 | << isa<InitListExpr>(Init) << VN << Type << Range; | ||||||
11555 | return QualType(); | ||||||
11556 | } | ||||||
11557 | |||||||
11558 | // Expressions default to 'id' when we're in a debugger. | ||||||
11559 | bool DefaultedAnyToId = false; | ||||||
11560 | if (getLangOpts().DebuggerCastResultToId && | ||||||
11561 | Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { | ||||||
11562 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | ||||||
11563 | if (Result.isInvalid()) { | ||||||
11564 | return QualType(); | ||||||
11565 | } | ||||||
11566 | Init = Result.get(); | ||||||
11567 | DefaultedAnyToId = true; | ||||||
11568 | } | ||||||
11569 | |||||||
11570 | // C++ [dcl.decomp]p1: | ||||||
11571 | // If the assignment-expression [...] has array type A and no ref-qualifier | ||||||
11572 | // is present, e has type cv A | ||||||
11573 | if (VDecl && isa<DecompositionDecl>(VDecl) && | ||||||
11574 | Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && | ||||||
11575 | DeduceInit->getType()->isConstantArrayType()) | ||||||
11576 | return Context.getQualifiedType(DeduceInit->getType(), | ||||||
11577 | Type.getQualifiers()); | ||||||
11578 | |||||||
11579 | QualType DeducedType; | ||||||
11580 | if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { | ||||||
11581 | if (!IsInitCapture) | ||||||
11582 | DiagnoseAutoDeductionFailure(VDecl, DeduceInit); | ||||||
11583 | else if (isa<InitListExpr>(Init)) | ||||||
11584 | Diag(Range.getBegin(), | ||||||
11585 | diag::err_init_capture_deduction_failure_from_init_list) | ||||||
11586 | << VN | ||||||
11587 | << (DeduceInit->getType().isNull() ? TSI->getType() | ||||||
11588 | : DeduceInit->getType()) | ||||||
11589 | << DeduceInit->getSourceRange(); | ||||||
11590 | else | ||||||
11591 | Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) | ||||||
11592 | << VN << TSI->getType() | ||||||
11593 | << (DeduceInit->getType().isNull() ? TSI->getType() | ||||||
11594 | : DeduceInit->getType()) | ||||||
11595 | << DeduceInit->getSourceRange(); | ||||||
11596 | } | ||||||
11597 | |||||||
11598 | // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using | ||||||
11599 | // 'id' instead of a specific object type prevents most of our usual | ||||||
11600 | // checks. | ||||||
11601 | // We only want to warn outside of template instantiations, though: | ||||||
11602 | // inside a template, the 'id' could have come from a parameter. | ||||||
11603 | if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && | ||||||
11604 | !DeducedType.isNull() && DeducedType->isObjCIdType()) { | ||||||
11605 | SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); | ||||||
11606 | Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; | ||||||
11607 | } | ||||||
11608 | |||||||
11609 | return DeducedType; | ||||||
11610 | } | ||||||
11611 | |||||||
11612 | bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, | ||||||
11613 | Expr *Init) { | ||||||
11614 | assert(!Init || !Init->containsErrors())((!Init || !Init->containsErrors()) ? static_cast<void> (0) : __assert_fail ("!Init || !Init->containsErrors()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11614, __PRETTY_FUNCTION__)); | ||||||
11615 | QualType DeducedType = deduceVarTypeFromInitializer( | ||||||
11616 | VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), | ||||||
11617 | VDecl->getSourceRange(), DirectInit, Init); | ||||||
11618 | if (DeducedType.isNull()) { | ||||||
11619 | VDecl->setInvalidDecl(); | ||||||
11620 | return true; | ||||||
11621 | } | ||||||
11622 | |||||||
11623 | VDecl->setType(DeducedType); | ||||||
11624 | assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11624, __PRETTY_FUNCTION__)); | ||||||
11625 | |||||||
11626 | // In ARC, infer lifetime. | ||||||
11627 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) | ||||||
11628 | VDecl->setInvalidDecl(); | ||||||
11629 | |||||||
11630 | if (getLangOpts().OpenCL) | ||||||
11631 | deduceOpenCLAddressSpace(VDecl); | ||||||
11632 | |||||||
11633 | // If this is a redeclaration, check that the type we just deduced matches | ||||||
11634 | // the previously declared type. | ||||||
11635 | if (VarDecl *Old = VDecl->getPreviousDecl()) { | ||||||
11636 | // We never need to merge the type, because we cannot form an incomplete | ||||||
11637 | // array of auto, nor deduce such a type. | ||||||
11638 | MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); | ||||||
11639 | } | ||||||
11640 | |||||||
11641 | // Check the deduced type is valid for a variable declaration. | ||||||
11642 | CheckVariableDeclarationType(VDecl); | ||||||
11643 | return VDecl->isInvalidDecl(); | ||||||
11644 | } | ||||||
11645 | |||||||
11646 | void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, | ||||||
11647 | SourceLocation Loc) { | ||||||
11648 | if (auto *EWC = dyn_cast<ExprWithCleanups>(Init)) | ||||||
11649 | Init = EWC->getSubExpr(); | ||||||
11650 | |||||||
11651 | if (auto *CE = dyn_cast<ConstantExpr>(Init)) | ||||||
11652 | Init = CE->getSubExpr(); | ||||||
11653 | |||||||
11654 | QualType InitType = Init->getType(); | ||||||
11655 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11657, __PRETTY_FUNCTION__)) | ||||||
11656 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11657, __PRETTY_FUNCTION__)) | ||||||
11657 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11657, __PRETTY_FUNCTION__)); | ||||||
11658 | if (auto *ILE = dyn_cast<InitListExpr>(Init)) { | ||||||
11659 | for (auto I : ILE->inits()) { | ||||||
11660 | if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && | ||||||
11661 | !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11662 | continue; | ||||||
11663 | SourceLocation SL = I->getExprLoc(); | ||||||
11664 | checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); | ||||||
11665 | } | ||||||
11666 | return; | ||||||
11667 | } | ||||||
11668 | |||||||
11669 | if (isa<ImplicitValueInitExpr>(Init)) { | ||||||
11670 | if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
11671 | checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, | ||||||
11672 | NTCUK_Init); | ||||||
11673 | } else { | ||||||
11674 | // Assume all other explicit initializers involving copying some existing | ||||||
11675 | // object. | ||||||
11676 | // TODO: ignore any explicit initializers where we can guarantee | ||||||
11677 | // copy-elision. | ||||||
11678 | if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11679 | checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); | ||||||
11680 | } | ||||||
11681 | } | ||||||
11682 | |||||||
11683 | namespace { | ||||||
11684 | |||||||
11685 | bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { | ||||||
11686 | // Ignore unavailable fields. A field can be marked as unavailable explicitly | ||||||
11687 | // in the source code or implicitly by the compiler if it is in a union | ||||||
11688 | // defined in a system header and has non-trivial ObjC ownership | ||||||
11689 | // qualifications. We don't want those fields to participate in determining | ||||||
11690 | // whether the containing union is non-trivial. | ||||||
11691 | return FD->hasAttr<UnavailableAttr>(); | ||||||
11692 | } | ||||||
11693 | |||||||
11694 | struct DiagNonTrivalCUnionDefaultInitializeVisitor | ||||||
11695 | : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | ||||||
11696 | void> { | ||||||
11697 | using Super = | ||||||
11698 | DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, | ||||||
11699 | void>; | ||||||
11700 | |||||||
11701 | DiagNonTrivalCUnionDefaultInitializeVisitor( | ||||||
11702 | QualType OrigTy, SourceLocation OrigLoc, | ||||||
11703 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | ||||||
11704 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11705 | |||||||
11706 | void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, | ||||||
11707 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11708 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11709 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11710 | InNonTrivialUnion); | ||||||
11711 | return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); | ||||||
11712 | } | ||||||
11713 | |||||||
11714 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11715 | bool InNonTrivialUnion) { | ||||||
11716 | if (InNonTrivialUnion) | ||||||
11717 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11718 | << 1 << 0 << QT << FD->getName(); | ||||||
11719 | } | ||||||
11720 | |||||||
11721 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11722 | if (InNonTrivialUnion) | ||||||
11723 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11724 | << 1 << 0 << QT << FD->getName(); | ||||||
11725 | } | ||||||
11726 | |||||||
11727 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11728 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11729 | if (RD->isUnion()) { | ||||||
11730 | if (OrigLoc.isValid()) { | ||||||
11731 | bool IsUnion = false; | ||||||
11732 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11733 | IsUnion = OrigRD->isUnion(); | ||||||
11734 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11735 | << 0 << OrigTy << IsUnion << UseContext; | ||||||
11736 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11737 | OrigLoc = SourceLocation(); | ||||||
11738 | } | ||||||
11739 | InNonTrivialUnion = true; | ||||||
11740 | } | ||||||
11741 | |||||||
11742 | if (InNonTrivialUnion) | ||||||
11743 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11744 | << 0 << 0 << QT.getUnqualifiedType() << ""; | ||||||
11745 | |||||||
11746 | for (const FieldDecl *FD : RD->fields()) | ||||||
11747 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11748 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11749 | } | ||||||
11750 | |||||||
11751 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11752 | |||||||
11753 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11754 | // non-trivial C union. | ||||||
11755 | QualType OrigTy; | ||||||
11756 | SourceLocation OrigLoc; | ||||||
11757 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11758 | Sema &S; | ||||||
11759 | }; | ||||||
11760 | |||||||
11761 | struct DiagNonTrivalCUnionDestructedTypeVisitor | ||||||
11762 | : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { | ||||||
11763 | using Super = | ||||||
11764 | DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; | ||||||
11765 | |||||||
11766 | DiagNonTrivalCUnionDestructedTypeVisitor( | ||||||
11767 | QualType OrigTy, SourceLocation OrigLoc, | ||||||
11768 | Sema::NonTrivialCUnionContext UseContext, Sema &S) | ||||||
11769 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11770 | |||||||
11771 | void visitWithKind(QualType::DestructionKind DK, QualType QT, | ||||||
11772 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11773 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11774 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11775 | InNonTrivialUnion); | ||||||
11776 | return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); | ||||||
11777 | } | ||||||
11778 | |||||||
11779 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11780 | bool InNonTrivialUnion) { | ||||||
11781 | if (InNonTrivialUnion) | ||||||
11782 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11783 | << 1 << 1 << QT << FD->getName(); | ||||||
11784 | } | ||||||
11785 | |||||||
11786 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11787 | if (InNonTrivialUnion) | ||||||
11788 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11789 | << 1 << 1 << QT << FD->getName(); | ||||||
11790 | } | ||||||
11791 | |||||||
11792 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11793 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11794 | if (RD->isUnion()) { | ||||||
11795 | if (OrigLoc.isValid()) { | ||||||
11796 | bool IsUnion = false; | ||||||
11797 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11798 | IsUnion = OrigRD->isUnion(); | ||||||
11799 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11800 | << 1 << OrigTy << IsUnion << UseContext; | ||||||
11801 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11802 | OrigLoc = SourceLocation(); | ||||||
11803 | } | ||||||
11804 | InNonTrivialUnion = true; | ||||||
11805 | } | ||||||
11806 | |||||||
11807 | if (InNonTrivialUnion) | ||||||
11808 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11809 | << 0 << 1 << QT.getUnqualifiedType() << ""; | ||||||
11810 | |||||||
11811 | for (const FieldDecl *FD : RD->fields()) | ||||||
11812 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11813 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11814 | } | ||||||
11815 | |||||||
11816 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11817 | void visitCXXDestructor(QualType QT, const FieldDecl *FD, | ||||||
11818 | bool InNonTrivialUnion) {} | ||||||
11819 | |||||||
11820 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11821 | // non-trivial C union. | ||||||
11822 | QualType OrigTy; | ||||||
11823 | SourceLocation OrigLoc; | ||||||
11824 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11825 | Sema &S; | ||||||
11826 | }; | ||||||
11827 | |||||||
11828 | struct DiagNonTrivalCUnionCopyVisitor | ||||||
11829 | : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { | ||||||
11830 | using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; | ||||||
11831 | |||||||
11832 | DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, | ||||||
11833 | Sema::NonTrivialCUnionContext UseContext, | ||||||
11834 | Sema &S) | ||||||
11835 | : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} | ||||||
11836 | |||||||
11837 | void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, | ||||||
11838 | const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11839 | if (const auto *AT = S.Context.getAsArrayType(QT)) | ||||||
11840 | return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, | ||||||
11841 | InNonTrivialUnion); | ||||||
11842 | return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); | ||||||
11843 | } | ||||||
11844 | |||||||
11845 | void visitARCStrong(QualType QT, const FieldDecl *FD, | ||||||
11846 | bool InNonTrivialUnion) { | ||||||
11847 | if (InNonTrivialUnion) | ||||||
11848 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11849 | << 1 << 2 << QT << FD->getName(); | ||||||
11850 | } | ||||||
11851 | |||||||
11852 | void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11853 | if (InNonTrivialUnion) | ||||||
11854 | S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11855 | << 1 << 2 << QT << FD->getName(); | ||||||
11856 | } | ||||||
11857 | |||||||
11858 | void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { | ||||||
11859 | const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); | ||||||
11860 | if (RD->isUnion()) { | ||||||
11861 | if (OrigLoc.isValid()) { | ||||||
11862 | bool IsUnion = false; | ||||||
11863 | if (auto *OrigRD = OrigTy->getAsRecordDecl()) | ||||||
11864 | IsUnion = OrigRD->isUnion(); | ||||||
11865 | S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) | ||||||
11866 | << 2 << OrigTy << IsUnion << UseContext; | ||||||
11867 | // Reset OrigLoc so that this diagnostic is emitted only once. | ||||||
11868 | OrigLoc = SourceLocation(); | ||||||
11869 | } | ||||||
11870 | InNonTrivialUnion = true; | ||||||
11871 | } | ||||||
11872 | |||||||
11873 | if (InNonTrivialUnion) | ||||||
11874 | S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) | ||||||
11875 | << 0 << 2 << QT.getUnqualifiedType() << ""; | ||||||
11876 | |||||||
11877 | for (const FieldDecl *FD : RD->fields()) | ||||||
11878 | if (!shouldIgnoreForRecordTriviality(FD)) | ||||||
11879 | asDerived().visit(FD->getType(), FD, InNonTrivialUnion); | ||||||
11880 | } | ||||||
11881 | |||||||
11882 | void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, | ||||||
11883 | const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11884 | void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} | ||||||
11885 | void visitVolatileTrivial(QualType QT, const FieldDecl *FD, | ||||||
11886 | bool InNonTrivialUnion) {} | ||||||
11887 | |||||||
11888 | // The non-trivial C union type or the struct/union type that contains a | ||||||
11889 | // non-trivial C union. | ||||||
11890 | QualType OrigTy; | ||||||
11891 | SourceLocation OrigLoc; | ||||||
11892 | Sema::NonTrivialCUnionContext UseContext; | ||||||
11893 | Sema &S; | ||||||
11894 | }; | ||||||
11895 | |||||||
11896 | } // namespace | ||||||
11897 | |||||||
11898 | void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, | ||||||
11899 | NonTrivialCUnionContext UseContext, | ||||||
11900 | unsigned NonTrivialKind) { | ||||||
11901 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11904, __PRETTY_FUNCTION__)) | ||||||
11902 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11904, __PRETTY_FUNCTION__)) | ||||||
11903 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11904, __PRETTY_FUNCTION__)) | ||||||
11904 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11904, __PRETTY_FUNCTION__)); | ||||||
11905 | |||||||
11906 | if ((NonTrivialKind & NTCUK_Init) && | ||||||
11907 | QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
11908 | DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) | ||||||
11909 | .visit(QT, nullptr, false); | ||||||
11910 | if ((NonTrivialKind & NTCUK_Destruct) && | ||||||
11911 | QT.hasNonTrivialToPrimitiveDestructCUnion()) | ||||||
11912 | DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) | ||||||
11913 | .visit(QT, nullptr, false); | ||||||
11914 | if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
11915 | DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) | ||||||
11916 | .visit(QT, nullptr, false); | ||||||
11917 | } | ||||||
11918 | |||||||
11919 | /// AddInitializerToDecl - Adds the initializer Init to the | ||||||
11920 | /// declaration dcl. If DirectInit is true, this is C++ direct | ||||||
11921 | /// initialization rather than copy initialization. | ||||||
11922 | void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { | ||||||
11923 | // If there is no declaration, there was an error parsing it. Just ignore | ||||||
11924 | // the initializer. | ||||||
11925 | if (!RealDecl || RealDecl->isInvalidDecl()) { | ||||||
11926 | CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); | ||||||
11927 | return; | ||||||
11928 | } | ||||||
11929 | |||||||
11930 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { | ||||||
11931 | // Pure-specifiers are handled in ActOnPureSpecifier. | ||||||
11932 | Diag(Method->getLocation(), diag::err_member_function_initialization) | ||||||
11933 | << Method->getDeclName() << Init->getSourceRange(); | ||||||
11934 | Method->setInvalidDecl(); | ||||||
11935 | return; | ||||||
11936 | } | ||||||
11937 | |||||||
11938 | VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); | ||||||
11939 | if (!VDecl) { | ||||||
11940 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 11940, __PRETTY_FUNCTION__)); | ||||||
11941 | Diag(RealDecl->getLocation(), diag::err_illegal_initializer); | ||||||
11942 | RealDecl->setInvalidDecl(); | ||||||
11943 | return; | ||||||
11944 | } | ||||||
11945 | |||||||
11946 | // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. | ||||||
11947 | if (VDecl->getType()->isUndeducedType()) { | ||||||
11948 | // Attempt typo correction early so that the type of the init expression can | ||||||
11949 | // be deduced based on the chosen correction if the original init contains a | ||||||
11950 | // TypoExpr. | ||||||
11951 | ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); | ||||||
11952 | if (!Res.isUsable()) { | ||||||
11953 | // There are unresolved typos in Init, just drop them. | ||||||
11954 | // FIXME: improve the recovery strategy to preserve the Init. | ||||||
11955 | RealDecl->setInvalidDecl(); | ||||||
11956 | return; | ||||||
11957 | } | ||||||
11958 | if (Res.get()->containsErrors()) { | ||||||
11959 | // Invalidate the decl as we don't know the type for recovery-expr yet. | ||||||
11960 | RealDecl->setInvalidDecl(); | ||||||
11961 | VDecl->setInit(Res.get()); | ||||||
11962 | return; | ||||||
11963 | } | ||||||
11964 | Init = Res.get(); | ||||||
11965 | |||||||
11966 | if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) | ||||||
11967 | return; | ||||||
11968 | } | ||||||
11969 | |||||||
11970 | // dllimport cannot be used on variable definitions. | ||||||
11971 | if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { | ||||||
11972 | Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); | ||||||
11973 | VDecl->setInvalidDecl(); | ||||||
11974 | return; | ||||||
11975 | } | ||||||
11976 | |||||||
11977 | if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { | ||||||
11978 | // C99 6.7.8p5. C++ has no such restriction, but that is a defect. | ||||||
11979 | Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); | ||||||
11980 | VDecl->setInvalidDecl(); | ||||||
11981 | return; | ||||||
11982 | } | ||||||
11983 | |||||||
11984 | if (!VDecl->getType()->isDependentType()) { | ||||||
11985 | // A definition must end up with a complete type, which means it must be | ||||||
11986 | // complete with the restriction that an array type might be completed by | ||||||
11987 | // the initializer; note that later code assumes this restriction. | ||||||
11988 | QualType BaseDeclType = VDecl->getType(); | ||||||
11989 | if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) | ||||||
11990 | BaseDeclType = Array->getElementType(); | ||||||
11991 | if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, | ||||||
11992 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
11993 | RealDecl->setInvalidDecl(); | ||||||
11994 | return; | ||||||
11995 | } | ||||||
11996 | |||||||
11997 | // The variable can not have an abstract class type. | ||||||
11998 | if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), | ||||||
11999 | diag::err_abstract_type_in_decl, | ||||||
12000 | AbstractVariableType)) | ||||||
12001 | VDecl->setInvalidDecl(); | ||||||
12002 | } | ||||||
12003 | |||||||
12004 | // If adding the initializer will turn this declaration into a definition, | ||||||
12005 | // and we already have a definition for this variable, diagnose or otherwise | ||||||
12006 | // handle the situation. | ||||||
12007 | VarDecl *Def; | ||||||
12008 | if ((Def = VDecl->getDefinition()) && Def != VDecl && | ||||||
12009 | (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && | ||||||
12010 | !VDecl->isThisDeclarationADemotedDefinition() && | ||||||
12011 | checkVarDeclRedefinition(Def, VDecl)) | ||||||
12012 | return; | ||||||
12013 | |||||||
12014 | if (getLangOpts().CPlusPlus) { | ||||||
12015 | // C++ [class.static.data]p4 | ||||||
12016 | // If a static data member is of const integral or const | ||||||
12017 | // enumeration type, its declaration in the class definition can | ||||||
12018 | // specify a constant-initializer which shall be an integral | ||||||
12019 | // constant expression (5.19). In that case, the member can appear | ||||||
12020 | // in integral constant expressions. The member shall still be | ||||||
12021 | // defined in a namespace scope if it is used in the program and the | ||||||
12022 | // namespace scope definition shall not contain an initializer. | ||||||
12023 | // | ||||||
12024 | // We already performed a redefinition check above, but for static | ||||||
12025 | // data members we also need to check whether there was an in-class | ||||||
12026 | // declaration with an initializer. | ||||||
12027 | if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { | ||||||
12028 | Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) | ||||||
12029 | << VDecl->getDeclName(); | ||||||
12030 | Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), | ||||||
12031 | diag::note_previous_initializer) | ||||||
12032 | << 0; | ||||||
12033 | return; | ||||||
12034 | } | ||||||
12035 | |||||||
12036 | if (VDecl->hasLocalStorage()) | ||||||
12037 | setFunctionHasBranchProtectedScope(); | ||||||
12038 | |||||||
12039 | if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { | ||||||
12040 | VDecl->setInvalidDecl(); | ||||||
12041 | return; | ||||||
12042 | } | ||||||
12043 | } | ||||||
12044 | |||||||
12045 | // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside | ||||||
12046 | // a kernel function cannot be initialized." | ||||||
12047 | if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { | ||||||
12048 | Diag(VDecl->getLocation(), diag::err_local_cant_init); | ||||||
12049 | VDecl->setInvalidDecl(); | ||||||
12050 | return; | ||||||
12051 | } | ||||||
12052 | |||||||
12053 | // The LoaderUninitialized attribute acts as a definition (of undef). | ||||||
12054 | if (VDecl->hasAttr<LoaderUninitializedAttr>()) { | ||||||
12055 | Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init); | ||||||
12056 | VDecl->setInvalidDecl(); | ||||||
12057 | return; | ||||||
12058 | } | ||||||
12059 | |||||||
12060 | // Get the decls type and save a reference for later, since | ||||||
12061 | // CheckInitializerTypes may change it. | ||||||
12062 | QualType DclT = VDecl->getType(), SavT = DclT; | ||||||
12063 | |||||||
12064 | // Expressions default to 'id' when we're in a debugger | ||||||
12065 | // and we are assigning it to a variable of Objective-C pointer type. | ||||||
12066 | if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && | ||||||
12067 | Init->getType() == Context.UnknownAnyTy) { | ||||||
12068 | ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); | ||||||
12069 | if (Result.isInvalid()) { | ||||||
12070 | VDecl->setInvalidDecl(); | ||||||
12071 | return; | ||||||
12072 | } | ||||||
12073 | Init = Result.get(); | ||||||
12074 | } | ||||||
12075 | |||||||
12076 | // Perform the initialization. | ||||||
12077 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); | ||||||
12078 | if (!VDecl->isInvalidDecl()) { | ||||||
12079 | InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); | ||||||
12080 | InitializationKind Kind = InitializationKind::CreateForInit( | ||||||
12081 | VDecl->getLocation(), DirectInit, Init); | ||||||
12082 | |||||||
12083 | MultiExprArg Args = Init; | ||||||
12084 | if (CXXDirectInit) | ||||||
12085 | Args = MultiExprArg(CXXDirectInit->getExprs(), | ||||||
12086 | CXXDirectInit->getNumExprs()); | ||||||
12087 | |||||||
12088 | // Try to correct any TypoExprs in the initialization arguments. | ||||||
12089 | for (size_t Idx = 0; Idx < Args.size(); ++Idx) { | ||||||
12090 | ExprResult Res = CorrectDelayedTyposInExpr( | ||||||
12091 | Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true, | ||||||
12092 | [this, Entity, Kind](Expr *E) { | ||||||
12093 | InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); | ||||||
12094 | return Init.Failed() ? ExprError() : E; | ||||||
12095 | }); | ||||||
12096 | if (Res.isInvalid()) { | ||||||
12097 | VDecl->setInvalidDecl(); | ||||||
12098 | } else if (Res.get() != Args[Idx]) { | ||||||
12099 | Args[Idx] = Res.get(); | ||||||
12100 | } | ||||||
12101 | } | ||||||
12102 | if (VDecl->isInvalidDecl()) | ||||||
12103 | return; | ||||||
12104 | |||||||
12105 | InitializationSequence InitSeq(*this, Entity, Kind, Args, | ||||||
12106 | /*TopLevelOfInitList=*/false, | ||||||
12107 | /*TreatUnavailableAsInvalid=*/false); | ||||||
12108 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); | ||||||
12109 | if (Result.isInvalid()) { | ||||||
12110 | // If the provied initializer fails to initialize the var decl, | ||||||
12111 | // we attach a recovery expr for better recovery. | ||||||
12112 | auto RecoveryExpr = | ||||||
12113 | CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args); | ||||||
12114 | if (RecoveryExpr.get()) | ||||||
12115 | VDecl->setInit(RecoveryExpr.get()); | ||||||
12116 | return; | ||||||
12117 | } | ||||||
12118 | |||||||
12119 | Init = Result.getAs<Expr>(); | ||||||
12120 | } | ||||||
12121 | |||||||
12122 | // Check for self-references within variable initializers. | ||||||
12123 | // Variables declared within a function/method body (except for references) | ||||||
12124 | // are handled by a dataflow analysis. | ||||||
12125 | // This is undefined behavior in C++, but valid in C. | ||||||
12126 | if (getLangOpts().CPlusPlus) { | ||||||
12127 | if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || | ||||||
12128 | VDecl->getType()->isReferenceType()) { | ||||||
12129 | CheckSelfReference(*this, RealDecl, Init, DirectInit); | ||||||
12130 | } | ||||||
12131 | } | ||||||
12132 | |||||||
12133 | // If the type changed, it means we had an incomplete type that was | ||||||
12134 | // completed by the initializer. For example: | ||||||
12135 | // int ary[] = { 1, 3, 5 }; | ||||||
12136 | // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. | ||||||
12137 | if (!VDecl->isInvalidDecl() && (DclT != SavT)) | ||||||
12138 | VDecl->setType(DclT); | ||||||
12139 | |||||||
12140 | if (!VDecl->isInvalidDecl()) { | ||||||
12141 | checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); | ||||||
12142 | |||||||
12143 | if (VDecl->hasAttr<BlocksAttr>()) | ||||||
12144 | checkRetainCycles(VDecl, Init); | ||||||
12145 | |||||||
12146 | // It is safe to assign a weak reference into a strong variable. | ||||||
12147 | // Although this code can still have problems: | ||||||
12148 | // id x = self.weakProp; | ||||||
12149 | // id y = self.weakProp; | ||||||
12150 | // we do not warn to warn spuriously when 'x' and 'y' are on separate | ||||||
12151 | // paths through the function. This should be revisited if | ||||||
12152 | // -Wrepeated-use-of-weak is made flow-sensitive. | ||||||
12153 | if (FunctionScopeInfo *FSI = getCurFunction()) | ||||||
12154 | if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || | ||||||
12155 | VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && | ||||||
12156 | !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, | ||||||
12157 | Init->getBeginLoc())) | ||||||
12158 | FSI->markSafeWeakUse(Init); | ||||||
12159 | } | ||||||
12160 | |||||||
12161 | // The initialization is usually a full-expression. | ||||||
12162 | // | ||||||
12163 | // FIXME: If this is a braced initialization of an aggregate, it is not | ||||||
12164 | // an expression, and each individual field initializer is a separate | ||||||
12165 | // full-expression. For instance, in: | ||||||
12166 | // | ||||||
12167 | // struct Temp { ~Temp(); }; | ||||||
12168 | // struct S { S(Temp); }; | ||||||
12169 | // struct T { S a, b; } t = { Temp(), Temp() } | ||||||
12170 | // | ||||||
12171 | // we should destroy the first Temp before constructing the second. | ||||||
12172 | ExprResult Result = | ||||||
12173 | ActOnFinishFullExpr(Init, VDecl->getLocation(), | ||||||
12174 | /*DiscardedValue*/ false, VDecl->isConstexpr()); | ||||||
12175 | if (Result.isInvalid()) { | ||||||
12176 | VDecl->setInvalidDecl(); | ||||||
12177 | return; | ||||||
12178 | } | ||||||
12179 | Init = Result.get(); | ||||||
12180 | |||||||
12181 | // Attach the initializer to the decl. | ||||||
12182 | VDecl->setInit(Init); | ||||||
12183 | |||||||
12184 | if (VDecl->isLocalVarDecl()) { | ||||||
12185 | // Don't check the initializer if the declaration is malformed. | ||||||
12186 | if (VDecl->isInvalidDecl()) { | ||||||
12187 | // do nothing | ||||||
12188 | |||||||
12189 | // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. | ||||||
12190 | // This is true even in C++ for OpenCL. | ||||||
12191 | } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { | ||||||
12192 | CheckForConstantInitializer(Init, DclT); | ||||||
12193 | |||||||
12194 | // Otherwise, C++ does not restrict the initializer. | ||||||
12195 | } else if (getLangOpts().CPlusPlus) { | ||||||
12196 | // do nothing | ||||||
12197 | |||||||
12198 | // C99 6.7.8p4: All the expressions in an initializer for an object that has | ||||||
12199 | // static storage duration shall be constant expressions or string literals. | ||||||
12200 | } else if (VDecl->getStorageClass() == SC_Static) { | ||||||
12201 | CheckForConstantInitializer(Init, DclT); | ||||||
12202 | |||||||
12203 | // C89 is stricter than C99 for aggregate initializers. | ||||||
12204 | // C89 6.5.7p3: All the expressions [...] in an initializer list | ||||||
12205 | // for an object that has aggregate or union type shall be | ||||||
12206 | // constant expressions. | ||||||
12207 | } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && | ||||||
12208 | isa<InitListExpr>(Init)) { | ||||||
12209 | const Expr *Culprit; | ||||||
12210 | if (!Init->isConstantInitializer(Context, false, &Culprit)) { | ||||||
12211 | Diag(Culprit->getExprLoc(), | ||||||
12212 | diag::ext_aggregate_init_not_constant) | ||||||
12213 | << Culprit->getSourceRange(); | ||||||
12214 | } | ||||||
12215 | } | ||||||
12216 | |||||||
12217 | if (auto *E = dyn_cast<ExprWithCleanups>(Init)) | ||||||
12218 | if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) | ||||||
12219 | if (VDecl->hasLocalStorage()) | ||||||
12220 | BE->getBlockDecl()->setCanAvoidCopyToHeap(); | ||||||
12221 | } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && | ||||||
12222 | VDecl->getLexicalDeclContext()->isRecord()) { | ||||||
12223 | // This is an in-class initialization for a static data member, e.g., | ||||||
12224 | // | ||||||
12225 | // struct S { | ||||||
12226 | // static const int value = 17; | ||||||
12227 | // }; | ||||||
12228 | |||||||
12229 | // C++ [class.mem]p4: | ||||||
12230 | // A member-declarator can contain a constant-initializer only | ||||||
12231 | // if it declares a static member (9.4) of const integral or | ||||||
12232 | // const enumeration type, see 9.4.2. | ||||||
12233 | // | ||||||
12234 | // C++11 [class.static.data]p3: | ||||||
12235 | // If a non-volatile non-inline const static data member is of integral | ||||||
12236 | // or enumeration type, its declaration in the class definition can | ||||||
12237 | // specify a brace-or-equal-initializer in which every initializer-clause | ||||||
12238 | // that is an assignment-expression is a constant expression. A static | ||||||
12239 | // data member of literal type can be declared in the class definition | ||||||
12240 | // with the constexpr specifier; if so, its declaration shall specify a | ||||||
12241 | // brace-or-equal-initializer in which every initializer-clause that is | ||||||
12242 | // an assignment-expression is a constant expression. | ||||||
12243 | |||||||
12244 | // Do nothing on dependent types. | ||||||
12245 | if (DclT->isDependentType()) { | ||||||
12246 | |||||||
12247 | // Allow any 'static constexpr' members, whether or not they are of literal | ||||||
12248 | // type. We separately check that every constexpr variable is of literal | ||||||
12249 | // type. | ||||||
12250 | } else if (VDecl->isConstexpr()) { | ||||||
12251 | |||||||
12252 | // Require constness. | ||||||
12253 | } else if (!DclT.isConstQualified()) { | ||||||
12254 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) | ||||||
12255 | << Init->getSourceRange(); | ||||||
12256 | VDecl->setInvalidDecl(); | ||||||
12257 | |||||||
12258 | // We allow integer constant expressions in all cases. | ||||||
12259 | } else if (DclT->isIntegralOrEnumerationType()) { | ||||||
12260 | // Check whether the expression is a constant expression. | ||||||
12261 | SourceLocation Loc; | ||||||
12262 | if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) | ||||||
12263 | // In C++11, a non-constexpr const static data member with an | ||||||
12264 | // in-class initializer cannot be volatile. | ||||||
12265 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); | ||||||
12266 | else if (Init->isValueDependent()) | ||||||
12267 | ; // Nothing to check. | ||||||
12268 | else if (Init->isIntegerConstantExpr(Context, &Loc)) | ||||||
12269 | ; // Ok, it's an ICE! | ||||||
12270 | else if (Init->getType()->isScopedEnumeralType() && | ||||||
12271 | Init->isCXX11ConstantExpr(Context)) | ||||||
12272 | ; // Ok, it is a scoped-enum constant expression. | ||||||
12273 | else if (Init->isEvaluatable(Context)) { | ||||||
12274 | // If we can constant fold the initializer through heroics, accept it, | ||||||
12275 | // but report this as a use of an extension for -pedantic. | ||||||
12276 | Diag(Loc, diag::ext_in_class_initializer_non_constant) | ||||||
12277 | << Init->getSourceRange(); | ||||||
12278 | } else { | ||||||
12279 | // Otherwise, this is some crazy unknown case. Report the issue at the | ||||||
12280 | // location provided by the isIntegerConstantExpr failed check. | ||||||
12281 | Diag(Loc, diag::err_in_class_initializer_non_constant) | ||||||
12282 | << Init->getSourceRange(); | ||||||
12283 | VDecl->setInvalidDecl(); | ||||||
12284 | } | ||||||
12285 | |||||||
12286 | // We allow foldable floating-point constants as an extension. | ||||||
12287 | } else if (DclT->isFloatingType()) { // also permits complex, which is ok | ||||||
12288 | // In C++98, this is a GNU extension. In C++11, it is not, but we support | ||||||
12289 | // it anyway and provide a fixit to add the 'constexpr'. | ||||||
12290 | if (getLangOpts().CPlusPlus11) { | ||||||
12291 | Diag(VDecl->getLocation(), | ||||||
12292 | diag::ext_in_class_initializer_float_type_cxx11) | ||||||
12293 | << DclT << Init->getSourceRange(); | ||||||
12294 | Diag(VDecl->getBeginLoc(), | ||||||
12295 | diag::note_in_class_initializer_float_type_cxx11) | ||||||
12296 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | ||||||
12297 | } else { | ||||||
12298 | Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) | ||||||
12299 | << DclT << Init->getSourceRange(); | ||||||
12300 | |||||||
12301 | if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { | ||||||
12302 | Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) | ||||||
12303 | << Init->getSourceRange(); | ||||||
12304 | VDecl->setInvalidDecl(); | ||||||
12305 | } | ||||||
12306 | } | ||||||
12307 | |||||||
12308 | // Suggest adding 'constexpr' in C++11 for literal types. | ||||||
12309 | } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { | ||||||
12310 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) | ||||||
12311 | << DclT << Init->getSourceRange() | ||||||
12312 | << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); | ||||||
12313 | VDecl->setConstexpr(true); | ||||||
12314 | |||||||
12315 | } else { | ||||||
12316 | Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) | ||||||
12317 | << DclT << Init->getSourceRange(); | ||||||
12318 | VDecl->setInvalidDecl(); | ||||||
12319 | } | ||||||
12320 | } else if (VDecl->isFileVarDecl()) { | ||||||
12321 | // In C, extern is typically used to avoid tentative definitions when | ||||||
12322 | // declaring variables in headers, but adding an intializer makes it a | ||||||
12323 | // definition. This is somewhat confusing, so GCC and Clang both warn on it. | ||||||
12324 | // In C++, extern is often used to give implictly static const variables | ||||||
12325 | // external linkage, so don't warn in that case. If selectany is present, | ||||||
12326 | // this might be header code intended for C and C++ inclusion, so apply the | ||||||
12327 | // C++ rules. | ||||||
12328 | if (VDecl->getStorageClass() == SC_Extern && | ||||||
12329 | ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || | ||||||
12330 | !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && | ||||||
12331 | !(getLangOpts().CPlusPlus && VDecl->isExternC()) && | ||||||
12332 | !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) | ||||||
12333 | Diag(VDecl->getLocation(), diag::warn_extern_init); | ||||||
12334 | |||||||
12335 | // In Microsoft C++ mode, a const variable defined in namespace scope has | ||||||
12336 | // external linkage by default if the variable is declared with | ||||||
12337 | // __declspec(dllexport). | ||||||
12338 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && | ||||||
12339 | getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && | ||||||
12340 | VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) | ||||||
12341 | VDecl->setStorageClass(SC_Extern); | ||||||
12342 | |||||||
12343 | // C99 6.7.8p4. All file scoped initializers need to be constant. | ||||||
12344 | if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) | ||||||
12345 | CheckForConstantInitializer(Init, DclT); | ||||||
12346 | } | ||||||
12347 | |||||||
12348 | QualType InitType = Init->getType(); | ||||||
12349 | if (!InitType.isNull() && | ||||||
12350 | (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||||
12351 | InitType.hasNonTrivialToPrimitiveCopyCUnion())) | ||||||
12352 | checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); | ||||||
12353 | |||||||
12354 | // We will represent direct-initialization similarly to copy-initialization: | ||||||
12355 | // int x(1); -as-> int x = 1; | ||||||
12356 | // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); | ||||||
12357 | // | ||||||
12358 | // Clients that want to distinguish between the two forms, can check for | ||||||
12359 | // direct initializer using VarDecl::getInitStyle(). | ||||||
12360 | // A major benefit is that clients that don't particularly care about which | ||||||
12361 | // exactly form was it (like the CodeGen) can handle both cases without | ||||||
12362 | // special case code. | ||||||
12363 | |||||||
12364 | // C++ 8.5p11: | ||||||
12365 | // The form of initialization (using parentheses or '=') is generally | ||||||
12366 | // insignificant, but does matter when the entity being initialized has a | ||||||
12367 | // class type. | ||||||
12368 | if (CXXDirectInit) { | ||||||
12369 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 12369, __PRETTY_FUNCTION__)); | ||||||
12370 | VDecl->setInitStyle(VarDecl::CallInit); | ||||||
12371 | } else if (DirectInit) { | ||||||
12372 | // This must be list-initialization. No other way is direct-initialization. | ||||||
12373 | VDecl->setInitStyle(VarDecl::ListInit); | ||||||
12374 | } | ||||||
12375 | |||||||
12376 | if (LangOpts.OpenMP && VDecl->isFileVarDecl()) | ||||||
12377 | DeclsToCheckForDeferredDiags.push_back(VDecl); | ||||||
12378 | CheckCompleteVariableDeclaration(VDecl); | ||||||
12379 | } | ||||||
12380 | |||||||
12381 | /// ActOnInitializerError - Given that there was an error parsing an | ||||||
12382 | /// initializer for the given declaration, try to return to some form | ||||||
12383 | /// of sanity. | ||||||
12384 | void Sema::ActOnInitializerError(Decl *D) { | ||||||
12385 | // Our main concern here is re-establishing invariants like "a | ||||||
12386 | // variable's type is either dependent or complete". | ||||||
12387 | if (!D || D->isInvalidDecl()) return; | ||||||
12388 | |||||||
12389 | VarDecl *VD = dyn_cast<VarDecl>(D); | ||||||
12390 | if (!VD) return; | ||||||
12391 | |||||||
12392 | // Bindings are not usable if we can't make sense of the initializer. | ||||||
12393 | if (auto *DD = dyn_cast<DecompositionDecl>(D)) | ||||||
12394 | for (auto *BD : DD->bindings()) | ||||||
12395 | BD->setInvalidDecl(); | ||||||
12396 | |||||||
12397 | // Auto types are meaningless if we can't make sense of the initializer. | ||||||
12398 | if (VD->getType()->isUndeducedType()) { | ||||||
12399 | D->setInvalidDecl(); | ||||||
12400 | return; | ||||||
12401 | } | ||||||
12402 | |||||||
12403 | QualType Ty = VD->getType(); | ||||||
12404 | if (Ty->isDependentType()) return; | ||||||
12405 | |||||||
12406 | // Require a complete type. | ||||||
12407 | if (RequireCompleteType(VD->getLocation(), | ||||||
12408 | Context.getBaseElementType(Ty), | ||||||
12409 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
12410 | VD->setInvalidDecl(); | ||||||
12411 | return; | ||||||
12412 | } | ||||||
12413 | |||||||
12414 | // Require a non-abstract type. | ||||||
12415 | if (RequireNonAbstractType(VD->getLocation(), Ty, | ||||||
12416 | diag::err_abstract_type_in_decl, | ||||||
12417 | AbstractVariableType)) { | ||||||
12418 | VD->setInvalidDecl(); | ||||||
12419 | return; | ||||||
12420 | } | ||||||
12421 | |||||||
12422 | // Don't bother complaining about constructors or destructors, | ||||||
12423 | // though. | ||||||
12424 | } | ||||||
12425 | |||||||
12426 | void Sema::ActOnUninitializedDecl(Decl *RealDecl) { | ||||||
12427 | // If there is no declaration, there was an error parsing it. Just ignore it. | ||||||
12428 | if (!RealDecl) | ||||||
12429 | return; | ||||||
12430 | |||||||
12431 | if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { | ||||||
12432 | QualType Type = Var->getType(); | ||||||
12433 | |||||||
12434 | // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. | ||||||
12435 | if (isa<DecompositionDecl>(RealDecl)) { | ||||||
12436 | Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; | ||||||
12437 | Var->setInvalidDecl(); | ||||||
12438 | return; | ||||||
12439 | } | ||||||
12440 | |||||||
12441 | if (Type->isUndeducedType() && | ||||||
12442 | DeduceVariableDeclarationType(Var, false, nullptr)) | ||||||
12443 | return; | ||||||
12444 | |||||||
12445 | // C++11 [class.static.data]p3: A static data member can be declared with | ||||||
12446 | // the constexpr specifier; if so, its declaration shall specify | ||||||
12447 | // a brace-or-equal-initializer. | ||||||
12448 | // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to | ||||||
12449 | // the definition of a variable [...] or the declaration of a static data | ||||||
12450 | // member. | ||||||
12451 | if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && | ||||||
12452 | !Var->isThisDeclarationADemotedDefinition()) { | ||||||
12453 | if (Var->isStaticDataMember()) { | ||||||
12454 | // C++1z removes the relevant rule; the in-class declaration is always | ||||||
12455 | // a definition there. | ||||||
12456 | if (!getLangOpts().CPlusPlus17 && | ||||||
12457 | !Context.getTargetInfo().getCXXABI().isMicrosoft()) { | ||||||
12458 | Diag(Var->getLocation(), | ||||||
12459 | diag::err_constexpr_static_mem_var_requires_init) | ||||||
12460 | << Var; | ||||||
12461 | Var->setInvalidDecl(); | ||||||
12462 | return; | ||||||
12463 | } | ||||||
12464 | } else { | ||||||
12465 | Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); | ||||||
12466 | Var->setInvalidDecl(); | ||||||
12467 | return; | ||||||
12468 | } | ||||||
12469 | } | ||||||
12470 | |||||||
12471 | // OpenCL v1.1 s6.5.3: variables declared in the constant address space must | ||||||
12472 | // be initialized. | ||||||
12473 | if (!Var->isInvalidDecl() && | ||||||
12474 | Var->getType().getAddressSpace() == LangAS::opencl_constant && | ||||||
12475 | Var->getStorageClass() != SC_Extern && !Var->getInit()) { | ||||||
12476 | Diag(Var->getLocation(), diag::err_opencl_constant_no_init); | ||||||
12477 | Var->setInvalidDecl(); | ||||||
12478 | return; | ||||||
12479 | } | ||||||
12480 | |||||||
12481 | if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) { | ||||||
12482 | if (Var->getStorageClass() == SC_Extern) { | ||||||
12483 | Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl) | ||||||
12484 | << Var; | ||||||
12485 | Var->setInvalidDecl(); | ||||||
12486 | return; | ||||||
12487 | } | ||||||
12488 | if (RequireCompleteType(Var->getLocation(), Var->getType(), | ||||||
12489 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
12490 | Var->setInvalidDecl(); | ||||||
12491 | return; | ||||||
12492 | } | ||||||
12493 | if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) { | ||||||
12494 | if (!RD->hasTrivialDefaultConstructor()) { | ||||||
12495 | Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor); | ||||||
12496 | Var->setInvalidDecl(); | ||||||
12497 | return; | ||||||
12498 | } | ||||||
12499 | } | ||||||
12500 | } | ||||||
12501 | |||||||
12502 | VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); | ||||||
12503 | if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && | ||||||
12504 | Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) | ||||||
12505 | checkNonTrivialCUnion(Var->getType(), Var->getLocation(), | ||||||
12506 | NTCUC_DefaultInitializedObject, NTCUK_Init); | ||||||
12507 | |||||||
12508 | |||||||
12509 | switch (DefKind) { | ||||||
12510 | case VarDecl::Definition: | ||||||
12511 | if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) | ||||||
12512 | break; | ||||||
12513 | |||||||
12514 | // We have an out-of-line definition of a static data member | ||||||
12515 | // that has an in-class initializer, so we type-check this like | ||||||
12516 | // a declaration. | ||||||
12517 | // | ||||||
12518 | LLVM_FALLTHROUGH[[gnu::fallthrough]]; | ||||||
12519 | |||||||
12520 | case VarDecl::DeclarationOnly: | ||||||
12521 | // It's only a declaration. | ||||||
12522 | |||||||
12523 | // Block scope. C99 6.7p7: If an identifier for an object is | ||||||
12524 | // declared with no linkage (C99 6.2.2p6), the type for the | ||||||
12525 | // object shall be complete. | ||||||
12526 | if (!Type->isDependentType() && Var->isLocalVarDecl() && | ||||||
12527 | !Var->hasLinkage() && !Var->isInvalidDecl() && | ||||||
12528 | RequireCompleteType(Var->getLocation(), Type, | ||||||
12529 | diag::err_typecheck_decl_incomplete_type)) | ||||||
12530 | Var->setInvalidDecl(); | ||||||
12531 | |||||||
12532 | // Make sure that the type is not abstract. | ||||||
12533 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | ||||||
12534 | RequireNonAbstractType(Var->getLocation(), Type, | ||||||
12535 | diag::err_abstract_type_in_decl, | ||||||
12536 | AbstractVariableType)) | ||||||
12537 | Var->setInvalidDecl(); | ||||||
12538 | if (!Type->isDependentType() && !Var->isInvalidDecl() && | ||||||
12539 | Var->getStorageClass() == SC_PrivateExtern) { | ||||||
12540 | Diag(Var->getLocation(), diag::warn_private_extern); | ||||||
12541 | Diag(Var->getLocation(), diag::note_private_extern); | ||||||
12542 | } | ||||||
12543 | |||||||
12544 | if (Context.getTargetInfo().allowDebugInfoForExternalVar() && | ||||||
12545 | !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) | ||||||
12546 | ExternalDeclarations.push_back(Var); | ||||||
12547 | |||||||
12548 | return; | ||||||
12549 | |||||||
12550 | case VarDecl::TentativeDefinition: | ||||||
12551 | // File scope. C99 6.9.2p2: A declaration of an identifier for an | ||||||
12552 | // object that has file scope without an initializer, and without a | ||||||
12553 | // storage-class specifier or with the storage-class specifier "static", | ||||||
12554 | // constitutes a tentative definition. Note: A tentative definition with | ||||||
12555 | // external linkage is valid (C99 6.2.2p5). | ||||||
12556 | if (!Var->isInvalidDecl()) { | ||||||
12557 | if (const IncompleteArrayType *ArrayT | ||||||
12558 | = Context.getAsIncompleteArrayType(Type)) { | ||||||
12559 | if (RequireCompleteSizedType( | ||||||
12560 | Var->getLocation(), ArrayT->getElementType(), | ||||||
12561 | diag::err_array_incomplete_or_sizeless_type)) | ||||||
12562 | Var->setInvalidDecl(); | ||||||
12563 | } else if (Var->getStorageClass() == SC_Static) { | ||||||
12564 | // C99 6.9.2p3: If the declaration of an identifier for an object is | ||||||
12565 | // a tentative definition and has internal linkage (C99 6.2.2p3), the | ||||||
12566 | // declared type shall not be an incomplete type. | ||||||
12567 | // NOTE: code such as the following | ||||||
12568 | // static struct s; | ||||||
12569 | // struct s { int a; }; | ||||||
12570 | // is accepted by gcc. Hence here we issue a warning instead of | ||||||
12571 | // an error and we do not invalidate the static declaration. | ||||||
12572 | // NOTE: to avoid multiple warnings, only check the first declaration. | ||||||
12573 | if (Var->isFirstDecl()) | ||||||
12574 | RequireCompleteType(Var->getLocation(), Type, | ||||||
12575 | diag::ext_typecheck_decl_incomplete_type); | ||||||
12576 | } | ||||||
12577 | } | ||||||
12578 | |||||||
12579 | // Record the tentative definition; we're done. | ||||||
12580 | if (!Var->isInvalidDecl()) | ||||||
12581 | TentativeDefinitions.push_back(Var); | ||||||
12582 | return; | ||||||
12583 | } | ||||||
12584 | |||||||
12585 | // Provide a specific diagnostic for uninitialized variable | ||||||
12586 | // definitions with incomplete array type. | ||||||
12587 | if (Type->isIncompleteArrayType()) { | ||||||
12588 | Diag(Var->getLocation(), | ||||||
12589 | diag::err_typecheck_incomplete_array_needs_initializer); | ||||||
12590 | Var->setInvalidDecl(); | ||||||
12591 | return; | ||||||
12592 | } | ||||||
12593 | |||||||
12594 | // Provide a specific diagnostic for uninitialized variable | ||||||
12595 | // definitions with reference type. | ||||||
12596 | if (Type->isReferenceType()) { | ||||||
12597 | Diag(Var->getLocation(), diag::err_reference_var_requires_init) | ||||||
12598 | << Var << SourceRange(Var->getLocation(), Var->getLocation()); | ||||||
12599 | Var->setInvalidDecl(); | ||||||
12600 | return; | ||||||
12601 | } | ||||||
12602 | |||||||
12603 | // Do not attempt to type-check the default initializer for a | ||||||
12604 | // variable with dependent type. | ||||||
12605 | if (Type->isDependentType()) | ||||||
12606 | return; | ||||||
12607 | |||||||
12608 | if (Var->isInvalidDecl()) | ||||||
12609 | return; | ||||||
12610 | |||||||
12611 | if (!Var->hasAttr<AliasAttr>()) { | ||||||
12612 | if (RequireCompleteType(Var->getLocation(), | ||||||
12613 | Context.getBaseElementType(Type), | ||||||
12614 | diag::err_typecheck_decl_incomplete_type)) { | ||||||
12615 | Var->setInvalidDecl(); | ||||||
12616 | return; | ||||||
12617 | } | ||||||
12618 | } else { | ||||||
12619 | return; | ||||||
12620 | } | ||||||
12621 | |||||||
12622 | // The variable can not have an abstract class type. | ||||||
12623 | if (RequireNonAbstractType(Var->getLocation(), Type, | ||||||
12624 | diag::err_abstract_type_in_decl, | ||||||
12625 | AbstractVariableType)) { | ||||||
12626 | Var->setInvalidDecl(); | ||||||
12627 | return; | ||||||
12628 | } | ||||||
12629 | |||||||
12630 | // Check for jumps past the implicit initializer. C++0x | ||||||
12631 | // clarifies that this applies to a "variable with automatic | ||||||
12632 | // storage duration", not a "local variable". | ||||||
12633 | // C++11 [stmt.dcl]p3 | ||||||
12634 | // A program that jumps from a point where a variable with automatic | ||||||
12635 | // storage duration is not in scope to a point where it is in scope is | ||||||
12636 | // ill-formed unless the variable has scalar type, class type with a | ||||||
12637 | // trivial default constructor and a trivial destructor, a cv-qualified | ||||||
12638 | // version of one of these types, or an array of one of the preceding | ||||||
12639 | // types and is declared without an initializer. | ||||||
12640 | if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { | ||||||
12641 | if (const RecordType *Record | ||||||
12642 | = Context.getBaseElementType(Type)->getAs<RecordType>()) { | ||||||
12643 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); | ||||||
12644 | // Mark the function (if we're in one) for further checking even if the | ||||||
12645 | // looser rules of C++11 do not require such checks, so that we can | ||||||
12646 | // diagnose incompatibilities with C++98. | ||||||
12647 | if (!CXXRecord->isPOD()) | ||||||
12648 | setFunctionHasBranchProtectedScope(); | ||||||
12649 | } | ||||||
12650 | } | ||||||
12651 | // In OpenCL, we can't initialize objects in the __local address space, | ||||||
12652 | // even implicitly, so don't synthesize an implicit initializer. | ||||||
12653 | if (getLangOpts().OpenCL && | ||||||
12654 | Var->getType().getAddressSpace() == LangAS::opencl_local) | ||||||
12655 | return; | ||||||
12656 | // C++03 [dcl.init]p9: | ||||||
12657 | // If no initializer is specified for an object, and the | ||||||
12658 | // object is of (possibly cv-qualified) non-POD class type (or | ||||||
12659 | // array thereof), the object shall be default-initialized; if | ||||||
12660 | // the object is of const-qualified type, the underlying class | ||||||
12661 | // type shall have a user-declared default | ||||||
12662 | // constructor. Otherwise, if no initializer is specified for | ||||||
12663 | // a non- static object, the object and its subobjects, if | ||||||
12664 | // any, have an indeterminate initial value); if the object | ||||||
12665 | // or any of its subobjects are of const-qualified type, the | ||||||
12666 | // program is ill-formed. | ||||||
12667 | // C++0x [dcl.init]p11: | ||||||
12668 | // If no initializer is specified for an object, the object is | ||||||
12669 | // default-initialized; [...]. | ||||||
12670 | InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); | ||||||
12671 | InitializationKind Kind | ||||||
12672 | = InitializationKind::CreateDefault(Var->getLocation()); | ||||||
12673 | |||||||
12674 | InitializationSequence InitSeq(*this, Entity, Kind, None); | ||||||
12675 | ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); | ||||||
12676 | |||||||
12677 | if (Init.get()) { | ||||||
12678 | Var->setInit(MaybeCreateExprWithCleanups(Init.get())); | ||||||
12679 | // This is important for template substitution. | ||||||
12680 | Var->setInitStyle(VarDecl::CallInit); | ||||||
12681 | } else if (Init.isInvalid()) { | ||||||
12682 | // If default-init fails, attach a recovery-expr initializer to track | ||||||
12683 | // that initialization was attempted and failed. | ||||||
12684 | auto RecoveryExpr = | ||||||
12685 | CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {}); | ||||||
12686 | if (RecoveryExpr.get()) | ||||||
12687 | Var->setInit(RecoveryExpr.get()); | ||||||
12688 | } | ||||||
12689 | |||||||
12690 | CheckCompleteVariableDeclaration(Var); | ||||||
12691 | } | ||||||
12692 | } | ||||||
12693 | |||||||
12694 | void Sema::ActOnCXXForRangeDecl(Decl *D) { | ||||||
12695 | // If there is no declaration, there was an error parsing it. Ignore it. | ||||||
12696 | if (!D) | ||||||
12697 | return; | ||||||
12698 | |||||||
12699 | VarDecl *VD = dyn_cast<VarDecl>(D); | ||||||
12700 | if (!VD) { | ||||||
12701 | Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); | ||||||
12702 | D->setInvalidDecl(); | ||||||
12703 | return; | ||||||
12704 | } | ||||||
12705 | |||||||
12706 | VD->setCXXForRangeDecl(true); | ||||||
12707 | |||||||
12708 | // for-range-declaration cannot be given a storage class specifier. | ||||||
12709 | int Error = -1; | ||||||
12710 | switch (VD->getStorageClass()) { | ||||||
12711 | case SC_None: | ||||||
12712 | break; | ||||||
12713 | case SC_Extern: | ||||||
12714 | Error = 0; | ||||||
12715 | break; | ||||||
12716 | case SC_Static: | ||||||
12717 | Error = 1; | ||||||
12718 | break; | ||||||
12719 | case SC_PrivateExtern: | ||||||
12720 | Error = 2; | ||||||
12721 | break; | ||||||
12722 | case SC_Auto: | ||||||
12723 | Error = 3; | ||||||
12724 | break; | ||||||
12725 | case SC_Register: | ||||||
12726 | Error = 4; | ||||||
12727 | break; | ||||||
12728 | } | ||||||
12729 | if (Error != -1) { | ||||||
12730 | Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) | ||||||
12731 | << VD << Error; | ||||||
12732 | D->setInvalidDecl(); | ||||||
12733 | } | ||||||
12734 | } | ||||||
12735 | |||||||
12736 | StmtResult | ||||||
12737 | Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, | ||||||
12738 | IdentifierInfo *Ident, | ||||||
12739 | ParsedAttributes &Attrs, | ||||||
12740 | SourceLocation AttrEnd) { | ||||||
12741 | // C++1y [stmt.iter]p1: | ||||||
12742 | // A range-based for statement of the form | ||||||
12743 | // for ( for-range-identifier : for-range-initializer ) statement | ||||||
12744 | // is equivalent to | ||||||
12745 | // for ( auto&& for-range-identifier : for-range-initializer ) statement | ||||||
12746 | DeclSpec DS(Attrs.getPool().getFactory()); | ||||||
12747 | |||||||
12748 | const char *PrevSpec; | ||||||
12749 | unsigned DiagID; | ||||||
12750 | DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, | ||||||
12751 | getPrintingPolicy()); | ||||||
12752 | |||||||
12753 | Declarator D(DS, DeclaratorContext::ForContext); | ||||||
12754 | D.SetIdentifier(Ident, IdentLoc); | ||||||
12755 | D.takeAttributes(Attrs, AttrEnd); | ||||||
12756 | |||||||
12757 | D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), | ||||||
12758 | IdentLoc); | ||||||
12759 | Decl *Var = ActOnDeclarator(S, D); | ||||||
12760 | cast<VarDecl>(Var)->setCXXForRangeDecl(true); | ||||||
12761 | FinalizeDeclaration(Var); | ||||||
12762 | return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, | ||||||
12763 | AttrEnd.isValid() ? AttrEnd : IdentLoc); | ||||||
12764 | } | ||||||
12765 | |||||||
12766 | void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { | ||||||
12767 | if (var->isInvalidDecl()) return; | ||||||
| |||||||
12768 | |||||||
12769 | if (getLangOpts().OpenCL) { | ||||||
12770 | // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an | ||||||
12771 | // initialiser | ||||||
12772 | if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && | ||||||
12773 | !var->hasInit()) { | ||||||
12774 | Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) | ||||||
12775 | << 1 /*Init*/; | ||||||
12776 | var->setInvalidDecl(); | ||||||
12777 | return; | ||||||
12778 | } | ||||||
12779 | } | ||||||
12780 | |||||||
12781 | // In Objective-C, don't allow jumps past the implicit initialization of a | ||||||
12782 | // local retaining variable. | ||||||
12783 | if (getLangOpts().ObjC && | ||||||
12784 | var->hasLocalStorage()) { | ||||||
12785 | switch (var->getType().getObjCLifetime()) { | ||||||
12786 | case Qualifiers::OCL_None: | ||||||
12787 | case Qualifiers::OCL_ExplicitNone: | ||||||
12788 | case Qualifiers::OCL_Autoreleasing: | ||||||
12789 | break; | ||||||
12790 | |||||||
12791 | case Qualifiers::OCL_Weak: | ||||||
12792 | case Qualifiers::OCL_Strong: | ||||||
12793 | setFunctionHasBranchProtectedScope(); | ||||||
12794 | break; | ||||||
12795 | } | ||||||
12796 | } | ||||||
12797 | |||||||
12798 | if (var->hasLocalStorage() && | ||||||
12799 | var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) | ||||||
12800 | setFunctionHasBranchProtectedScope(); | ||||||
12801 | |||||||
12802 | // Warn about externally-visible variables being defined without a | ||||||
12803 | // prior declaration. We only want to do this for global | ||||||
12804 | // declarations, but we also specifically need to avoid doing it for | ||||||
12805 | // class members because the linkage of an anonymous class can | ||||||
12806 | // change if it's later given a typedef name. | ||||||
12807 | if (var->isThisDeclarationADefinition() && | ||||||
12808 | var->getDeclContext()->getRedeclContext()->isFileContext() && | ||||||
12809 | var->isExternallyVisible() && var->hasLinkage() && | ||||||
12810 | !var->isInline() && !var->getDescribedVarTemplate() && | ||||||
12811 | !isa<VarTemplatePartialSpecializationDecl>(var) && | ||||||
12812 | !isTemplateInstantiation(var->getTemplateSpecializationKind()) && | ||||||
12813 | !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, | ||||||
12814 | var->getLocation())) { | ||||||
12815 | // Find a previous declaration that's not a definition. | ||||||
12816 | VarDecl *prev = var->getPreviousDecl(); | ||||||
12817 | while (prev && prev->isThisDeclarationADefinition()) | ||||||
12818 | prev = prev->getPreviousDecl(); | ||||||
12819 | |||||||
12820 | if (!prev) { | ||||||
12821 | Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; | ||||||
12822 | Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | ||||||
12823 | << /* variable */ 0; | ||||||
12824 | } | ||||||
12825 | } | ||||||
12826 | |||||||
12827 | // Cache the result of checking for constant initialization. | ||||||
12828 | Optional<bool> CacheHasConstInit; | ||||||
12829 | const Expr *CacheCulprit = nullptr; | ||||||
12830 | auto checkConstInit = [&]() mutable { | ||||||
12831 | if (!CacheHasConstInit) | ||||||
12832 | CacheHasConstInit = var->getInit()->isConstantInitializer( | ||||||
12833 | Context, var->getType()->isReferenceType(), &CacheCulprit); | ||||||
12834 | return *CacheHasConstInit; | ||||||
12835 | }; | ||||||
12836 | |||||||
12837 | if (var->getTLSKind() == VarDecl::TLS_Static) { | ||||||
12838 | if (var->getType().isDestructedType()) { | ||||||
12839 | // GNU C++98 edits for __thread, [basic.start.term]p3: | ||||||
12840 | // The type of an object with thread storage duration shall not | ||||||
12841 | // have a non-trivial destructor. | ||||||
12842 | Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); | ||||||
12843 | if (getLangOpts().CPlusPlus11) | ||||||
12844 | Diag(var->getLocation(), diag::note_use_thread_local); | ||||||
12845 | } else if (getLangOpts().CPlusPlus && var->hasInit()) { | ||||||
12846 | if (!checkConstInit()) { | ||||||
12847 | // GNU C++98 edits for __thread, [basic.start.init]p4: | ||||||
12848 | // An object of thread storage duration shall not require dynamic | ||||||
12849 | // initialization. | ||||||
12850 | // FIXME: Need strict checking here. | ||||||
12851 | Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) | ||||||
12852 | << CacheCulprit->getSourceRange(); | ||||||
12853 | if (getLangOpts().CPlusPlus11) | ||||||
12854 | Diag(var->getLocation(), diag::note_use_thread_local); | ||||||
12855 | } | ||||||
12856 | } | ||||||
12857 | } | ||||||
12858 | |||||||
12859 | // Apply section attributes and pragmas to global variables. | ||||||
12860 | bool GlobalStorage = var->hasGlobalStorage(); | ||||||
12861 | if (GlobalStorage
| ||||||
12862 | !inTemplateInstantiation()) { | ||||||
12863 | PragmaStack<StringLiteral *> *Stack = nullptr; | ||||||
12864 | int SectionFlags = ASTContext::PSF_Read; | ||||||
12865 | if (var->getType().isConstQualified()) | ||||||
12866 | Stack = &ConstSegStack; | ||||||
12867 | else if (!var->getInit()) { | ||||||
12868 | Stack = &BSSSegStack; | ||||||
12869 | SectionFlags |= ASTContext::PSF_Write; | ||||||
12870 | } else { | ||||||
12871 | Stack = &DataSegStack; | ||||||
12872 | SectionFlags |= ASTContext::PSF_Write; | ||||||
12873 | } | ||||||
12874 | if (const SectionAttr *SA = var->getAttr<SectionAttr>()) { | ||||||
12875 | if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec) | ||||||
12876 | SectionFlags |= ASTContext::PSF_Implicit; | ||||||
12877 | UnifySection(SA->getName(), SectionFlags, var); | ||||||
12878 | } else if (Stack->CurrentValue) { | ||||||
12879 | SectionFlags |= ASTContext::PSF_Implicit; | ||||||
12880 | auto SectionName = Stack->CurrentValue->getString(); | ||||||
12881 | var->addAttr(SectionAttr::CreateImplicit( | ||||||
12882 | Context, SectionName, Stack->CurrentPragmaLocation, | ||||||
12883 | AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate)); | ||||||
12884 | if (UnifySection(SectionName, SectionFlags, var)) | ||||||
12885 | var->dropAttr<SectionAttr>(); | ||||||
12886 | } | ||||||
12887 | |||||||
12888 | // Apply the init_seg attribute if this has an initializer. If the | ||||||
12889 | // initializer turns out to not be dynamic, we'll end up ignoring this | ||||||
12890 | // attribute. | ||||||
12891 | if (CurInitSeg && var->getInit()) | ||||||
12892 | var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), | ||||||
12893 | CurInitSegLoc, | ||||||
12894 | AttributeCommonInfo::AS_Pragma)); | ||||||
12895 | } | ||||||
12896 | |||||||
12897 | if (!var->getType()->isStructureType() && var->hasInit() && | ||||||
12898 | isa<InitListExpr>(var->getInit())) { | ||||||
12899 | const auto *ILE = cast<InitListExpr>(var->getInit()); | ||||||
12900 | unsigned NumInits = ILE->getNumInits(); | ||||||
12901 | if (NumInits > 2) | ||||||
12902 | for (unsigned I = 0; I < NumInits; ++I) { | ||||||
12903 | const auto *Init = ILE->getInit(I); | ||||||
12904 | if (!Init) | ||||||
12905 | break; | ||||||
12906 | const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); | ||||||
12907 | if (!SL) | ||||||
12908 | break; | ||||||
12909 | |||||||
12910 | unsigned NumConcat = SL->getNumConcatenated(); | ||||||
12911 | // Diagnose missing comma in string array initialization. | ||||||
12912 | // Do not warn when all the elements in the initializer are concatenated | ||||||
12913 | // together. Do not warn for macros too. | ||||||
12914 | if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) { | ||||||
12915 | bool OnlyOneMissingComma = true; | ||||||
12916 | for (unsigned J = I + 1; J < NumInits; ++J) { | ||||||
12917 | const auto *Init = ILE->getInit(J); | ||||||
12918 | if (!Init) | ||||||
12919 | break; | ||||||
12920 | const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts()); | ||||||
12921 | if (!SLJ || SLJ->getNumConcatenated() > 1) { | ||||||
12922 | OnlyOneMissingComma = false; | ||||||
12923 | break; | ||||||
12924 | } | ||||||
12925 | } | ||||||
12926 | |||||||
12927 | if (OnlyOneMissingComma) { | ||||||
12928 | SmallVector<FixItHint, 1> Hints; | ||||||
12929 | for (unsigned i = 0; i < NumConcat - 1; ++i) | ||||||
12930 | Hints.push_back(FixItHint::CreateInsertion( | ||||||
12931 | PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ",")); | ||||||
12932 | |||||||
12933 | Diag(SL->getStrTokenLoc(1), | ||||||
12934 | diag::warn_concatenated_literal_array_init) | ||||||
12935 | << Hints; | ||||||
12936 | Diag(SL->getBeginLoc(), | ||||||
12937 | diag::note_concatenated_string_literal_silence); | ||||||
12938 | } | ||||||
12939 | // In any case, stop now. | ||||||
12940 | break; | ||||||
12941 | } | ||||||
12942 | } | ||||||
12943 | } | ||||||
12944 | |||||||
12945 | // All the following checks are C++ only. | ||||||
12946 | if (!getLangOpts().CPlusPlus) { | ||||||
12947 | // If this variable must be emitted, add it as an initializer for the | ||||||
12948 | // current module. | ||||||
12949 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | ||||||
12950 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | ||||||
12951 | return; | ||||||
12952 | } | ||||||
12953 | |||||||
12954 | if (auto *DD
| ||||||
12955 | CheckCompleteDecompositionDeclaration(DD); | ||||||
12956 | |||||||
12957 | QualType type = var->getType(); | ||||||
12958 | if (type->isDependentType()) return; | ||||||
12959 | |||||||
12960 | if (var->hasAttr<BlocksAttr>()) | ||||||
12961 | getCurFunction()->addByrefBlockVar(var); | ||||||
12962 | |||||||
12963 | Expr *Init = var->getInit(); | ||||||
12964 | bool IsGlobal = GlobalStorage
| ||||||
12965 | QualType baseType = Context.getBaseElementType(type); | ||||||
12966 | |||||||
12967 | if (Init && !Init->isValueDependent()) { | ||||||
12968 | if (var->isConstexpr()) { | ||||||
12969 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||
12970 | if (!var->evaluateValue(Notes) || !var->isInitICE()) { | ||||||
12971 | SourceLocation DiagLoc = var->getLocation(); | ||||||
12972 | // If the note doesn't add any useful information other than a source | ||||||
12973 | // location, fold it into the primary diagnostic. | ||||||
12974 | if (Notes.size() == 1 && Notes[0].second.getDiagID() == | ||||||
12975 | diag::note_invalid_subexpr_in_const_expr) { | ||||||
12976 | DiagLoc = Notes[0].first; | ||||||
12977 | Notes.clear(); | ||||||
12978 | } | ||||||
12979 | Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) | ||||||
12980 | << var << Init->getSourceRange(); | ||||||
12981 | for (unsigned I = 0, N = Notes.size(); I != N; ++I) | ||||||
12982 | Diag(Notes[I].first, Notes[I].second); | ||||||
12983 | } | ||||||
12984 | } else if (var->mightBeUsableInConstantExpressions(Context)) { | ||||||
12985 | // Check whether the initializer of a const variable of integral or | ||||||
12986 | // enumeration type is an ICE now, since we can't tell whether it was | ||||||
12987 | // initialized by a constant expression if we check later. | ||||||
12988 | var->checkInitIsICE(); | ||||||
12989 | } | ||||||
12990 | |||||||
12991 | // Don't emit further diagnostics about constexpr globals since they | ||||||
12992 | // were just diagnosed. | ||||||
12993 | if (!var->isConstexpr() && GlobalStorage
| ||||||
12994 | // FIXME: Need strict checking in C++03 here. | ||||||
12995 | bool DiagErr = getLangOpts().CPlusPlus11 | ||||||
12996 | ? !var->checkInitIsICE() : !checkConstInit(); | ||||||
12997 | if (DiagErr
| ||||||
12998 | auto *Attr = var->getAttr<ConstInitAttr>(); | ||||||
12999 | Diag(var->getLocation(), diag::err_require_constant_init_failed) | ||||||
13000 | << Init->getSourceRange(); | ||||||
13001 | Diag(Attr->getLocation(), | ||||||
13002 | diag::note_declared_required_constant_init_here) | ||||||
13003 | << Attr->getRange() << Attr->isConstinit(); | ||||||
13004 | if (getLangOpts().CPlusPlus11) { | ||||||
13005 | APValue Value; | ||||||
13006 | SmallVector<PartialDiagnosticAt, 8> Notes; | ||||||
13007 | Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); | ||||||
13008 | for (auto &it : Notes) | ||||||
13009 | Diag(it.first, it.second); | ||||||
13010 | } else { | ||||||
13011 | Diag(CacheCulprit->getExprLoc(), | ||||||
| |||||||
13012 | diag::note_invalid_subexpr_in_const_expr) | ||||||
13013 | << CacheCulprit->getSourceRange(); | ||||||
13014 | } | ||||||
13015 | } | ||||||
13016 | } | ||||||
13017 | else if (!var->isConstexpr() && IsGlobal && | ||||||
13018 | !getDiagnostics().isIgnored(diag::warn_global_constructor, | ||||||
13019 | var->getLocation())) { | ||||||
13020 | // Warn about globals which don't have a constant initializer. Don't | ||||||
13021 | // warn about globals with a non-trivial destructor because we already | ||||||
13022 | // warned about them. | ||||||
13023 | CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); | ||||||
13024 | if (!(RD && !RD->hasTrivialDestructor())) { | ||||||
13025 | if (!checkConstInit()) | ||||||
13026 | Diag(var->getLocation(), diag::warn_global_constructor) | ||||||
13027 | << Init->getSourceRange(); | ||||||
13028 | } | ||||||
13029 | } | ||||||
13030 | } | ||||||
13031 | |||||||
13032 | // Require the destructor. | ||||||
13033 | if (const RecordType *recordType = baseType->getAs<RecordType>()) | ||||||
13034 | FinalizeVarWithDestructor(var, recordType); | ||||||
13035 | |||||||
13036 | // If this variable must be emitted, add it as an initializer for the current | ||||||
13037 | // module. | ||||||
13038 | if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) | ||||||
13039 | Context.addModuleInitializer(ModuleScopes.back().Module, var); | ||||||
13040 | } | ||||||
13041 | |||||||
13042 | /// Determines if a variable's alignment is dependent. | ||||||
13043 | static bool hasDependentAlignment(VarDecl *VD) { | ||||||
13044 | if (VD->getType()->isDependentType()) | ||||||
13045 | return true; | ||||||
13046 | for (auto *I : VD->specific_attrs<AlignedAttr>()) | ||||||
13047 | if (I->isAlignmentDependent()) | ||||||
13048 | return true; | ||||||
13049 | return false; | ||||||
13050 | } | ||||||
13051 | |||||||
13052 | /// Check if VD needs to be dllexport/dllimport due to being in a | ||||||
13053 | /// dllexport/import function. | ||||||
13054 | void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { | ||||||
13055 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 13055, __PRETTY_FUNCTION__)); | ||||||
13056 | |||||||
13057 | auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | ||||||
13058 | |||||||
13059 | // Find outermost function when VD is in lambda function. | ||||||
13060 | while (FD && !getDLLAttr(FD) && | ||||||
13061 | !FD->hasAttr<DLLExportStaticLocalAttr>() && | ||||||
13062 | !FD->hasAttr<DLLImportStaticLocalAttr>()) { | ||||||
13063 | FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); | ||||||
13064 | } | ||||||
13065 | |||||||
13066 | if (!FD) | ||||||
13067 | return; | ||||||
13068 | |||||||
13069 | // Static locals inherit dll attributes from their function. | ||||||
13070 | if (Attr *A = getDLLAttr(FD)) { | ||||||
13071 | auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); | ||||||
13072 | NewAttr->setInherited(true); | ||||||
13073 | VD->addAttr(NewAttr); | ||||||
13074 | } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { | ||||||
13075 | auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); | ||||||
13076 | NewAttr->setInherited(true); | ||||||
13077 | VD->addAttr(NewAttr); | ||||||
13078 | |||||||
13079 | // Export this function to enforce exporting this static variable even | ||||||
13080 | // if it is not used in this compilation unit. | ||||||
13081 | if (!FD->hasAttr<DLLExportAttr>()) | ||||||
13082 | FD->addAttr(NewAttr); | ||||||
13083 | |||||||
13084 | } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { | ||||||
13085 | auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); | ||||||
13086 | NewAttr->setInherited(true); | ||||||
13087 | VD->addAttr(NewAttr); | ||||||
13088 | } | ||||||
13089 | } | ||||||
13090 | |||||||
13091 | /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform | ||||||
13092 | /// any semantic actions necessary after any initializer has been attached. | ||||||
13093 | void Sema::FinalizeDeclaration(Decl *ThisDecl) { | ||||||
13094 | // Note that we are no longer parsing the initializer for this declaration. | ||||||
13095 | ParsingInitForAutoVars.erase(ThisDecl); | ||||||
13096 | |||||||
13097 | VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); | ||||||
13098 | if (!VD) | ||||||
13099 | return; | ||||||
13100 | |||||||
13101 | // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active | ||||||
13102 | if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && | ||||||
13103 | !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { | ||||||
13104 | if (PragmaClangBSSSection.Valid) | ||||||
13105 | VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( | ||||||
13106 | Context, PragmaClangBSSSection.SectionName, | ||||||
13107 | PragmaClangBSSSection.PragmaLocation, | ||||||
13108 | AttributeCommonInfo::AS_Pragma)); | ||||||
13109 | if (PragmaClangDataSection.Valid) | ||||||
13110 | VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( | ||||||
13111 | Context, PragmaClangDataSection.SectionName, | ||||||
13112 | PragmaClangDataSection.PragmaLocation, | ||||||
13113 | AttributeCommonInfo::AS_Pragma)); | ||||||
13114 | if (PragmaClangRodataSection.Valid) | ||||||
13115 | VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( | ||||||
13116 | Context, PragmaClangRodataSection.SectionName, | ||||||
13117 | PragmaClangRodataSection.PragmaLocation, | ||||||
13118 | AttributeCommonInfo::AS_Pragma)); | ||||||
13119 | if (PragmaClangRelroSection.Valid) | ||||||
13120 | VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( | ||||||
13121 | Context, PragmaClangRelroSection.SectionName, | ||||||
13122 | PragmaClangRelroSection.PragmaLocation, | ||||||
13123 | AttributeCommonInfo::AS_Pragma)); | ||||||
13124 | } | ||||||
13125 | |||||||
13126 | if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { | ||||||
13127 | for (auto *BD : DD->bindings()) { | ||||||
13128 | FinalizeDeclaration(BD); | ||||||
13129 | } | ||||||
13130 | } | ||||||
13131 | |||||||
13132 | checkAttributesAfterMerging(*this, *VD); | ||||||
13133 | |||||||
13134 | // Perform TLS alignment check here after attributes attached to the variable | ||||||
13135 | // which may affect the alignment have been processed. Only perform the check | ||||||
13136 | // if the target has a maximum TLS alignment (zero means no constraints). | ||||||
13137 | if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { | ||||||
13138 | // Protect the check so that it's not performed on dependent types and | ||||||
13139 | // dependent alignments (we can't determine the alignment in that case). | ||||||
13140 | if (VD->getTLSKind() && !hasDependentAlignment(VD) && | ||||||
13141 | !VD->isInvalidDecl()) { | ||||||
13142 | CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); | ||||||
13143 | if (Context.getDeclAlign(VD) > MaxAlignChars) { | ||||||
13144 | Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) | ||||||
13145 | << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD | ||||||
13146 | << (unsigned)MaxAlignChars.getQuantity(); | ||||||
13147 | } | ||||||
13148 | } | ||||||
13149 | } | ||||||
13150 | |||||||
13151 | if (VD->isStaticLocal()) { | ||||||
13152 | CheckStaticLocalForDllExport(VD); | ||||||
13153 | |||||||
13154 | if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { | ||||||
13155 | // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ | ||||||
13156 | // function, only __shared__ variables or variables without any device | ||||||
13157 | // memory qualifiers may be declared with static storage class. | ||||||
13158 | // Note: It is unclear how a function-scope non-const static variable | ||||||
13159 | // without device memory qualifier is implemented, therefore only static | ||||||
13160 | // const variable without device memory qualifier is allowed. | ||||||
13161 | [&]() { | ||||||
13162 | if (!getLangOpts().CUDA) | ||||||
13163 | return; | ||||||
13164 | if (VD->hasAttr<CUDASharedAttr>()) | ||||||
13165 | return; | ||||||
13166 | if (VD->getType().isConstQualified() && | ||||||
13167 | !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) | ||||||
13168 | return; | ||||||
13169 | if (CUDADiagIfDeviceCode(VD->getLocation(), | ||||||
13170 | diag::err_device_static_local_var) | ||||||
13171 | << CurrentCUDATarget()) | ||||||
13172 | VD->setInvalidDecl(); | ||||||
13173 | }(); | ||||||
13174 | } | ||||||
13175 | } | ||||||
13176 | |||||||
13177 | // Perform check for initializers of device-side global variables. | ||||||
13178 | // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA | ||||||
13179 | // 7.5). We must also apply the same checks to all __shared__ | ||||||
13180 | // variables whether they are local or not. CUDA also allows | ||||||
13181 | // constant initializers for __constant__ and __device__ variables. | ||||||
13182 | if (getLangOpts().CUDA) | ||||||
13183 | checkAllowedCUDAInitializer(VD); | ||||||
13184 | |||||||
13185 | // Grab the dllimport or dllexport attribute off of the VarDecl. | ||||||
13186 | const InheritableAttr *DLLAttr = getDLLAttr(VD); | ||||||
13187 | |||||||
13188 | // Imported static data members cannot be defined out-of-line. | ||||||
13189 | if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { | ||||||
13190 | if (VD->isStaticDataMember() && VD->isOutOfLine() && | ||||||
13191 | VD->isThisDeclarationADefinition()) { | ||||||
13192 | // We allow definitions of dllimport class template static data members | ||||||
13193 | // with a warning. | ||||||
13194 | CXXRecordDecl *Context = | ||||||
13195 | cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); | ||||||
13196 | bool IsClassTemplateMember = | ||||||
13197 | isa<ClassTemplatePartialSpecializationDecl>(Context) || | ||||||
13198 | Context->getDescribedClassTemplate(); | ||||||
13199 | |||||||
13200 | Diag(VD->getLocation(), | ||||||
13201 | IsClassTemplateMember | ||||||
13202 | ? diag::warn_attribute_dllimport_static_field_definition | ||||||
13203 | : diag::err_attribute_dllimport_static_field_definition); | ||||||
13204 | Diag(IA->getLocation(), diag::note_attribute); | ||||||
13205 | if (!IsClassTemplateMember) | ||||||
13206 | VD->setInvalidDecl(); | ||||||
13207 | } | ||||||
13208 | } | ||||||
13209 | |||||||
13210 | // dllimport/dllexport variables cannot be thread local, their TLS index | ||||||
13211 | // isn't exported with the variable. | ||||||
13212 | if (DLLAttr && VD->getTLSKind()) { | ||||||
13213 | auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); | ||||||
13214 | if (F && getDLLAttr(F)) { | ||||||
13215 | assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 13215, __PRETTY_FUNCTION__)); | ||||||
13216 | // But if this is a static local in a dlimport/dllexport function, the | ||||||
13217 | // function will never be inlined, which means the var would never be | ||||||
13218 | // imported, so having it marked import/export is safe. | ||||||
13219 | } else { | ||||||
13220 | Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD | ||||||
13221 | << DLLAttr; | ||||||
13222 | VD->setInvalidDecl(); | ||||||
13223 | } | ||||||
13224 | } | ||||||
13225 | |||||||
13226 | if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { | ||||||
13227 | if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { | ||||||
13228 | Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; | ||||||
13229 | VD->dropAttr<UsedAttr>(); | ||||||
13230 | } | ||||||
13231 | } | ||||||
13232 | |||||||
13233 | const DeclContext *DC = VD->getDeclContext(); | ||||||
13234 | // If there's a #pragma GCC visibility in scope, and this isn't a class | ||||||
13235 | // member, set the visibility of this variable. | ||||||
13236 | if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) | ||||||
13237 | AddPushedVisibilityAttribute(VD); | ||||||
13238 | |||||||
13239 | // FIXME: Warn on unused var template partial specializations. | ||||||
13240 | if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) | ||||||
13241 | MarkUnusedFileScopedDecl(VD); | ||||||
13242 | |||||||
13243 | // Now we have parsed the initializer and can update the table of magic | ||||||
13244 | // tag values. | ||||||
13245 | if (!VD->hasAttr<TypeTagForDatatypeAttr>() || | ||||||
13246 | !VD->getType()->isIntegralOrEnumerationType()) | ||||||
13247 | return; | ||||||
13248 | |||||||
13249 | for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { | ||||||
13250 | const Expr *MagicValueExpr = VD->getInit(); | ||||||
13251 | if (!MagicValueExpr) { | ||||||
13252 | continue; | ||||||
13253 | } | ||||||
13254 | Optional<llvm::APSInt> MagicValueInt; | ||||||
13255 | if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) { | ||||||
13256 | Diag(I->getRange().getBegin(), | ||||||
13257 | diag::err_type_tag_for_datatype_not_ice) | ||||||
13258 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | ||||||
13259 | continue; | ||||||
13260 | } | ||||||
13261 | if (MagicValueInt->getActiveBits() > 64) { | ||||||
13262 | Diag(I->getRange().getBegin(), | ||||||
13263 | diag::err_type_tag_for_datatype_too_large) | ||||||
13264 | << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); | ||||||
13265 | continue; | ||||||
13266 | } | ||||||
13267 | uint64_t MagicValue = MagicValueInt->getZExtValue(); | ||||||
13268 | RegisterTypeTagForDatatype(I->getArgumentKind(), | ||||||
13269 | MagicValue, | ||||||
13270 | I->getMatchingCType(), | ||||||
13271 | I->getLayoutCompatible(), | ||||||
13272 | I->getMustBeNull()); | ||||||
13273 | } | ||||||
13274 | } | ||||||
13275 | |||||||
13276 | static bool hasDeducedAuto(DeclaratorDecl *DD) { | ||||||
13277 | auto *VD = dyn_cast<VarDecl>(DD); | ||||||
13278 | return VD && !VD->getType()->hasAutoForTrailingReturnType(); | ||||||
13279 | } | ||||||
13280 | |||||||
13281 | Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, | ||||||
13282 | ArrayRef<Decl *> Group) { | ||||||
13283 | SmallVector<Decl*, 8> Decls; | ||||||
13284 | |||||||
13285 | if (DS.isTypeSpecOwned()) | ||||||
13286 | Decls.push_back(DS.getRepAsDecl()); | ||||||
13287 | |||||||
13288 | DeclaratorDecl *FirstDeclaratorInGroup = nullptr; | ||||||
13289 | DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; | ||||||
13290 | bool DiagnosedMultipleDecomps = false; | ||||||
13291 | DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; | ||||||
13292 | bool DiagnosedNonDeducedAuto = false; | ||||||
13293 | |||||||
13294 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | ||||||
13295 | if (Decl *D = Group[i]) { | ||||||
13296 | // For declarators, there are some additional syntactic-ish checks we need | ||||||
13297 | // to perform. | ||||||
13298 | if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { | ||||||
13299 | if (!FirstDeclaratorInGroup) | ||||||
13300 | FirstDeclaratorInGroup = DD; | ||||||
13301 | if (!FirstDecompDeclaratorInGroup) | ||||||
13302 | FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); | ||||||
13303 | if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && | ||||||
13304 | !hasDeducedAuto(DD)) | ||||||
13305 | FirstNonDeducedAutoInGroup = DD; | ||||||
13306 | |||||||
13307 | if (FirstDeclaratorInGroup != DD) { | ||||||
13308 | // A decomposition declaration cannot be combined with any other | ||||||
13309 | // declaration in the same group. | ||||||
13310 | if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { | ||||||
13311 | Diag(FirstDecompDeclaratorInGroup->getLocation(), | ||||||
13312 | diag::err_decomp_decl_not_alone) | ||||||
13313 | << FirstDeclaratorInGroup->getSourceRange() | ||||||
13314 | << DD->getSourceRange(); | ||||||
13315 | DiagnosedMultipleDecomps = true; | ||||||
13316 | } | ||||||
13317 | |||||||
13318 | // A declarator that uses 'auto' in any way other than to declare a | ||||||
13319 | // variable with a deduced type cannot be combined with any other | ||||||
13320 | // declarator in the same group. | ||||||
13321 | if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { | ||||||
13322 | Diag(FirstNonDeducedAutoInGroup->getLocation(), | ||||||
13323 | diag::err_auto_non_deduced_not_alone) | ||||||
13324 | << FirstNonDeducedAutoInGroup->getType() | ||||||
13325 | ->hasAutoForTrailingReturnType() | ||||||
13326 | << FirstDeclaratorInGroup->getSourceRange() | ||||||
13327 | << DD->getSourceRange(); | ||||||
13328 | DiagnosedNonDeducedAuto = true; | ||||||
13329 | } | ||||||
13330 | } | ||||||
13331 | } | ||||||
13332 | |||||||
13333 | Decls.push_back(D); | ||||||
13334 | } | ||||||
13335 | } | ||||||
13336 | |||||||
13337 | if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { | ||||||
13338 | if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { | ||||||
13339 | handleTagNumbering(Tag, S); | ||||||
13340 | if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && | ||||||
13341 | getLangOpts().CPlusPlus) | ||||||
13342 | Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); | ||||||
13343 | } | ||||||
13344 | } | ||||||
13345 | |||||||
13346 | return BuildDeclaratorGroup(Decls); | ||||||
13347 | } | ||||||
13348 | |||||||
13349 | /// BuildDeclaratorGroup - convert a list of declarations into a declaration | ||||||
13350 | /// group, performing any necessary semantic checking. | ||||||
13351 | Sema::DeclGroupPtrTy | ||||||
13352 | Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { | ||||||
13353 | // C++14 [dcl.spec.auto]p7: (DR1347) | ||||||
13354 | // If the type that replaces the placeholder type is not the same in each | ||||||
13355 | // deduction, the program is ill-formed. | ||||||
13356 | if (Group.size() > 1) { | ||||||
13357 | QualType Deduced; | ||||||
13358 | VarDecl *DeducedDecl = nullptr; | ||||||
13359 | for (unsigned i = 0, e = Group.size(); i != e; ++i) { | ||||||
13360 | VarDecl *D = dyn_cast<VarDecl>(Group[i]); | ||||||
13361 | if (!D || D->isInvalidDecl()) | ||||||
13362 | break; | ||||||
13363 | DeducedType *DT = D->getType()->getContainedDeducedType(); | ||||||
13364 | if (!DT || DT->getDeducedType().isNull()) | ||||||
13365 | continue; | ||||||
13366 | if (Deduced.isNull()) { | ||||||
13367 | Deduced = DT->getDeducedType(); | ||||||
13368 | DeducedDecl = D; | ||||||
13369 | } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { | ||||||
13370 | auto *AT = dyn_cast<AutoType>(DT); | ||||||
13371 | auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), | ||||||
13372 | diag::err_auto_different_deductions) | ||||||
13373 | << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced | ||||||
13374 | << DeducedDecl->getDeclName() << DT->getDeducedType() | ||||||
13375 | << D->getDeclName(); | ||||||
13376 | if (DeducedDecl->hasInit()) | ||||||
13377 | Dia << DeducedDecl->getInit()->getSourceRange(); | ||||||
13378 | if (D->getInit()) | ||||||
13379 | Dia << D->getInit()->getSourceRange(); | ||||||
13380 | D->setInvalidDecl(); | ||||||
13381 | break; | ||||||
13382 | } | ||||||
13383 | } | ||||||
13384 | } | ||||||
13385 | |||||||
13386 | ActOnDocumentableDecls(Group); | ||||||
13387 | |||||||
13388 | return DeclGroupPtrTy::make( | ||||||
13389 | DeclGroupRef::Create(Context, Group.data(), Group.size())); | ||||||
13390 | } | ||||||
13391 | |||||||
13392 | void Sema::ActOnDocumentableDecl(Decl *D) { | ||||||
13393 | ActOnDocumentableDecls(D); | ||||||
13394 | } | ||||||
13395 | |||||||
13396 | void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { | ||||||
13397 | // Don't parse the comment if Doxygen diagnostics are ignored. | ||||||
13398 | if (Group.empty() || !Group[0]) | ||||||
13399 | return; | ||||||
13400 | |||||||
13401 | if (Diags.isIgnored(diag::warn_doc_param_not_found, | ||||||
13402 | Group[0]->getLocation()) && | ||||||
13403 | Diags.isIgnored(diag::warn_unknown_comment_command_name, | ||||||
13404 | Group[0]->getLocation())) | ||||||
13405 | return; | ||||||
13406 | |||||||
13407 | if (Group.size() >= 2) { | ||||||
13408 | // This is a decl group. Normally it will contain only declarations | ||||||
13409 | // produced from declarator list. But in case we have any definitions or | ||||||
13410 | // additional declaration references: | ||||||
13411 | // 'typedef struct S {} S;' | ||||||
13412 | // 'typedef struct S *S;' | ||||||
13413 | // 'struct S *pS;' | ||||||
13414 | // FinalizeDeclaratorGroup adds these as separate declarations. | ||||||
13415 | Decl *MaybeTagDecl = Group[0]; | ||||||
13416 | if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { | ||||||
13417 | Group = Group.slice(1); | ||||||
13418 | } | ||||||
13419 | } | ||||||
13420 | |||||||
13421 | // FIMXE: We assume every Decl in the group is in the same file. | ||||||
13422 | // This is false when preprocessor constructs the group from decls in | ||||||
13423 | // different files (e. g. macros or #include). | ||||||
13424 | Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); | ||||||
13425 | } | ||||||
13426 | |||||||
13427 | /// Common checks for a parameter-declaration that should apply to both function | ||||||
13428 | /// parameters and non-type template parameters. | ||||||
13429 | void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { | ||||||
13430 | // Check that there are no default arguments inside the type of this | ||||||
13431 | // parameter. | ||||||
13432 | if (getLangOpts().CPlusPlus) | ||||||
13433 | CheckExtraCXXDefaultArguments(D); | ||||||
13434 | |||||||
13435 | // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). | ||||||
13436 | if (D.getCXXScopeSpec().isSet()) { | ||||||
13437 | Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) | ||||||
13438 | << D.getCXXScopeSpec().getRange(); | ||||||
13439 | } | ||||||
13440 | |||||||
13441 | // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a | ||||||
13442 | // simple identifier except [...irrelevant cases...]. | ||||||
13443 | switch (D.getName().getKind()) { | ||||||
13444 | case UnqualifiedIdKind::IK_Identifier: | ||||||
13445 | break; | ||||||
13446 | |||||||
13447 | case UnqualifiedIdKind::IK_OperatorFunctionId: | ||||||
13448 | case UnqualifiedIdKind::IK_ConversionFunctionId: | ||||||
13449 | case UnqualifiedIdKind::IK_LiteralOperatorId: | ||||||
13450 | case UnqualifiedIdKind::IK_ConstructorName: | ||||||
13451 | case UnqualifiedIdKind::IK_DestructorName: | ||||||
13452 | case UnqualifiedIdKind::IK_ImplicitSelfParam: | ||||||
13453 | case UnqualifiedIdKind::IK_DeductionGuideName: | ||||||
13454 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) | ||||||
13455 | << GetNameForDeclarator(D).getName(); | ||||||
13456 | break; | ||||||
13457 | |||||||
13458 | case UnqualifiedIdKind::IK_TemplateId: | ||||||
13459 | case UnqualifiedIdKind::IK_ConstructorTemplateId: | ||||||
13460 | // GetNameForDeclarator would not produce a useful name in this case. | ||||||
13461 | Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); | ||||||
13462 | break; | ||||||
13463 | } | ||||||
13464 | } | ||||||
13465 | |||||||
13466 | /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() | ||||||
13467 | /// to introduce parameters into function prototype scope. | ||||||
13468 | Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { | ||||||
13469 | const DeclSpec &DS = D.getDeclSpec(); | ||||||
13470 | |||||||
13471 | // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. | ||||||
13472 | |||||||
13473 | // C++03 [dcl.stc]p2 also permits 'auto'. | ||||||
13474 | StorageClass SC = SC_None; | ||||||
13475 | if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { | ||||||
13476 | SC = SC_Register; | ||||||
13477 | // In C++11, the 'register' storage class specifier is deprecated. | ||||||
13478 | // In C++17, it is not allowed, but we tolerate it as an extension. | ||||||
13479 | if (getLangOpts().CPlusPlus11) { | ||||||
13480 | Diag(DS.getStorageClassSpecLoc(), | ||||||
13481 | getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class | ||||||
13482 | : diag::warn_deprecated_register) | ||||||
13483 | << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); | ||||||
13484 | } | ||||||
13485 | } else if (getLangOpts().CPlusPlus && | ||||||
13486 | DS.getStorageClassSpec() == DeclSpec::SCS_auto) { | ||||||
13487 | SC = SC_Auto; | ||||||
13488 | } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { | ||||||
13489 | Diag(DS.getStorageClassSpecLoc(), | ||||||
13490 | diag::err_invalid_storage_class_in_func_decl); | ||||||
13491 | D.getMutableDeclSpec().ClearStorageClassSpecs(); | ||||||
13492 | } | ||||||
13493 | |||||||
13494 | if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) | ||||||
13495 | Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) | ||||||
13496 | << DeclSpec::getSpecifierName(TSCS); | ||||||
13497 | if (DS.isInlineSpecified()) | ||||||
13498 | Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
13499 | << getLangOpts().CPlusPlus17; | ||||||
13500 | if (DS.hasConstexprSpecifier()) | ||||||
13501 | Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) | ||||||
13502 | << 0 << D.getDeclSpec().getConstexprSpecifier(); | ||||||
13503 | |||||||
13504 | DiagnoseFunctionSpecifiers(DS); | ||||||
13505 | |||||||
13506 | CheckFunctionOrTemplateParamDeclarator(S, D); | ||||||
13507 | |||||||
13508 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
13509 | QualType parmDeclType = TInfo->getType(); | ||||||
13510 | |||||||
13511 | // Check for redeclaration of parameters, e.g. int foo(int x, int x); | ||||||
13512 | IdentifierInfo *II = D.getIdentifier(); | ||||||
13513 | if (II) { | ||||||
13514 | LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, | ||||||
13515 | ForVisibleRedeclaration); | ||||||
13516 | LookupName(R, S); | ||||||
13517 | if (R.isSingleResult()) { | ||||||
13518 | NamedDecl *PrevDecl = R.getFoundDecl(); | ||||||
13519 | if (PrevDecl->isTemplateParameter()) { | ||||||
13520 | // Maybe we will complain about the shadowed template parameter. | ||||||
13521 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||||
13522 | // Just pretend that we didn't see the previous declaration. | ||||||
13523 | PrevDecl = nullptr; | ||||||
13524 | } else if (S->isDeclScope(PrevDecl)) { | ||||||
13525 | Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; | ||||||
13526 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
13527 | |||||||
13528 | // Recover by removing the name | ||||||
13529 | II = nullptr; | ||||||
13530 | D.SetIdentifier(nullptr, D.getIdentifierLoc()); | ||||||
13531 | D.setInvalidType(true); | ||||||
13532 | } | ||||||
13533 | } | ||||||
13534 | } | ||||||
13535 | |||||||
13536 | // Temporarily put parameter variables in the translation unit, not | ||||||
13537 | // the enclosing context. This prevents them from accidentally | ||||||
13538 | // looking like class members in C++. | ||||||
13539 | ParmVarDecl *New = | ||||||
13540 | CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), | ||||||
13541 | D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); | ||||||
13542 | |||||||
13543 | if (D.isInvalidType()) | ||||||
13544 | New->setInvalidDecl(); | ||||||
13545 | |||||||
13546 | assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void> (0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 13546, __PRETTY_FUNCTION__)); | ||||||
13547 | assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast< void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 13547, __PRETTY_FUNCTION__)); | ||||||
13548 | New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, | ||||||
13549 | S->getNextFunctionPrototypeIndex()); | ||||||
13550 | |||||||
13551 | // Add the parameter declaration into this scope. | ||||||
13552 | S->AddDecl(New); | ||||||
13553 | if (II) | ||||||
13554 | IdResolver.AddDecl(New); | ||||||
13555 | |||||||
13556 | ProcessDeclAttributes(S, New, D); | ||||||
13557 | |||||||
13558 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
13559 | Diag(New->getLocation(), diag::err_module_private_local) | ||||||
13560 | << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
13561 | << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
13562 | |||||||
13563 | if (New->hasAttr<BlocksAttr>()) { | ||||||
13564 | Diag(New->getLocation(), diag::err_block_on_nonlocal); | ||||||
13565 | } | ||||||
13566 | |||||||
13567 | if (getLangOpts().OpenCL) | ||||||
13568 | deduceOpenCLAddressSpace(New); | ||||||
13569 | |||||||
13570 | return New; | ||||||
13571 | } | ||||||
13572 | |||||||
13573 | /// Synthesizes a variable for a parameter arising from a | ||||||
13574 | /// typedef. | ||||||
13575 | ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, | ||||||
13576 | SourceLocation Loc, | ||||||
13577 | QualType T) { | ||||||
13578 | /* FIXME: setting StartLoc == Loc. | ||||||
13579 | Would it be worth to modify callers so as to provide proper source | ||||||
13580 | location for the unnamed parameters, embedding the parameter's type? */ | ||||||
13581 | ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, | ||||||
13582 | T, Context.getTrivialTypeSourceInfo(T, Loc), | ||||||
13583 | SC_None, nullptr); | ||||||
13584 | Param->setImplicit(); | ||||||
13585 | return Param; | ||||||
13586 | } | ||||||
13587 | |||||||
13588 | void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { | ||||||
13589 | // Don't diagnose unused-parameter errors in template instantiations; we | ||||||
13590 | // will already have done so in the template itself. | ||||||
13591 | if (inTemplateInstantiation()) | ||||||
13592 | return; | ||||||
13593 | |||||||
13594 | for (const ParmVarDecl *Parameter : Parameters) { | ||||||
13595 | if (!Parameter->isReferenced() && Parameter->getDeclName() && | ||||||
13596 | !Parameter->hasAttr<UnusedAttr>()) { | ||||||
13597 | Diag(Parameter->getLocation(), diag::warn_unused_parameter) | ||||||
13598 | << Parameter->getDeclName(); | ||||||
13599 | } | ||||||
13600 | } | ||||||
13601 | } | ||||||
13602 | |||||||
13603 | void Sema::DiagnoseSizeOfParametersAndReturnValue( | ||||||
13604 | ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { | ||||||
13605 | if (LangOpts.NumLargeByValueCopy == 0) // No check. | ||||||
13606 | return; | ||||||
13607 | |||||||
13608 | // Warn if the return value is pass-by-value and larger than the specified | ||||||
13609 | // threshold. | ||||||
13610 | if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { | ||||||
13611 | unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); | ||||||
13612 | if (Size > LangOpts.NumLargeByValueCopy) | ||||||
13613 | Diag(D->getLocation(), diag::warn_return_value_size) << D << Size; | ||||||
13614 | } | ||||||
13615 | |||||||
13616 | // Warn if any parameter is pass-by-value and larger than the specified | ||||||
13617 | // threshold. | ||||||
13618 | for (const ParmVarDecl *Parameter : Parameters) { | ||||||
13619 | QualType T = Parameter->getType(); | ||||||
13620 | if (T->isDependentType() || !T.isPODType(Context)) | ||||||
13621 | continue; | ||||||
13622 | unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); | ||||||
13623 | if (Size > LangOpts.NumLargeByValueCopy) | ||||||
13624 | Diag(Parameter->getLocation(), diag::warn_parameter_size) | ||||||
13625 | << Parameter << Size; | ||||||
13626 | } | ||||||
13627 | } | ||||||
13628 | |||||||
13629 | ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, | ||||||
13630 | SourceLocation NameLoc, IdentifierInfo *Name, | ||||||
13631 | QualType T, TypeSourceInfo *TSInfo, | ||||||
13632 | StorageClass SC) { | ||||||
13633 | // In ARC, infer a lifetime qualifier for appropriate parameter types. | ||||||
13634 | if (getLangOpts().ObjCAutoRefCount && | ||||||
13635 | T.getObjCLifetime() == Qualifiers::OCL_None && | ||||||
13636 | T->isObjCLifetimeType()) { | ||||||
13637 | |||||||
13638 | Qualifiers::ObjCLifetime lifetime; | ||||||
13639 | |||||||
13640 | // Special cases for arrays: | ||||||
13641 | // - if it's const, use __unsafe_unretained | ||||||
13642 | // - otherwise, it's an error | ||||||
13643 | if (T->isArrayType()) { | ||||||
13644 | if (!T.isConstQualified()) { | ||||||
13645 | if (DelayedDiagnostics.shouldDelayDiagnostics()) | ||||||
13646 | DelayedDiagnostics.add( | ||||||
13647 | sema::DelayedDiagnostic::makeForbiddenType( | ||||||
13648 | NameLoc, diag::err_arc_array_param_no_ownership, T, false)); | ||||||
13649 | else | ||||||
13650 | Diag(NameLoc, diag::err_arc_array_param_no_ownership) | ||||||
13651 | << TSInfo->getTypeLoc().getSourceRange(); | ||||||
13652 | } | ||||||
13653 | lifetime = Qualifiers::OCL_ExplicitNone; | ||||||
13654 | } else { | ||||||
13655 | lifetime = T->getObjCARCImplicitLifetime(); | ||||||
13656 | } | ||||||
13657 | T = Context.getLifetimeQualifiedType(T, lifetime); | ||||||
13658 | } | ||||||
13659 | |||||||
13660 | ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, | ||||||
13661 | Context.getAdjustedParameterType(T), | ||||||
13662 | TSInfo, SC, nullptr); | ||||||
13663 | |||||||
13664 | // Make a note if we created a new pack in the scope of a lambda, so that | ||||||
13665 | // we know that references to that pack must also be expanded within the | ||||||
13666 | // lambda scope. | ||||||
13667 | if (New->isParameterPack()) | ||||||
13668 | if (auto *LSI = getEnclosingLambda()) | ||||||
13669 | LSI->LocalPacks.push_back(New); | ||||||
13670 | |||||||
13671 | if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || | ||||||
13672 | New->getType().hasNonTrivialToPrimitiveCopyCUnion()) | ||||||
13673 | checkNonTrivialCUnion(New->getType(), New->getLocation(), | ||||||
13674 | NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); | ||||||
13675 | |||||||
13676 | // Parameters can not be abstract class types. | ||||||
13677 | // For record types, this is done by the AbstractClassUsageDiagnoser once | ||||||
13678 | // the class has been completely parsed. | ||||||
13679 | if (!CurContext->isRecord() && | ||||||
13680 | RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, | ||||||
13681 | AbstractParamType)) | ||||||
13682 | New->setInvalidDecl(); | ||||||
13683 | |||||||
13684 | // Parameter declarators cannot be interface types. All ObjC objects are | ||||||
13685 | // passed by reference. | ||||||
13686 | if (T->isObjCObjectType()) { | ||||||
13687 | SourceLocation TypeEndLoc = | ||||||
13688 | getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); | ||||||
13689 | Diag(NameLoc, | ||||||
13690 | diag::err_object_cannot_be_passed_returned_by_value) << 1 << T | ||||||
13691 | << FixItHint::CreateInsertion(TypeEndLoc, "*"); | ||||||
13692 | T = Context.getObjCObjectPointerType(T); | ||||||
13693 | New->setType(T); | ||||||
13694 | } | ||||||
13695 | |||||||
13696 | // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage | ||||||
13697 | // duration shall not be qualified by an address-space qualifier." | ||||||
13698 | // Since all parameters have automatic store duration, they can not have | ||||||
13699 | // an address space. | ||||||
13700 | if (T.getAddressSpace() != LangAS::Default && | ||||||
13701 | // OpenCL allows function arguments declared to be an array of a type | ||||||
13702 | // to be qualified with an address space. | ||||||
13703 | !(getLangOpts().OpenCL && | ||||||
13704 | (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { | ||||||
13705 | Diag(NameLoc, diag::err_arg_with_address_space); | ||||||
13706 | New->setInvalidDecl(); | ||||||
13707 | } | ||||||
13708 | |||||||
13709 | return New; | ||||||
13710 | } | ||||||
13711 | |||||||
13712 | void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, | ||||||
13713 | SourceLocation LocAfterDecls) { | ||||||
13714 | DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); | ||||||
13715 | |||||||
13716 | // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' | ||||||
13717 | // for a K&R function. | ||||||
13718 | if (!FTI.hasPrototype) { | ||||||
13719 | for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { | ||||||
13720 | --i; | ||||||
13721 | if (FTI.Params[i].Param == nullptr) { | ||||||
13722 | SmallString<256> Code; | ||||||
13723 | llvm::raw_svector_ostream(Code) | ||||||
13724 | << " int " << FTI.Params[i].Ident->getName() << ";\n"; | ||||||
13725 | Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) | ||||||
13726 | << FTI.Params[i].Ident | ||||||
13727 | << FixItHint::CreateInsertion(LocAfterDecls, Code); | ||||||
13728 | |||||||
13729 | // Implicitly declare the argument as type 'int' for lack of a better | ||||||
13730 | // type. | ||||||
13731 | AttributeFactory attrs; | ||||||
13732 | DeclSpec DS(attrs); | ||||||
13733 | const char* PrevSpec; // unused | ||||||
13734 | unsigned DiagID; // unused | ||||||
13735 | DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, | ||||||
13736 | DiagID, Context.getPrintingPolicy()); | ||||||
13737 | // Use the identifier location for the type source range. | ||||||
13738 | DS.SetRangeStart(FTI.Params[i].IdentLoc); | ||||||
13739 | DS.SetRangeEnd(FTI.Params[i].IdentLoc); | ||||||
13740 | Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); | ||||||
13741 | ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); | ||||||
13742 | FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); | ||||||
13743 | } | ||||||
13744 | } | ||||||
13745 | } | ||||||
13746 | } | ||||||
13747 | |||||||
13748 | Decl * | ||||||
13749 | Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, | ||||||
13750 | MultiTemplateParamsArg TemplateParameterLists, | ||||||
13751 | SkipBodyInfo *SkipBody) { | ||||||
13752 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 13752, __PRETTY_FUNCTION__)); | ||||||
13753 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 13753, __PRETTY_FUNCTION__)); | ||||||
13754 | Scope *ParentScope = FnBodyScope->getParent(); | ||||||
13755 | |||||||
13756 | // Check if we are in an `omp begin/end declare variant` scope. If we are, and | ||||||
13757 | // we define a non-templated function definition, we will create a declaration | ||||||
13758 | // instead (=BaseFD), and emit the definition with a mangled name afterwards. | ||||||
13759 | // The base function declaration will have the equivalent of an `omp declare | ||||||
13760 | // variant` annotation which specifies the mangled definition as a | ||||||
13761 | // specialization function under the OpenMP context defined as part of the | ||||||
13762 | // `omp begin declare variant`. | ||||||
13763 | SmallVector<FunctionDecl *, 4> Bases; | ||||||
13764 | if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope()) | ||||||
13765 | ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( | ||||||
13766 | ParentScope, D, TemplateParameterLists, Bases); | ||||||
13767 | |||||||
13768 | D.setFunctionDefinitionKind(FDK_Definition); | ||||||
13769 | Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); | ||||||
13770 | Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); | ||||||
13771 | |||||||
13772 | if (!Bases.empty()) | ||||||
13773 | ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases); | ||||||
13774 | |||||||
13775 | return Dcl; | ||||||
13776 | } | ||||||
13777 | |||||||
13778 | void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { | ||||||
13779 | Consumer.HandleInlineFunctionDefinition(D); | ||||||
13780 | } | ||||||
13781 | |||||||
13782 | static bool | ||||||
13783 | ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, | ||||||
13784 | const FunctionDecl *&PossiblePrototype) { | ||||||
13785 | // Don't warn about invalid declarations. | ||||||
13786 | if (FD->isInvalidDecl()) | ||||||
13787 | return false; | ||||||
13788 | |||||||
13789 | // Or declarations that aren't global. | ||||||
13790 | if (!FD->isGlobal()) | ||||||
13791 | return false; | ||||||
13792 | |||||||
13793 | // Don't warn about C++ member functions. | ||||||
13794 | if (isa<CXXMethodDecl>(FD)) | ||||||
13795 | return false; | ||||||
13796 | |||||||
13797 | // Don't warn about 'main'. | ||||||
13798 | if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) | ||||||
13799 | if (IdentifierInfo *II = FD->getIdentifier()) | ||||||
13800 | if (II->isStr("main")) | ||||||
13801 | return false; | ||||||
13802 | |||||||
13803 | // Don't warn about inline functions. | ||||||
13804 | if (FD->isInlined()) | ||||||
13805 | return false; | ||||||
13806 | |||||||
13807 | // Don't warn about function templates. | ||||||
13808 | if (FD->getDescribedFunctionTemplate()) | ||||||
13809 | return false; | ||||||
13810 | |||||||
13811 | // Don't warn about function template specializations. | ||||||
13812 | if (FD->isFunctionTemplateSpecialization()) | ||||||
13813 | return false; | ||||||
13814 | |||||||
13815 | // Don't warn for OpenCL kernels. | ||||||
13816 | if (FD->hasAttr<OpenCLKernelAttr>()) | ||||||
13817 | return false; | ||||||
13818 | |||||||
13819 | // Don't warn on explicitly deleted functions. | ||||||
13820 | if (FD->isDeleted()) | ||||||
13821 | return false; | ||||||
13822 | |||||||
13823 | for (const FunctionDecl *Prev = FD->getPreviousDecl(); | ||||||
13824 | Prev; Prev = Prev->getPreviousDecl()) { | ||||||
13825 | // Ignore any declarations that occur in function or method | ||||||
13826 | // scope, because they aren't visible from the header. | ||||||
13827 | if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) | ||||||
13828 | continue; | ||||||
13829 | |||||||
13830 | PossiblePrototype = Prev; | ||||||
13831 | return Prev->getType()->isFunctionNoProtoType(); | ||||||
13832 | } | ||||||
13833 | |||||||
13834 | return true; | ||||||
13835 | } | ||||||
13836 | |||||||
13837 | void | ||||||
13838 | Sema::CheckForFunctionRedefinition(FunctionDecl *FD, | ||||||
13839 | const FunctionDecl *EffectiveDefinition, | ||||||
13840 | SkipBodyInfo *SkipBody) { | ||||||
13841 | const FunctionDecl *Definition = EffectiveDefinition; | ||||||
13842 | if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { | ||||||
13843 | // If this is a friend function defined in a class template, it does not | ||||||
13844 | // have a body until it is used, nevertheless it is a definition, see | ||||||
13845 | // [temp.inst]p2: | ||||||
13846 | // | ||||||
13847 | // ... for the purpose of determining whether an instantiated redeclaration | ||||||
13848 | // is valid according to [basic.def.odr] and [class.mem], a declaration that | ||||||
13849 | // corresponds to a definition in the template is considered to be a | ||||||
13850 | // definition. | ||||||
13851 | // | ||||||
13852 | // The following code must produce redefinition error: | ||||||
13853 | // | ||||||
13854 | // template<typename T> struct C20 { friend void func_20() {} }; | ||||||
13855 | // C20<int> c20i; | ||||||
13856 | // void func_20() {} | ||||||
13857 | // | ||||||
13858 | for (auto I : FD->redecls()) { | ||||||
13859 | if (I != FD && !I->isInvalidDecl() && | ||||||
13860 | I->getFriendObjectKind() != Decl::FOK_None) { | ||||||
13861 | if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { | ||||||
13862 | if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { | ||||||
13863 | // A merged copy of the same function, instantiated as a member of | ||||||
13864 | // the same class, is OK. | ||||||
13865 | if (declaresSameEntity(OrigFD, Original) && | ||||||
13866 | declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), | ||||||
13867 | cast<Decl>(FD->getLexicalDeclContext()))) | ||||||
13868 | continue; | ||||||
13869 | } | ||||||
13870 | |||||||
13871 | if (Original->isThisDeclarationADefinition()) { | ||||||
13872 | Definition = I; | ||||||
13873 | break; | ||||||
13874 | } | ||||||
13875 | } | ||||||
13876 | } | ||||||
13877 | } | ||||||
13878 | } | ||||||
13879 | |||||||
13880 | if (!Definition) | ||||||
13881 | // Similar to friend functions a friend function template may be a | ||||||
13882 | // definition and do not have a body if it is instantiated in a class | ||||||
13883 | // template. | ||||||
13884 | if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { | ||||||
13885 | for (auto I : FTD->redecls()) { | ||||||
13886 | auto D = cast<FunctionTemplateDecl>(I); | ||||||
13887 | if (D != FTD) { | ||||||
13888 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 13889, __PRETTY_FUNCTION__)) | ||||||
13889 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 13889, __PRETTY_FUNCTION__)); | ||||||
13890 | if (D->getFriendObjectKind() != Decl::FOK_None) | ||||||
13891 | if (FunctionTemplateDecl *FT = | ||||||
13892 | D->getInstantiatedFromMemberTemplate()) { | ||||||
13893 | if (FT->isThisDeclarationADefinition()) { | ||||||
13894 | Definition = D->getTemplatedDecl(); | ||||||
13895 | break; | ||||||
13896 | } | ||||||
13897 | } | ||||||
13898 | } | ||||||
13899 | } | ||||||
13900 | } | ||||||
13901 | |||||||
13902 | if (!Definition) | ||||||
13903 | return; | ||||||
13904 | |||||||
13905 | if (canRedefineFunction(Definition, getLangOpts())) | ||||||
13906 | return; | ||||||
13907 | |||||||
13908 | // Don't emit an error when this is redefinition of a typo-corrected | ||||||
13909 | // definition. | ||||||
13910 | if (TypoCorrectedFunctionDefinitions.count(Definition)) | ||||||
13911 | return; | ||||||
13912 | |||||||
13913 | // If we don't have a visible definition of the function, and it's inline or | ||||||
13914 | // a template, skip the new definition. | ||||||
13915 | if (SkipBody && !hasVisibleDefinition(Definition) && | ||||||
13916 | (Definition->getFormalLinkage() == InternalLinkage || | ||||||
13917 | Definition->isInlined() || | ||||||
13918 | Definition->getDescribedFunctionTemplate() || | ||||||
13919 | Definition->getNumTemplateParameterLists())) { | ||||||
13920 | SkipBody->ShouldSkip = true; | ||||||
13921 | SkipBody->Previous = const_cast<FunctionDecl*>(Definition); | ||||||
13922 | if (auto *TD = Definition->getDescribedFunctionTemplate()) | ||||||
13923 | makeMergedDefinitionVisible(TD); | ||||||
13924 | makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); | ||||||
13925 | return; | ||||||
13926 | } | ||||||
13927 | |||||||
13928 | if (getLangOpts().GNUMode && Definition->isInlineSpecified() && | ||||||
13929 | Definition->getStorageClass() == SC_Extern) | ||||||
13930 | Diag(FD->getLocation(), diag::err_redefinition_extern_inline) | ||||||
13931 | << FD << getLangOpts().CPlusPlus; | ||||||
13932 | else | ||||||
13933 | Diag(FD->getLocation(), diag::err_redefinition) << FD; | ||||||
13934 | |||||||
13935 | Diag(Definition->getLocation(), diag::note_previous_definition); | ||||||
13936 | FD->setInvalidDecl(); | ||||||
13937 | } | ||||||
13938 | |||||||
13939 | static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, | ||||||
13940 | Sema &S) { | ||||||
13941 | CXXRecordDecl *const LambdaClass = CallOperator->getParent(); | ||||||
13942 | |||||||
13943 | LambdaScopeInfo *LSI = S.PushLambdaScope(); | ||||||
13944 | LSI->CallOperator = CallOperator; | ||||||
13945 | LSI->Lambda = LambdaClass; | ||||||
13946 | LSI->ReturnType = CallOperator->getReturnType(); | ||||||
13947 | const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); | ||||||
13948 | |||||||
13949 | if (LCD == LCD_None) | ||||||
13950 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; | ||||||
13951 | else if (LCD == LCD_ByCopy) | ||||||
13952 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; | ||||||
13953 | else if (LCD == LCD_ByRef) | ||||||
13954 | LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; | ||||||
13955 | DeclarationNameInfo DNI = CallOperator->getNameInfo(); | ||||||
13956 | |||||||
13957 | LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); | ||||||
13958 | LSI->Mutable = !CallOperator->isConst(); | ||||||
13959 | |||||||
13960 | // Add the captures to the LSI so they can be noted as already | ||||||
13961 | // captured within tryCaptureVar. | ||||||
13962 | auto I = LambdaClass->field_begin(); | ||||||
13963 | for (const auto &C : LambdaClass->captures()) { | ||||||
13964 | if (C.capturesVariable()) { | ||||||
13965 | VarDecl *VD = C.getCapturedVar(); | ||||||
13966 | if (VD->isInitCapture()) | ||||||
13967 | S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); | ||||||
13968 | const bool ByRef = C.getCaptureKind() == LCK_ByRef; | ||||||
13969 | LSI->addCapture(VD, /*IsBlock*/false, ByRef, | ||||||
13970 | /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), | ||||||
13971 | /*EllipsisLoc*/C.isPackExpansion() | ||||||
13972 | ? C.getEllipsisLoc() : SourceLocation(), | ||||||
13973 | I->getType(), /*Invalid*/false); | ||||||
13974 | |||||||
13975 | } else if (C.capturesThis()) { | ||||||
13976 | LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), | ||||||
13977 | C.getCaptureKind() == LCK_StarThis); | ||||||
13978 | } else { | ||||||
13979 | LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), | ||||||
13980 | I->getType()); | ||||||
13981 | } | ||||||
13982 | ++I; | ||||||
13983 | } | ||||||
13984 | } | ||||||
13985 | |||||||
13986 | Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, | ||||||
13987 | SkipBodyInfo *SkipBody) { | ||||||
13988 | if (!D) { | ||||||
13989 | // Parsing the function declaration failed in some way. Push on a fake scope | ||||||
13990 | // anyway so we can try to parse the function body. | ||||||
13991 | PushFunctionScope(); | ||||||
13992 | PushExpressionEvaluationContext(ExprEvalContexts.back().Context); | ||||||
13993 | return D; | ||||||
13994 | } | ||||||
13995 | |||||||
13996 | FunctionDecl *FD = nullptr; | ||||||
13997 | |||||||
13998 | if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) | ||||||
13999 | FD = FunTmpl->getTemplatedDecl(); | ||||||
14000 | else | ||||||
14001 | FD = cast<FunctionDecl>(D); | ||||||
14002 | |||||||
14003 | // Do not push if it is a lambda because one is already pushed when building | ||||||
14004 | // the lambda in ActOnStartOfLambdaDefinition(). | ||||||
14005 | if (!isLambdaCallOperator(FD)) | ||||||
14006 | PushExpressionEvaluationContext( | ||||||
14007 | FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated | ||||||
14008 | : ExprEvalContexts.back().Context); | ||||||
14009 | |||||||
14010 | // Check for defining attributes before the check for redefinition. | ||||||
14011 | if (const auto *Attr = FD->getAttr<AliasAttr>()) { | ||||||
14012 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; | ||||||
14013 | FD->dropAttr<AliasAttr>(); | ||||||
14014 | FD->setInvalidDecl(); | ||||||
14015 | } | ||||||
14016 | if (const auto *Attr = FD->getAttr<IFuncAttr>()) { | ||||||
14017 | Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; | ||||||
14018 | FD->dropAttr<IFuncAttr>(); | ||||||
14019 | FD->setInvalidDecl(); | ||||||
14020 | } | ||||||
14021 | |||||||
14022 | // See if this is a redefinition. If 'will have body' is already set, then | ||||||
14023 | // these checks were already performed when it was set. | ||||||
14024 | if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { | ||||||
14025 | CheckForFunctionRedefinition(FD, nullptr, SkipBody); | ||||||
14026 | |||||||
14027 | // If we're skipping the body, we're done. Don't enter the scope. | ||||||
14028 | if (SkipBody && SkipBody->ShouldSkip) | ||||||
14029 | return D; | ||||||
14030 | } | ||||||
14031 | |||||||
14032 | // Mark this function as "will have a body eventually". This lets users to | ||||||
14033 | // call e.g. isInlineDefinitionExternallyVisible while we're still parsing | ||||||
14034 | // this function. | ||||||
14035 | FD->setWillHaveBody(); | ||||||
14036 | |||||||
14037 | // If we are instantiating a generic lambda call operator, push | ||||||
14038 | // a LambdaScopeInfo onto the function stack. But use the information | ||||||
14039 | // that's already been calculated (ActOnLambdaExpr) to prime the current | ||||||
14040 | // LambdaScopeInfo. | ||||||
14041 | // When the template operator is being specialized, the LambdaScopeInfo, | ||||||
14042 | // has to be properly restored so that tryCaptureVariable doesn't try | ||||||
14043 | // and capture any new variables. In addition when calculating potential | ||||||
14044 | // captures during transformation of nested lambdas, it is necessary to | ||||||
14045 | // have the LSI properly restored. | ||||||
14046 | if (isGenericLambdaCallOperatorSpecialization(FD)) { | ||||||
14047 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14049, __PRETTY_FUNCTION__)) | ||||||
14048 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14049, __PRETTY_FUNCTION__)) | ||||||
14049 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14049, __PRETTY_FUNCTION__)); | ||||||
14050 | RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); | ||||||
14051 | } else { | ||||||
14052 | // Enter a new function scope | ||||||
14053 | PushFunctionScope(); | ||||||
14054 | } | ||||||
14055 | |||||||
14056 | // Builtin functions cannot be defined. | ||||||
14057 | if (unsigned BuiltinID = FD->getBuiltinID()) { | ||||||
14058 | if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && | ||||||
14059 | !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { | ||||||
14060 | Diag(FD->getLocation(), diag::err_builtin_definition) << FD; | ||||||
14061 | FD->setInvalidDecl(); | ||||||
14062 | } | ||||||
14063 | } | ||||||
14064 | |||||||
14065 | // The return type of a function definition must be complete | ||||||
14066 | // (C99 6.9.1p3, C++ [dcl.fct]p6). | ||||||
14067 | QualType ResultType = FD->getReturnType(); | ||||||
14068 | if (!ResultType->isDependentType() && !ResultType->isVoidType() && | ||||||
14069 | !FD->isInvalidDecl() && | ||||||
14070 | RequireCompleteType(FD->getLocation(), ResultType, | ||||||
14071 | diag::err_func_def_incomplete_result)) | ||||||
14072 | FD->setInvalidDecl(); | ||||||
14073 | |||||||
14074 | if (FnBodyScope) | ||||||
14075 | PushDeclContext(FnBodyScope, FD); | ||||||
14076 | |||||||
14077 | // Check the validity of our function parameters | ||||||
14078 | CheckParmsForFunctionDef(FD->parameters(), | ||||||
14079 | /*CheckParameterNames=*/true); | ||||||
14080 | |||||||
14081 | // Add non-parameter declarations already in the function to the current | ||||||
14082 | // scope. | ||||||
14083 | if (FnBodyScope) { | ||||||
14084 | for (Decl *NPD : FD->decls()) { | ||||||
14085 | auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); | ||||||
14086 | if (!NonParmDecl) | ||||||
14087 | continue; | ||||||
14088 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14089, __PRETTY_FUNCTION__)) | ||||||
14089 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14089, __PRETTY_FUNCTION__)); | ||||||
14090 | |||||||
14091 | // If the decl has a name, make it accessible in the current scope. | ||||||
14092 | if (NonParmDecl->getDeclName()) | ||||||
14093 | PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); | ||||||
14094 | |||||||
14095 | // Similarly, dive into enums and fish their constants out, making them | ||||||
14096 | // accessible in this scope. | ||||||
14097 | if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { | ||||||
14098 | for (auto *EI : ED->enumerators()) | ||||||
14099 | PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); | ||||||
14100 | } | ||||||
14101 | } | ||||||
14102 | } | ||||||
14103 | |||||||
14104 | // Introduce our parameters into the function scope | ||||||
14105 | for (auto Param : FD->parameters()) { | ||||||
14106 | Param->setOwningFunction(FD); | ||||||
14107 | |||||||
14108 | // If this has an identifier, add it to the scope stack. | ||||||
14109 | if (Param->getIdentifier() && FnBodyScope) { | ||||||
14110 | CheckShadow(FnBodyScope, Param); | ||||||
14111 | |||||||
14112 | PushOnScopeChains(Param, FnBodyScope); | ||||||
14113 | } | ||||||
14114 | } | ||||||
14115 | |||||||
14116 | // Ensure that the function's exception specification is instantiated. | ||||||
14117 | if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) | ||||||
14118 | ResolveExceptionSpec(D->getLocation(), FPT); | ||||||
14119 | |||||||
14120 | // dllimport cannot be applied to non-inline function definitions. | ||||||
14121 | if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && | ||||||
14122 | !FD->isTemplateInstantiation()) { | ||||||
14123 | assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void > (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14123, __PRETTY_FUNCTION__)); | ||||||
14124 | Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); | ||||||
14125 | FD->setInvalidDecl(); | ||||||
14126 | return D; | ||||||
14127 | } | ||||||
14128 | // We want to attach documentation to original Decl (which might be | ||||||
14129 | // a function template). | ||||||
14130 | ActOnDocumentableDecl(D); | ||||||
14131 | if (getCurLexicalContext()->isObjCContainer() && | ||||||
14132 | getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && | ||||||
14133 | getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) | ||||||
14134 | Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); | ||||||
14135 | |||||||
14136 | return D; | ||||||
14137 | } | ||||||
14138 | |||||||
14139 | /// Given the set of return statements within a function body, | ||||||
14140 | /// compute the variables that are subject to the named return value | ||||||
14141 | /// optimization. | ||||||
14142 | /// | ||||||
14143 | /// Each of the variables that is subject to the named return value | ||||||
14144 | /// optimization will be marked as NRVO variables in the AST, and any | ||||||
14145 | /// return statement that has a marked NRVO variable as its NRVO candidate can | ||||||
14146 | /// use the named return value optimization. | ||||||
14147 | /// | ||||||
14148 | /// This function applies a very simplistic algorithm for NRVO: if every return | ||||||
14149 | /// statement in the scope of a variable has the same NRVO candidate, that | ||||||
14150 | /// candidate is an NRVO variable. | ||||||
14151 | void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { | ||||||
14152 | ReturnStmt **Returns = Scope->Returns.data(); | ||||||
14153 | |||||||
14154 | for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { | ||||||
14155 | if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { | ||||||
14156 | if (!NRVOCandidate->isNRVOVariable()) | ||||||
14157 | Returns[I]->setNRVOCandidate(nullptr); | ||||||
14158 | } | ||||||
14159 | } | ||||||
14160 | } | ||||||
14161 | |||||||
14162 | bool Sema::canDelayFunctionBody(const Declarator &D) { | ||||||
14163 | // We can't delay parsing the body of a constexpr function template (yet). | ||||||
14164 | if (D.getDeclSpec().hasConstexprSpecifier()) | ||||||
14165 | return false; | ||||||
14166 | |||||||
14167 | // We can't delay parsing the body of a function template with a deduced | ||||||
14168 | // return type (yet). | ||||||
14169 | if (D.getDeclSpec().hasAutoTypeSpec()) { | ||||||
14170 | // If the placeholder introduces a non-deduced trailing return type, | ||||||
14171 | // we can still delay parsing it. | ||||||
14172 | if (D.getNumTypeObjects()) { | ||||||
14173 | const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); | ||||||
14174 | if (Outer.Kind == DeclaratorChunk::Function && | ||||||
14175 | Outer.Fun.hasTrailingReturnType()) { | ||||||
14176 | QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); | ||||||
14177 | return Ty.isNull() || !Ty->isUndeducedType(); | ||||||
14178 | } | ||||||
14179 | } | ||||||
14180 | return false; | ||||||
14181 | } | ||||||
14182 | |||||||
14183 | return true; | ||||||
14184 | } | ||||||
14185 | |||||||
14186 | bool Sema::canSkipFunctionBody(Decl *D) { | ||||||
14187 | // We cannot skip the body of a function (or function template) which is | ||||||
14188 | // constexpr, since we may need to evaluate its body in order to parse the | ||||||
14189 | // rest of the file. | ||||||
14190 | // We cannot skip the body of a function with an undeduced return type, | ||||||
14191 | // because any callers of that function need to know the type. | ||||||
14192 | if (const FunctionDecl *FD = D->getAsFunction()) { | ||||||
14193 | if (FD->isConstexpr()) | ||||||
14194 | return false; | ||||||
14195 | // We can't simply call Type::isUndeducedType here, because inside template | ||||||
14196 | // auto can be deduced to a dependent type, which is not considered | ||||||
14197 | // "undeduced". | ||||||
14198 | if (FD->getReturnType()->getContainedDeducedType()) | ||||||
14199 | return false; | ||||||
14200 | } | ||||||
14201 | return Consumer.shouldSkipFunctionBody(D); | ||||||
14202 | } | ||||||
14203 | |||||||
14204 | Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { | ||||||
14205 | if (!Decl) | ||||||
14206 | return nullptr; | ||||||
14207 | if (FunctionDecl *FD = Decl->getAsFunction()) | ||||||
14208 | FD->setHasSkippedBody(); | ||||||
14209 | else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) | ||||||
14210 | MD->setHasSkippedBody(); | ||||||
14211 | return Decl; | ||||||
14212 | } | ||||||
14213 | |||||||
14214 | Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { | ||||||
14215 | return ActOnFinishFunctionBody(D, BodyArg, false); | ||||||
14216 | } | ||||||
14217 | |||||||
14218 | /// RAII object that pops an ExpressionEvaluationContext when exiting a function | ||||||
14219 | /// body. | ||||||
14220 | class ExitFunctionBodyRAII { | ||||||
14221 | public: | ||||||
14222 | ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} | ||||||
14223 | ~ExitFunctionBodyRAII() { | ||||||
14224 | if (!IsLambda) | ||||||
14225 | S.PopExpressionEvaluationContext(); | ||||||
14226 | } | ||||||
14227 | |||||||
14228 | private: | ||||||
14229 | Sema &S; | ||||||
14230 | bool IsLambda = false; | ||||||
14231 | }; | ||||||
14232 | |||||||
14233 | static void diagnoseImplicitlyRetainedSelf(Sema &S) { | ||||||
14234 | llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; | ||||||
14235 | |||||||
14236 | auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { | ||||||
14237 | if (EscapeInfo.count(BD)) | ||||||
14238 | return EscapeInfo[BD]; | ||||||
14239 | |||||||
14240 | bool R = false; | ||||||
14241 | const BlockDecl *CurBD = BD; | ||||||
14242 | |||||||
14243 | do { | ||||||
14244 | R = !CurBD->doesNotEscape(); | ||||||
14245 | if (R) | ||||||
14246 | break; | ||||||
14247 | CurBD = CurBD->getParent()->getInnermostBlockDecl(); | ||||||
14248 | } while (CurBD); | ||||||
14249 | |||||||
14250 | return EscapeInfo[BD] = R; | ||||||
14251 | }; | ||||||
14252 | |||||||
14253 | // If the location where 'self' is implicitly retained is inside a escaping | ||||||
14254 | // block, emit a diagnostic. | ||||||
14255 | for (const std::pair<SourceLocation, const BlockDecl *> &P : | ||||||
14256 | S.ImplicitlyRetainedSelfLocs) | ||||||
14257 | if (IsOrNestedInEscapingBlock(P.second)) | ||||||
14258 | S.Diag(P.first, diag::warn_implicitly_retains_self) | ||||||
14259 | << FixItHint::CreateInsertion(P.first, "self->"); | ||||||
14260 | } | ||||||
14261 | |||||||
14262 | Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, | ||||||
14263 | bool IsInstantiation) { | ||||||
14264 | FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; | ||||||
14265 | |||||||
14266 | sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); | ||||||
14267 | sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; | ||||||
14268 | |||||||
14269 | if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) | ||||||
14270 | CheckCompletedCoroutineBody(FD, Body); | ||||||
14271 | |||||||
14272 | // Do not call PopExpressionEvaluationContext() if it is a lambda because one | ||||||
14273 | // is already popped when finishing the lambda in BuildLambdaExpr(). This is | ||||||
14274 | // meant to pop the context added in ActOnStartOfFunctionDef(). | ||||||
14275 | ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); | ||||||
14276 | |||||||
14277 | if (FD) { | ||||||
14278 | FD->setBody(Body); | ||||||
14279 | FD->setWillHaveBody(false); | ||||||
14280 | |||||||
14281 | if (getLangOpts().CPlusPlus14) { | ||||||
14282 | if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && | ||||||
14283 | FD->getReturnType()->isUndeducedType()) { | ||||||
14284 | // If the function has a deduced result type but contains no 'return' | ||||||
14285 | // statements, the result type as written must be exactly 'auto', and | ||||||
14286 | // the deduced result type is 'void'. | ||||||
14287 | if (!FD->getReturnType()->getAs<AutoType>()) { | ||||||
14288 | Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) | ||||||
14289 | << FD->getReturnType(); | ||||||
14290 | FD->setInvalidDecl(); | ||||||
14291 | } else { | ||||||
14292 | // Substitute 'void' for the 'auto' in the type. | ||||||
14293 | TypeLoc ResultType = getReturnTypeLoc(FD); | ||||||
14294 | Context.adjustDeducedFunctionResultType( | ||||||
14295 | FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); | ||||||
14296 | } | ||||||
14297 | } | ||||||
14298 | } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { | ||||||
14299 | // In C++11, we don't use 'auto' deduction rules for lambda call | ||||||
14300 | // operators because we don't support return type deduction. | ||||||
14301 | auto *LSI = getCurLambda(); | ||||||
14302 | if (LSI->HasImplicitReturnType) { | ||||||
14303 | deduceClosureReturnType(*LSI); | ||||||
14304 | |||||||
14305 | // C++11 [expr.prim.lambda]p4: | ||||||
14306 | // [...] if there are no return statements in the compound-statement | ||||||
14307 | // [the deduced type is] the type void | ||||||
14308 | QualType RetType = | ||||||
14309 | LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; | ||||||
14310 | |||||||
14311 | // Update the return type to the deduced type. | ||||||
14312 | const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); | ||||||
14313 | FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), | ||||||
14314 | Proto->getExtProtoInfo())); | ||||||
14315 | } | ||||||
14316 | } | ||||||
14317 | |||||||
14318 | // If the function implicitly returns zero (like 'main') or is naked, | ||||||
14319 | // don't complain about missing return statements. | ||||||
14320 | if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) | ||||||
14321 | WP.disableCheckFallThrough(); | ||||||
14322 | |||||||
14323 | // MSVC permits the use of pure specifier (=0) on function definition, | ||||||
14324 | // defined at class scope, warn about this non-standard construct. | ||||||
14325 | if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) | ||||||
14326 | Diag(FD->getLocation(), diag::ext_pure_function_definition); | ||||||
14327 | |||||||
14328 | if (!FD->isInvalidDecl()) { | ||||||
14329 | // Don't diagnose unused parameters of defaulted or deleted functions. | ||||||
14330 | if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) | ||||||
14331 | DiagnoseUnusedParameters(FD->parameters()); | ||||||
14332 | DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), | ||||||
14333 | FD->getReturnType(), FD); | ||||||
14334 | |||||||
14335 | // If this is a structor, we need a vtable. | ||||||
14336 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) | ||||||
14337 | MarkVTableUsed(FD->getLocation(), Constructor->getParent()); | ||||||
14338 | else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) | ||||||
14339 | MarkVTableUsed(FD->getLocation(), Destructor->getParent()); | ||||||
14340 | |||||||
14341 | // Try to apply the named return value optimization. We have to check | ||||||
14342 | // if we can do this here because lambdas keep return statements around | ||||||
14343 | // to deduce an implicit return type. | ||||||
14344 | if (FD->getReturnType()->isRecordType() && | ||||||
14345 | (!getLangOpts().CPlusPlus || !FD->isDependentContext())) | ||||||
14346 | computeNRVO(Body, getCurFunction()); | ||||||
14347 | } | ||||||
14348 | |||||||
14349 | // GNU warning -Wmissing-prototypes: | ||||||
14350 | // Warn if a global function is defined without a previous | ||||||
14351 | // prototype declaration. This warning is issued even if the | ||||||
14352 | // definition itself provides a prototype. The aim is to detect | ||||||
14353 | // global functions that fail to be declared in header files. | ||||||
14354 | const FunctionDecl *PossiblePrototype = nullptr; | ||||||
14355 | if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { | ||||||
14356 | Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; | ||||||
14357 | |||||||
14358 | if (PossiblePrototype) { | ||||||
14359 | // We found a declaration that is not a prototype, | ||||||
14360 | // but that could be a zero-parameter prototype | ||||||
14361 | if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { | ||||||
14362 | TypeLoc TL = TI->getTypeLoc(); | ||||||
14363 | if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) | ||||||
14364 | Diag(PossiblePrototype->getLocation(), | ||||||
14365 | diag::note_declaration_not_a_prototype) | ||||||
14366 | << (FD->getNumParams() != 0) | ||||||
14367 | << (FD->getNumParams() == 0 | ||||||
14368 | ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") | ||||||
14369 | : FixItHint{}); | ||||||
14370 | } | ||||||
14371 | } else { | ||||||
14372 | // Returns true if the token beginning at this Loc is `const`. | ||||||
14373 | auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM, | ||||||
14374 | const LangOptions &LangOpts) { | ||||||
14375 | std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); | ||||||
14376 | if (LocInfo.first.isInvalid()) | ||||||
14377 | return false; | ||||||
14378 | |||||||
14379 | bool Invalid = false; | ||||||
14380 | StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); | ||||||
14381 | if (Invalid) | ||||||
14382 | return false; | ||||||
14383 | |||||||
14384 | if (LocInfo.second > Buffer.size()) | ||||||
14385 | return false; | ||||||
14386 | |||||||
14387 | const char *LexStart = Buffer.data() + LocInfo.second; | ||||||
14388 | StringRef StartTok(LexStart, Buffer.size() - LocInfo.second); | ||||||
14389 | |||||||
14390 | return StartTok.consume_front("const") && | ||||||
14391 | (StartTok.empty() || isWhitespace(StartTok[0]) || | ||||||
14392 | StartTok.startswith("/*") || StartTok.startswith("//")); | ||||||
14393 | }; | ||||||
14394 | |||||||
14395 | auto findBeginLoc = [&]() { | ||||||
14396 | // If the return type has `const` qualifier, we want to insert | ||||||
14397 | // `static` before `const` (and not before the typename). | ||||||
14398 | if ((FD->getReturnType()->isAnyPointerType() && | ||||||
14399 | FD->getReturnType()->getPointeeType().isConstQualified()) || | ||||||
14400 | FD->getReturnType().isConstQualified()) { | ||||||
14401 | // But only do this if we can determine where the `const` is. | ||||||
14402 | |||||||
14403 | if (isLocAtConst(FD->getBeginLoc(), getSourceManager(), | ||||||
14404 | getLangOpts())) | ||||||
14405 | |||||||
14406 | return FD->getBeginLoc(); | ||||||
14407 | } | ||||||
14408 | return FD->getTypeSpecStartLoc(); | ||||||
14409 | }; | ||||||
14410 | Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) | ||||||
14411 | << /* function */ 1 | ||||||
14412 | << (FD->getStorageClass() == SC_None | ||||||
14413 | ? FixItHint::CreateInsertion(findBeginLoc(), "static ") | ||||||
14414 | : FixItHint{}); | ||||||
14415 | } | ||||||
14416 | |||||||
14417 | // GNU warning -Wstrict-prototypes | ||||||
14418 | // Warn if K&R function is defined without a previous declaration. | ||||||
14419 | // This warning is issued only if the definition itself does not provide | ||||||
14420 | // a prototype. Only K&R definitions do not provide a prototype. | ||||||
14421 | if (!FD->hasWrittenPrototype()) { | ||||||
14422 | TypeSourceInfo *TI = FD->getTypeSourceInfo(); | ||||||
14423 | TypeLoc TL = TI->getTypeLoc(); | ||||||
14424 | FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); | ||||||
14425 | Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; | ||||||
14426 | } | ||||||
14427 | } | ||||||
14428 | |||||||
14429 | // Warn on CPUDispatch with an actual body. | ||||||
14430 | if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) | ||||||
14431 | if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) | ||||||
14432 | if (!CmpndBody->body_empty()) | ||||||
14433 | Diag(CmpndBody->body_front()->getBeginLoc(), | ||||||
14434 | diag::warn_dispatch_body_ignored); | ||||||
14435 | |||||||
14436 | if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { | ||||||
14437 | const CXXMethodDecl *KeyFunction; | ||||||
14438 | if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && | ||||||
14439 | MD->isVirtual() && | ||||||
14440 | (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && | ||||||
14441 | MD == KeyFunction->getCanonicalDecl()) { | ||||||
14442 | // Update the key-function state if necessary for this ABI. | ||||||
14443 | if (FD->isInlined() && | ||||||
14444 | !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { | ||||||
14445 | Context.setNonKeyFunction(MD); | ||||||
14446 | |||||||
14447 | // If the newly-chosen key function is already defined, then we | ||||||
14448 | // need to mark the vtable as used retroactively. | ||||||
14449 | KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); | ||||||
14450 | const FunctionDecl *Definition; | ||||||
14451 | if (KeyFunction && KeyFunction->isDefined(Definition)) | ||||||
14452 | MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); | ||||||
14453 | } else { | ||||||
14454 | // We just defined they key function; mark the vtable as used. | ||||||
14455 | MarkVTableUsed(FD->getLocation(), MD->getParent(), true); | ||||||
14456 | } | ||||||
14457 | } | ||||||
14458 | } | ||||||
14459 | |||||||
14460 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14461, __PRETTY_FUNCTION__)) | ||||||
14461 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14461, __PRETTY_FUNCTION__)); | ||||||
14462 | } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { | ||||||
14463 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14463, __PRETTY_FUNCTION__)); | ||||||
14464 | MD->setBody(Body); | ||||||
14465 | if (!MD->isInvalidDecl()) { | ||||||
14466 | DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), | ||||||
14467 | MD->getReturnType(), MD); | ||||||
14468 | |||||||
14469 | if (Body) | ||||||
14470 | computeNRVO(Body, getCurFunction()); | ||||||
14471 | } | ||||||
14472 | if (getCurFunction()->ObjCShouldCallSuper) { | ||||||
14473 | Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) | ||||||
14474 | << MD->getSelector().getAsString(); | ||||||
14475 | getCurFunction()->ObjCShouldCallSuper = false; | ||||||
14476 | } | ||||||
14477 | if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { | ||||||
14478 | const ObjCMethodDecl *InitMethod = nullptr; | ||||||
14479 | bool isDesignated = | ||||||
14480 | MD->isDesignatedInitializerForTheInterface(&InitMethod); | ||||||
14481 | assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void> (0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14481, __PRETTY_FUNCTION__)); | ||||||
14482 | (void)isDesignated; | ||||||
14483 | |||||||
14484 | auto superIsNSObject = [&](const ObjCMethodDecl *MD) { | ||||||
14485 | auto IFace = MD->getClassInterface(); | ||||||
14486 | if (!IFace) | ||||||
14487 | return false; | ||||||
14488 | auto SuperD = IFace->getSuperClass(); | ||||||
14489 | if (!SuperD) | ||||||
14490 | return false; | ||||||
14491 | return SuperD->getIdentifier() == | ||||||
14492 | NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); | ||||||
14493 | }; | ||||||
14494 | // Don't issue this warning for unavailable inits or direct subclasses | ||||||
14495 | // of NSObject. | ||||||
14496 | if (!MD->isUnavailable() && !superIsNSObject(MD)) { | ||||||
14497 | Diag(MD->getLocation(), | ||||||
14498 | diag::warn_objc_designated_init_missing_super_call); | ||||||
14499 | Diag(InitMethod->getLocation(), | ||||||
14500 | diag::note_objc_designated_init_marked_here); | ||||||
14501 | } | ||||||
14502 | getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; | ||||||
14503 | } | ||||||
14504 | if (getCurFunction()->ObjCWarnForNoInitDelegation) { | ||||||
14505 | // Don't issue this warning for unavaialable inits. | ||||||
14506 | if (!MD->isUnavailable()) | ||||||
14507 | Diag(MD->getLocation(), | ||||||
14508 | diag::warn_objc_secondary_init_missing_init_call); | ||||||
14509 | getCurFunction()->ObjCWarnForNoInitDelegation = false; | ||||||
14510 | } | ||||||
14511 | |||||||
14512 | diagnoseImplicitlyRetainedSelf(*this); | ||||||
14513 | } else { | ||||||
14514 | // Parsing the function declaration failed in some way. Pop the fake scope | ||||||
14515 | // we pushed on. | ||||||
14516 | PopFunctionScopeInfo(ActivePolicy, dcl); | ||||||
14517 | return nullptr; | ||||||
14518 | } | ||||||
14519 | |||||||
14520 | if (Body && getCurFunction()->HasPotentialAvailabilityViolations) | ||||||
14521 | DiagnoseUnguardedAvailabilityViolations(dcl); | ||||||
14522 | |||||||
14523 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14525, __PRETTY_FUNCTION__)) | ||||||
14524 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14525, __PRETTY_FUNCTION__)) | ||||||
14525 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14525, __PRETTY_FUNCTION__)); | ||||||
14526 | |||||||
14527 | // Verify and clean out per-function state. | ||||||
14528 | if (Body && (!FD || !FD->isDefaulted())) { | ||||||
14529 | // C++ constructors that have function-try-blocks can't have return | ||||||
14530 | // statements in the handlers of that block. (C++ [except.handle]p14) | ||||||
14531 | // Verify this. | ||||||
14532 | if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) | ||||||
14533 | DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); | ||||||
14534 | |||||||
14535 | // Verify that gotos and switch cases don't jump into scopes illegally. | ||||||
14536 | if (getCurFunction()->NeedsScopeChecking() && | ||||||
14537 | !PP.isCodeCompletionEnabled()) | ||||||
14538 | DiagnoseInvalidJumps(Body); | ||||||
14539 | |||||||
14540 | if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { | ||||||
14541 | if (!Destructor->getParent()->isDependentType()) | ||||||
14542 | CheckDestructor(Destructor); | ||||||
14543 | |||||||
14544 | MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), | ||||||
14545 | Destructor->getParent()); | ||||||
14546 | } | ||||||
14547 | |||||||
14548 | // If any errors have occurred, clear out any temporaries that may have | ||||||
14549 | // been leftover. This ensures that these temporaries won't be picked up for | ||||||
14550 | // deletion in some later function. | ||||||
14551 | if (getDiagnostics().hasUncompilableErrorOccurred() || | ||||||
14552 | getDiagnostics().getSuppressAllDiagnostics()) { | ||||||
14553 | DiscardCleanupsInEvaluationContext(); | ||||||
14554 | } | ||||||
14555 | if (!getDiagnostics().hasUncompilableErrorOccurred() && | ||||||
14556 | !isa<FunctionTemplateDecl>(dcl)) { | ||||||
14557 | // Since the body is valid, issue any analysis-based warnings that are | ||||||
14558 | // enabled. | ||||||
14559 | ActivePolicy = &WP; | ||||||
14560 | } | ||||||
14561 | |||||||
14562 | if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && | ||||||
14563 | !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) | ||||||
14564 | FD->setInvalidDecl(); | ||||||
14565 | |||||||
14566 | if (FD && FD->hasAttr<NakedAttr>()) { | ||||||
14567 | for (const Stmt *S : Body->children()) { | ||||||
14568 | // Allow local register variables without initializer as they don't | ||||||
14569 | // require prologue. | ||||||
14570 | bool RegisterVariables = false; | ||||||
14571 | if (auto *DS = dyn_cast<DeclStmt>(S)) { | ||||||
14572 | for (const auto *Decl : DS->decls()) { | ||||||
14573 | if (const auto *Var = dyn_cast<VarDecl>(Decl)) { | ||||||
14574 | RegisterVariables = | ||||||
14575 | Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); | ||||||
14576 | if (!RegisterVariables) | ||||||
14577 | break; | ||||||
14578 | } | ||||||
14579 | } | ||||||
14580 | } | ||||||
14581 | if (RegisterVariables) | ||||||
14582 | continue; | ||||||
14583 | if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { | ||||||
14584 | Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); | ||||||
14585 | Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); | ||||||
14586 | FD->setInvalidDecl(); | ||||||
14587 | break; | ||||||
14588 | } | ||||||
14589 | } | ||||||
14590 | } | ||||||
14591 | |||||||
14592 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14594, __PRETTY_FUNCTION__)) | ||||||
14593 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14594, __PRETTY_FUNCTION__)) | ||||||
14594 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14594, __PRETTY_FUNCTION__)); | ||||||
14595 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14595, __PRETTY_FUNCTION__)); | ||||||
14596 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14597, __PRETTY_FUNCTION__)) | ||||||
14597 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14597, __PRETTY_FUNCTION__)); | ||||||
14598 | } | ||||||
14599 | |||||||
14600 | if (!IsInstantiation) | ||||||
14601 | PopDeclContext(); | ||||||
14602 | |||||||
14603 | PopFunctionScopeInfo(ActivePolicy, dcl); | ||||||
14604 | // If any errors have occurred, clear out any temporaries that may have | ||||||
14605 | // been leftover. This ensures that these temporaries won't be picked up for | ||||||
14606 | // deletion in some later function. | ||||||
14607 | if (getDiagnostics().hasUncompilableErrorOccurred()) { | ||||||
14608 | DiscardCleanupsInEvaluationContext(); | ||||||
14609 | } | ||||||
14610 | |||||||
14611 | if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) { | ||||||
14612 | auto ES = getEmissionStatus(FD); | ||||||
14613 | if (ES == Sema::FunctionEmissionStatus::Emitted || | ||||||
14614 | ES == Sema::FunctionEmissionStatus::Unknown) | ||||||
14615 | DeclsToCheckForDeferredDiags.push_back(FD); | ||||||
14616 | } | ||||||
14617 | |||||||
14618 | return dcl; | ||||||
14619 | } | ||||||
14620 | |||||||
14621 | /// When we finish delayed parsing of an attribute, we must attach it to the | ||||||
14622 | /// relevant Decl. | ||||||
14623 | void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, | ||||||
14624 | ParsedAttributes &Attrs) { | ||||||
14625 | // Always attach attributes to the underlying decl. | ||||||
14626 | if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) | ||||||
14627 | D = TD->getTemplatedDecl(); | ||||||
14628 | ProcessDeclAttributeList(S, D, Attrs); | ||||||
14629 | |||||||
14630 | if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) | ||||||
14631 | if (Method->isStatic()) | ||||||
14632 | checkThisInStaticMemberFunctionAttributes(Method); | ||||||
14633 | } | ||||||
14634 | |||||||
14635 | /// ImplicitlyDefineFunction - An undeclared identifier was used in a function | ||||||
14636 | /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). | ||||||
14637 | NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, | ||||||
14638 | IdentifierInfo &II, Scope *S) { | ||||||
14639 | // Find the scope in which the identifier is injected and the corresponding | ||||||
14640 | // DeclContext. | ||||||
14641 | // FIXME: C89 does not say what happens if there is no enclosing block scope. | ||||||
14642 | // In that case, we inject the declaration into the translation unit scope | ||||||
14643 | // instead. | ||||||
14644 | Scope *BlockScope = S; | ||||||
14645 | while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) | ||||||
14646 | BlockScope = BlockScope->getParent(); | ||||||
14647 | |||||||
14648 | Scope *ContextScope = BlockScope; | ||||||
14649 | while (!ContextScope->getEntity()) | ||||||
14650 | ContextScope = ContextScope->getParent(); | ||||||
14651 | ContextRAII SavedContext(*this, ContextScope->getEntity()); | ||||||
14652 | |||||||
14653 | // Before we produce a declaration for an implicitly defined | ||||||
14654 | // function, see whether there was a locally-scoped declaration of | ||||||
14655 | // this name as a function or variable. If so, use that | ||||||
14656 | // (non-visible) declaration, and complain about it. | ||||||
14657 | NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); | ||||||
14658 | if (ExternCPrev) { | ||||||
14659 | // We still need to inject the function into the enclosing block scope so | ||||||
14660 | // that later (non-call) uses can see it. | ||||||
14661 | PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); | ||||||
14662 | |||||||
14663 | // C89 footnote 38: | ||||||
14664 | // If in fact it is not defined as having type "function returning int", | ||||||
14665 | // the behavior is undefined. | ||||||
14666 | if (!isa<FunctionDecl>(ExternCPrev) || | ||||||
14667 | !Context.typesAreCompatible( | ||||||
14668 | cast<FunctionDecl>(ExternCPrev)->getType(), | ||||||
14669 | Context.getFunctionNoProtoType(Context.IntTy))) { | ||||||
14670 | Diag(Loc, diag::ext_use_out_of_scope_declaration) | ||||||
14671 | << ExternCPrev << !getLangOpts().C99; | ||||||
14672 | Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); | ||||||
14673 | return ExternCPrev; | ||||||
14674 | } | ||||||
14675 | } | ||||||
14676 | |||||||
14677 | // Extension in C99. Legal in C90, but warn about it. | ||||||
14678 | unsigned diag_id; | ||||||
14679 | if (II.getName().startswith("__builtin_")) | ||||||
14680 | diag_id = diag::warn_builtin_unknown; | ||||||
14681 | // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. | ||||||
14682 | else if (getLangOpts().OpenCL) | ||||||
14683 | diag_id = diag::err_opencl_implicit_function_decl; | ||||||
14684 | else if (getLangOpts().C99) | ||||||
14685 | diag_id = diag::ext_implicit_function_decl; | ||||||
14686 | else | ||||||
14687 | diag_id = diag::warn_implicit_function_decl; | ||||||
14688 | Diag(Loc, diag_id) << &II; | ||||||
14689 | |||||||
14690 | // If we found a prior declaration of this function, don't bother building | ||||||
14691 | // another one. We've already pushed that one into scope, so there's nothing | ||||||
14692 | // more to do. | ||||||
14693 | if (ExternCPrev) | ||||||
14694 | return ExternCPrev; | ||||||
14695 | |||||||
14696 | // Because typo correction is expensive, only do it if the implicit | ||||||
14697 | // function declaration is going to be treated as an error. | ||||||
14698 | if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { | ||||||
14699 | TypoCorrection Corrected; | ||||||
14700 | DeclFilterCCC<FunctionDecl> CCC{}; | ||||||
14701 | if (S && (Corrected = | ||||||
14702 | CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, | ||||||
14703 | S, nullptr, CCC, CTK_NonError))) | ||||||
14704 | diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), | ||||||
14705 | /*ErrorRecovery*/false); | ||||||
14706 | } | ||||||
14707 | |||||||
14708 | // Set a Declarator for the implicit definition: int foo(); | ||||||
14709 | const char *Dummy; | ||||||
14710 | AttributeFactory attrFactory; | ||||||
14711 | DeclSpec DS(attrFactory); | ||||||
14712 | unsigned DiagID; | ||||||
14713 | bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, | ||||||
14714 | Context.getPrintingPolicy()); | ||||||
14715 | (void)Error; // Silence warning. | ||||||
14716 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14716, __PRETTY_FUNCTION__)); | ||||||
14717 | SourceLocation NoLoc; | ||||||
14718 | Declarator D(DS, DeclaratorContext::BlockContext); | ||||||
14719 | D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, | ||||||
14720 | /*IsAmbiguous=*/false, | ||||||
14721 | /*LParenLoc=*/NoLoc, | ||||||
14722 | /*Params=*/nullptr, | ||||||
14723 | /*NumParams=*/0, | ||||||
14724 | /*EllipsisLoc=*/NoLoc, | ||||||
14725 | /*RParenLoc=*/NoLoc, | ||||||
14726 | /*RefQualifierIsLvalueRef=*/true, | ||||||
14727 | /*RefQualifierLoc=*/NoLoc, | ||||||
14728 | /*MutableLoc=*/NoLoc, EST_None, | ||||||
14729 | /*ESpecRange=*/SourceRange(), | ||||||
14730 | /*Exceptions=*/nullptr, | ||||||
14731 | /*ExceptionRanges=*/nullptr, | ||||||
14732 | /*NumExceptions=*/0, | ||||||
14733 | /*NoexceptExpr=*/nullptr, | ||||||
14734 | /*ExceptionSpecTokens=*/nullptr, | ||||||
14735 | /*DeclsInPrototype=*/None, Loc, | ||||||
14736 | Loc, D), | ||||||
14737 | std::move(DS.getAttributes()), SourceLocation()); | ||||||
14738 | D.SetIdentifier(&II, Loc); | ||||||
14739 | |||||||
14740 | // Insert this function into the enclosing block scope. | ||||||
14741 | FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); | ||||||
14742 | FD->setImplicit(); | ||||||
14743 | |||||||
14744 | AddKnownFunctionAttributes(FD); | ||||||
14745 | |||||||
14746 | return FD; | ||||||
14747 | } | ||||||
14748 | |||||||
14749 | /// If this function is a C++ replaceable global allocation function | ||||||
14750 | /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), | ||||||
14751 | /// adds any function attributes that we know a priori based on the standard. | ||||||
14752 | /// | ||||||
14753 | /// We need to check for duplicate attributes both here and where user-written | ||||||
14754 | /// attributes are applied to declarations. | ||||||
14755 | void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( | ||||||
14756 | FunctionDecl *FD) { | ||||||
14757 | if (FD->isInvalidDecl()) | ||||||
14758 | return; | ||||||
14759 | |||||||
14760 | if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && | ||||||
14761 | FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) | ||||||
14762 | return; | ||||||
14763 | |||||||
14764 | Optional<unsigned> AlignmentParam; | ||||||
14765 | bool IsNothrow = false; | ||||||
14766 | if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) | ||||||
14767 | return; | ||||||
14768 | |||||||
14769 | // C++2a [basic.stc.dynamic.allocation]p4: | ||||||
14770 | // An allocation function that has a non-throwing exception specification | ||||||
14771 | // indicates failure by returning a null pointer value. Any other allocation | ||||||
14772 | // function never returns a null pointer value and indicates failure only by | ||||||
14773 | // throwing an exception [...] | ||||||
14774 | if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) | ||||||
14775 | FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14776 | |||||||
14777 | // C++2a [basic.stc.dynamic.allocation]p2: | ||||||
14778 | // An allocation function attempts to allocate the requested amount of | ||||||
14779 | // storage. [...] If the request succeeds, the value returned by a | ||||||
14780 | // replaceable allocation function is a [...] pointer value p0 different | ||||||
14781 | // from any previously returned value p1 [...] | ||||||
14782 | // | ||||||
14783 | // However, this particular information is being added in codegen, | ||||||
14784 | // because there is an opt-out switch for it (-fno-assume-sane-operator-new) | ||||||
14785 | |||||||
14786 | // C++2a [basic.stc.dynamic.allocation]p2: | ||||||
14787 | // An allocation function attempts to allocate the requested amount of | ||||||
14788 | // storage. If it is successful, it returns the address of the start of a | ||||||
14789 | // block of storage whose length in bytes is at least as large as the | ||||||
14790 | // requested size. | ||||||
14791 | if (!FD->hasAttr<AllocSizeAttr>()) { | ||||||
14792 | FD->addAttr(AllocSizeAttr::CreateImplicit( | ||||||
14793 | Context, /*ElemSizeParam=*/ParamIdx(1, FD), | ||||||
14794 | /*NumElemsParam=*/ParamIdx(), FD->getLocation())); | ||||||
14795 | } | ||||||
14796 | |||||||
14797 | // C++2a [basic.stc.dynamic.allocation]p3: | ||||||
14798 | // For an allocation function [...], the pointer returned on a successful | ||||||
14799 | // call shall represent the address of storage that is aligned as follows: | ||||||
14800 | // (3.1) If the allocation function takes an argument of type | ||||||
14801 | // std​::​align_Âval_Ât, the storage will have the alignment | ||||||
14802 | // specified by the value of this argument. | ||||||
14803 | if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { | ||||||
14804 | FD->addAttr(AllocAlignAttr::CreateImplicit( | ||||||
14805 | Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); | ||||||
14806 | } | ||||||
14807 | |||||||
14808 | // FIXME: | ||||||
14809 | // C++2a [basic.stc.dynamic.allocation]p3: | ||||||
14810 | // For an allocation function [...], the pointer returned on a successful | ||||||
14811 | // call shall represent the address of storage that is aligned as follows: | ||||||
14812 | // (3.2) Otherwise, if the allocation function is named operator new[], | ||||||
14813 | // the storage is aligned for any object that does not have | ||||||
14814 | // new-extended alignment ([basic.align]) and is no larger than the | ||||||
14815 | // requested size. | ||||||
14816 | // (3.3) Otherwise, the storage is aligned for any object that does not | ||||||
14817 | // have new-extended alignment and is of the requested size. | ||||||
14818 | } | ||||||
14819 | |||||||
14820 | /// Adds any function attributes that we know a priori based on | ||||||
14821 | /// the declaration of this function. | ||||||
14822 | /// | ||||||
14823 | /// These attributes can apply both to implicitly-declared builtins | ||||||
14824 | /// (like __builtin___printf_chk) or to library-declared functions | ||||||
14825 | /// like NSLog or printf. | ||||||
14826 | /// | ||||||
14827 | /// We need to check for duplicate attributes both here and where user-written | ||||||
14828 | /// attributes are applied to declarations. | ||||||
14829 | void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { | ||||||
14830 | if (FD->isInvalidDecl()) | ||||||
14831 | return; | ||||||
14832 | |||||||
14833 | // If this is a built-in function, map its builtin attributes to | ||||||
14834 | // actual attributes. | ||||||
14835 | if (unsigned BuiltinID = FD->getBuiltinID()) { | ||||||
14836 | // Handle printf-formatting attributes. | ||||||
14837 | unsigned FormatIdx; | ||||||
14838 | bool HasVAListArg; | ||||||
14839 | if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { | ||||||
14840 | if (!FD->hasAttr<FormatAttr>()) { | ||||||
14841 | const char *fmt = "printf"; | ||||||
14842 | unsigned int NumParams = FD->getNumParams(); | ||||||
14843 | if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) | ||||||
14844 | FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) | ||||||
14845 | fmt = "NSString"; | ||||||
14846 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14847 | &Context.Idents.get(fmt), | ||||||
14848 | FormatIdx+1, | ||||||
14849 | HasVAListArg ? 0 : FormatIdx+2, | ||||||
14850 | FD->getLocation())); | ||||||
14851 | } | ||||||
14852 | } | ||||||
14853 | if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, | ||||||
14854 | HasVAListArg)) { | ||||||
14855 | if (!FD->hasAttr<FormatAttr>()) | ||||||
14856 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14857 | &Context.Idents.get("scanf"), | ||||||
14858 | FormatIdx+1, | ||||||
14859 | HasVAListArg ? 0 : FormatIdx+2, | ||||||
14860 | FD->getLocation())); | ||||||
14861 | } | ||||||
14862 | |||||||
14863 | // Handle automatically recognized callbacks. | ||||||
14864 | SmallVector<int, 4> Encoding; | ||||||
14865 | if (!FD->hasAttr<CallbackAttr>() && | ||||||
14866 | Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) | ||||||
14867 | FD->addAttr(CallbackAttr::CreateImplicit( | ||||||
14868 | Context, Encoding.data(), Encoding.size(), FD->getLocation())); | ||||||
14869 | |||||||
14870 | // Mark const if we don't care about errno and that is the only thing | ||||||
14871 | // preventing the function from being const. This allows IRgen to use LLVM | ||||||
14872 | // intrinsics for such functions. | ||||||
14873 | if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && | ||||||
14874 | Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) | ||||||
14875 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14876 | |||||||
14877 | // We make "fma" on some platforms const because we know it does not set | ||||||
14878 | // errno in those environments even though it could set errno based on the | ||||||
14879 | // C standard. | ||||||
14880 | const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); | ||||||
14881 | if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && | ||||||
14882 | !FD->hasAttr<ConstAttr>()) { | ||||||
14883 | switch (BuiltinID) { | ||||||
14884 | case Builtin::BI__builtin_fma: | ||||||
14885 | case Builtin::BI__builtin_fmaf: | ||||||
14886 | case Builtin::BI__builtin_fmal: | ||||||
14887 | case Builtin::BIfma: | ||||||
14888 | case Builtin::BIfmaf: | ||||||
14889 | case Builtin::BIfmal: | ||||||
14890 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14891 | break; | ||||||
14892 | default: | ||||||
14893 | break; | ||||||
14894 | } | ||||||
14895 | } | ||||||
14896 | |||||||
14897 | if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && | ||||||
14898 | !FD->hasAttr<ReturnsTwiceAttr>()) | ||||||
14899 | FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, | ||||||
14900 | FD->getLocation())); | ||||||
14901 | if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) | ||||||
14902 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14903 | if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) | ||||||
14904 | FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14905 | if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) | ||||||
14906 | FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14907 | if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && | ||||||
14908 | !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { | ||||||
14909 | // Add the appropriate attribute, depending on the CUDA compilation mode | ||||||
14910 | // and which target the builtin belongs to. For example, during host | ||||||
14911 | // compilation, aux builtins are __device__, while the rest are __host__. | ||||||
14912 | if (getLangOpts().CUDAIsDevice != | ||||||
14913 | Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) | ||||||
14914 | FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14915 | else | ||||||
14916 | FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14917 | } | ||||||
14918 | } | ||||||
14919 | |||||||
14920 | AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); | ||||||
14921 | |||||||
14922 | // If C++ exceptions are enabled but we are told extern "C" functions cannot | ||||||
14923 | // throw, add an implicit nothrow attribute to any extern "C" function we come | ||||||
14924 | // across. | ||||||
14925 | if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && | ||||||
14926 | FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { | ||||||
14927 | const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); | ||||||
14928 | if (!FPT || FPT->getExceptionSpecType() == EST_None) | ||||||
14929 | FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); | ||||||
14930 | } | ||||||
14931 | |||||||
14932 | IdentifierInfo *Name = FD->getIdentifier(); | ||||||
14933 | if (!Name) | ||||||
14934 | return; | ||||||
14935 | if ((!getLangOpts().CPlusPlus && | ||||||
14936 | FD->getDeclContext()->isTranslationUnit()) || | ||||||
14937 | (isa<LinkageSpecDecl>(FD->getDeclContext()) && | ||||||
14938 | cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == | ||||||
14939 | LinkageSpecDecl::lang_c)) { | ||||||
14940 | // Okay: this could be a libc/libm/Objective-C function we know | ||||||
14941 | // about. | ||||||
14942 | } else | ||||||
14943 | return; | ||||||
14944 | |||||||
14945 | if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { | ||||||
14946 | // FIXME: asprintf and vasprintf aren't C99 functions. Should they be | ||||||
14947 | // target-specific builtins, perhaps? | ||||||
14948 | if (!FD->hasAttr<FormatAttr>()) | ||||||
14949 | FD->addAttr(FormatAttr::CreateImplicit(Context, | ||||||
14950 | &Context.Idents.get("printf"), 2, | ||||||
14951 | Name->isStr("vasprintf") ? 0 : 3, | ||||||
14952 | FD->getLocation())); | ||||||
14953 | } | ||||||
14954 | |||||||
14955 | if (Name->isStr("__CFStringMakeConstantString")) { | ||||||
14956 | // We already have a __builtin___CFStringMakeConstantString, | ||||||
14957 | // but builds that use -fno-constant-cfstrings don't go through that. | ||||||
14958 | if (!FD->hasAttr<FormatArgAttr>()) | ||||||
14959 | FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), | ||||||
14960 | FD->getLocation())); | ||||||
14961 | } | ||||||
14962 | } | ||||||
14963 | |||||||
14964 | TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, | ||||||
14965 | TypeSourceInfo *TInfo) { | ||||||
14966 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14966, __PRETTY_FUNCTION__)); | ||||||
14967 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14967, __PRETTY_FUNCTION__)); | ||||||
14968 | |||||||
14969 | if (!TInfo) { | ||||||
14970 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 14970, __PRETTY_FUNCTION__)); | ||||||
14971 | TInfo = Context.getTrivialTypeSourceInfo(T); | ||||||
14972 | } | ||||||
14973 | |||||||
14974 | // Scope manipulation handled by caller. | ||||||
14975 | TypedefDecl *NewTD = | ||||||
14976 | TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), | ||||||
14977 | D.getIdentifierLoc(), D.getIdentifier(), TInfo); | ||||||
14978 | |||||||
14979 | // Bail out immediately if we have an invalid declaration. | ||||||
14980 | if (D.isInvalidType()) { | ||||||
14981 | NewTD->setInvalidDecl(); | ||||||
14982 | return NewTD; | ||||||
14983 | } | ||||||
14984 | |||||||
14985 | if (D.getDeclSpec().isModulePrivateSpecified()) { | ||||||
14986 | if (CurContext->isFunctionOrMethod()) | ||||||
14987 | Diag(NewTD->getLocation(), diag::err_module_private_local) | ||||||
14988 | << 2 << NewTD | ||||||
14989 | << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) | ||||||
14990 | << FixItHint::CreateRemoval( | ||||||
14991 | D.getDeclSpec().getModulePrivateSpecLoc()); | ||||||
14992 | else | ||||||
14993 | NewTD->setModulePrivate(); | ||||||
14994 | } | ||||||
14995 | |||||||
14996 | // C++ [dcl.typedef]p8: | ||||||
14997 | // If the typedef declaration defines an unnamed class (or | ||||||
14998 | // enum), the first typedef-name declared by the declaration | ||||||
14999 | // to be that class type (or enum type) is used to denote the | ||||||
15000 | // class type (or enum type) for linkage purposes only. | ||||||
15001 | // We need to check whether the type was declared in the declaration. | ||||||
15002 | switch (D.getDeclSpec().getTypeSpecType()) { | ||||||
15003 | case TST_enum: | ||||||
15004 | case TST_struct: | ||||||
15005 | case TST_interface: | ||||||
15006 | case TST_union: | ||||||
15007 | case TST_class: { | ||||||
15008 | TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); | ||||||
15009 | setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); | ||||||
15010 | break; | ||||||
15011 | } | ||||||
15012 | |||||||
15013 | default: | ||||||
15014 | break; | ||||||
15015 | } | ||||||
15016 | |||||||
15017 | return NewTD; | ||||||
15018 | } | ||||||
15019 | |||||||
15020 | /// Check that this is a valid underlying type for an enum declaration. | ||||||
15021 | bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { | ||||||
15022 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); | ||||||
15023 | QualType T = TI->getType(); | ||||||
15024 | |||||||
15025 | if (T->isDependentType()) | ||||||
15026 | return false; | ||||||
15027 | |||||||
15028 | // This doesn't use 'isIntegralType' despite the error message mentioning | ||||||
15029 | // integral type because isIntegralType would also allow enum types in C. | ||||||
15030 | if (const BuiltinType *BT = T->getAs<BuiltinType>()) | ||||||
15031 | if (BT->isInteger()) | ||||||
15032 | return false; | ||||||
15033 | |||||||
15034 | if (T->isExtIntType()) | ||||||
15035 | return false; | ||||||
15036 | |||||||
15037 | return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; | ||||||
15038 | } | ||||||
15039 | |||||||
15040 | /// Check whether this is a valid redeclaration of a previous enumeration. | ||||||
15041 | /// \return true if the redeclaration was invalid. | ||||||
15042 | bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, | ||||||
15043 | QualType EnumUnderlyingTy, bool IsFixed, | ||||||
15044 | const EnumDecl *Prev) { | ||||||
15045 | if (IsScoped != Prev->isScoped()) { | ||||||
15046 | Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) | ||||||
15047 | << Prev->isScoped(); | ||||||
15048 | Diag(Prev->getLocation(), diag::note_previous_declaration); | ||||||
15049 | return true; | ||||||
15050 | } | ||||||
15051 | |||||||
15052 | if (IsFixed && Prev->isFixed()) { | ||||||
15053 | if (!EnumUnderlyingTy->isDependentType() && | ||||||
15054 | !Prev->getIntegerType()->isDependentType() && | ||||||
15055 | !Context.hasSameUnqualifiedType(EnumUnderlyingTy, | ||||||
15056 | Prev->getIntegerType())) { | ||||||
15057 | // TODO: Highlight the underlying type of the redeclaration. | ||||||
15058 | Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) | ||||||
15059 | << EnumUnderlyingTy << Prev->getIntegerType(); | ||||||
15060 | Diag(Prev->getLocation(), diag::note_previous_declaration) | ||||||
15061 | << Prev->getIntegerTypeRange(); | ||||||
15062 | return true; | ||||||
15063 | } | ||||||
15064 | } else if (IsFixed != Prev->isFixed()) { | ||||||
15065 | Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) | ||||||
15066 | << Prev->isFixed(); | ||||||
15067 | Diag(Prev->getLocation(), diag::note_previous_declaration); | ||||||
15068 | return true; | ||||||
15069 | } | ||||||
15070 | |||||||
15071 | return false; | ||||||
15072 | } | ||||||
15073 | |||||||
15074 | /// Get diagnostic %select index for tag kind for | ||||||
15075 | /// redeclaration diagnostic message. | ||||||
15076 | /// WARNING: Indexes apply to particular diagnostics only! | ||||||
15077 | /// | ||||||
15078 | /// \returns diagnostic %select index. | ||||||
15079 | static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { | ||||||
15080 | switch (Tag) { | ||||||
15081 | case TTK_Struct: return 0; | ||||||
15082 | case TTK_Interface: return 1; | ||||||
15083 | case TTK_Class: return 2; | ||||||
15084 | default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 15084); | ||||||
15085 | } | ||||||
15086 | } | ||||||
15087 | |||||||
15088 | /// Determine if tag kind is a class-key compatible with | ||||||
15089 | /// class for redeclaration (class, struct, or __interface). | ||||||
15090 | /// | ||||||
15091 | /// \returns true iff the tag kind is compatible. | ||||||
15092 | static bool isClassCompatTagKind(TagTypeKind Tag) | ||||||
15093 | { | ||||||
15094 | return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; | ||||||
15095 | } | ||||||
15096 | |||||||
15097 | Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, | ||||||
15098 | TagTypeKind TTK) { | ||||||
15099 | if (isa<TypedefDecl>(PrevDecl)) | ||||||
15100 | return NTK_Typedef; | ||||||
15101 | else if (isa<TypeAliasDecl>(PrevDecl)) | ||||||
15102 | return NTK_TypeAlias; | ||||||
15103 | else if (isa<ClassTemplateDecl>(PrevDecl)) | ||||||
15104 | return NTK_Template; | ||||||
15105 | else if (isa<TypeAliasTemplateDecl>(PrevDecl)) | ||||||
15106 | return NTK_TypeAliasTemplate; | ||||||
15107 | else if (isa<TemplateTemplateParmDecl>(PrevDecl)) | ||||||
15108 | return NTK_TemplateTemplateArgument; | ||||||
15109 | switch (TTK) { | ||||||
15110 | case TTK_Struct: | ||||||
15111 | case TTK_Interface: | ||||||
15112 | case TTK_Class: | ||||||
15113 | return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; | ||||||
15114 | case TTK_Union: | ||||||
15115 | return NTK_NonUnion; | ||||||
15116 | case TTK_Enum: | ||||||
15117 | return NTK_NonEnum; | ||||||
15118 | } | ||||||
15119 | llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 15119); | ||||||
15120 | } | ||||||
15121 | |||||||
15122 | /// Determine whether a tag with a given kind is acceptable | ||||||
15123 | /// as a redeclaration of the given tag declaration. | ||||||
15124 | /// | ||||||
15125 | /// \returns true if the new tag kind is acceptable, false otherwise. | ||||||
15126 | bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, | ||||||
15127 | TagTypeKind NewTag, bool isDefinition, | ||||||
15128 | SourceLocation NewTagLoc, | ||||||
15129 | const IdentifierInfo *Name) { | ||||||
15130 | // C++ [dcl.type.elab]p3: | ||||||
15131 | // The class-key or enum keyword present in the | ||||||
15132 | // elaborated-type-specifier shall agree in kind with the | ||||||
15133 | // declaration to which the name in the elaborated-type-specifier | ||||||
15134 | // refers. This rule also applies to the form of | ||||||
15135 | // elaborated-type-specifier that declares a class-name or | ||||||
15136 | // friend class since it can be construed as referring to the | ||||||
15137 | // definition of the class. Thus, in any | ||||||
15138 | // elaborated-type-specifier, the enum keyword shall be used to | ||||||
15139 | // refer to an enumeration (7.2), the union class-key shall be | ||||||
15140 | // used to refer to a union (clause 9), and either the class or | ||||||
15141 | // struct class-key shall be used to refer to a class (clause 9) | ||||||
15142 | // declared using the class or struct class-key. | ||||||
15143 | TagTypeKind OldTag = Previous->getTagKind(); | ||||||
15144 | if (OldTag != NewTag && | ||||||
15145 | !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) | ||||||
15146 | return false; | ||||||
15147 | |||||||
15148 | // Tags are compatible, but we might still want to warn on mismatched tags. | ||||||
15149 | // Non-class tags can't be mismatched at this point. | ||||||
15150 | if (!isClassCompatTagKind(NewTag)) | ||||||
15151 | return true; | ||||||
15152 | |||||||
15153 | // Declarations for which -Wmismatched-tags is disabled are entirely ignored | ||||||
15154 | // by our warning analysis. We don't want to warn about mismatches with (eg) | ||||||
15155 | // declarations in system headers that are designed to be specialized, but if | ||||||
15156 | // a user asks us to warn, we should warn if their code contains mismatched | ||||||
15157 | // declarations. | ||||||
15158 | auto IsIgnoredLoc = [&](SourceLocation Loc) { | ||||||
15159 | return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, | ||||||
15160 | Loc); | ||||||
15161 | }; | ||||||
15162 | if (IsIgnoredLoc(NewTagLoc)) | ||||||
15163 | return true; | ||||||
15164 | |||||||
15165 | auto IsIgnored = [&](const TagDecl *Tag) { | ||||||
15166 | return IsIgnoredLoc(Tag->getLocation()); | ||||||
15167 | }; | ||||||
15168 | while (IsIgnored(Previous)) { | ||||||
15169 | Previous = Previous->getPreviousDecl(); | ||||||
15170 | if (!Previous) | ||||||
15171 | return true; | ||||||
15172 | OldTag = Previous->getTagKind(); | ||||||
15173 | } | ||||||
15174 | |||||||
15175 | bool isTemplate = false; | ||||||
15176 | if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) | ||||||
15177 | isTemplate = Record->getDescribedClassTemplate(); | ||||||
15178 | |||||||
15179 | if (inTemplateInstantiation()) { | ||||||
15180 | if (OldTag != NewTag) { | ||||||
15181 | // In a template instantiation, do not offer fix-its for tag mismatches | ||||||
15182 | // since they usually mess up the template instead of fixing the problem. | ||||||
15183 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | ||||||
15184 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
15185 | << getRedeclDiagFromTagKind(OldTag); | ||||||
15186 | // FIXME: Note previous location? | ||||||
15187 | } | ||||||
15188 | return true; | ||||||
15189 | } | ||||||
15190 | |||||||
15191 | if (isDefinition) { | ||||||
15192 | // On definitions, check all previous tags and issue a fix-it for each | ||||||
15193 | // one that doesn't match the current tag. | ||||||
15194 | if (Previous->getDefinition()) { | ||||||
15195 | // Don't suggest fix-its for redefinitions. | ||||||
15196 | return true; | ||||||
15197 | } | ||||||
15198 | |||||||
15199 | bool previousMismatch = false; | ||||||
15200 | for (const TagDecl *I : Previous->redecls()) { | ||||||
15201 | if (I->getTagKind() != NewTag) { | ||||||
15202 | // Ignore previous declarations for which the warning was disabled. | ||||||
15203 | if (IsIgnored(I)) | ||||||
15204 | continue; | ||||||
15205 | |||||||
15206 | if (!previousMismatch) { | ||||||
15207 | previousMismatch = true; | ||||||
15208 | Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) | ||||||
15209 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
15210 | << getRedeclDiagFromTagKind(I->getTagKind()); | ||||||
15211 | } | ||||||
15212 | Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) | ||||||
15213 | << getRedeclDiagFromTagKind(NewTag) | ||||||
15214 | << FixItHint::CreateReplacement(I->getInnerLocStart(), | ||||||
15215 | TypeWithKeyword::getTagTypeKindName(NewTag)); | ||||||
15216 | } | ||||||
15217 | } | ||||||
15218 | return true; | ||||||
15219 | } | ||||||
15220 | |||||||
15221 | // Identify the prevailing tag kind: this is the kind of the definition (if | ||||||
15222 | // there is a non-ignored definition), or otherwise the kind of the prior | ||||||
15223 | // (non-ignored) declaration. | ||||||
15224 | const TagDecl *PrevDef = Previous->getDefinition(); | ||||||
15225 | if (PrevDef && IsIgnored(PrevDef)) | ||||||
15226 | PrevDef = nullptr; | ||||||
15227 | const TagDecl *Redecl = PrevDef ? PrevDef : Previous; | ||||||
15228 | if (Redecl->getTagKind() != NewTag) { | ||||||
15229 | Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) | ||||||
15230 | << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name | ||||||
15231 | << getRedeclDiagFromTagKind(OldTag); | ||||||
15232 | Diag(Redecl->getLocation(), diag::note_previous_use); | ||||||
15233 | |||||||
15234 | // If there is a previous definition, suggest a fix-it. | ||||||
15235 | if (PrevDef) { | ||||||
15236 | Diag(NewTagLoc, diag::note_struct_class_suggestion) | ||||||
15237 | << getRedeclDiagFromTagKind(Redecl->getTagKind()) | ||||||
15238 | << FixItHint::CreateReplacement(SourceRange(NewTagLoc), | ||||||
15239 | TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); | ||||||
15240 | } | ||||||
15241 | } | ||||||
15242 | |||||||
15243 | return true; | ||||||
15244 | } | ||||||
15245 | |||||||
15246 | /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name | ||||||
15247 | /// from an outer enclosing namespace or file scope inside a friend declaration. | ||||||
15248 | /// This should provide the commented out code in the following snippet: | ||||||
15249 | /// namespace N { | ||||||
15250 | /// struct X; | ||||||
15251 | /// namespace M { | ||||||
15252 | /// struct Y { friend struct /*N::*/ X; }; | ||||||
15253 | /// } | ||||||
15254 | /// } | ||||||
15255 | static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, | ||||||
15256 | SourceLocation NameLoc) { | ||||||
15257 | // While the decl is in a namespace, do repeated lookup of that name and see | ||||||
15258 | // if we get the same namespace back. If we do not, continue until | ||||||
15259 | // translation unit scope, at which point we have a fully qualified NNS. | ||||||
15260 | SmallVector<IdentifierInfo *, 4> Namespaces; | ||||||
15261 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | ||||||
15262 | for (; !DC->isTranslationUnit(); DC = DC->getParent()) { | ||||||
15263 | // This tag should be declared in a namespace, which can only be enclosed by | ||||||
15264 | // other namespaces. Bail if there's an anonymous namespace in the chain. | ||||||
15265 | NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); | ||||||
15266 | if (!Namespace || Namespace->isAnonymousNamespace()) | ||||||
15267 | return FixItHint(); | ||||||
15268 | IdentifierInfo *II = Namespace->getIdentifier(); | ||||||
15269 | Namespaces.push_back(II); | ||||||
15270 | NamedDecl *Lookup = SemaRef.LookupSingleName( | ||||||
15271 | S, II, NameLoc, Sema::LookupNestedNameSpecifierName); | ||||||
15272 | if (Lookup == Namespace) | ||||||
15273 | break; | ||||||
15274 | } | ||||||
15275 | |||||||
15276 | // Once we have all the namespaces, reverse them to go outermost first, and | ||||||
15277 | // build an NNS. | ||||||
15278 | SmallString<64> Insertion; | ||||||
15279 | llvm::raw_svector_ostream OS(Insertion); | ||||||
15280 | if (DC->isTranslationUnit()) | ||||||
15281 | OS << "::"; | ||||||
15282 | std::reverse(Namespaces.begin(), Namespaces.end()); | ||||||
15283 | for (auto *II : Namespaces) | ||||||
15284 | OS << II->getName() << "::"; | ||||||
15285 | return FixItHint::CreateInsertion(NameLoc, Insertion); | ||||||
15286 | } | ||||||
15287 | |||||||
15288 | /// Determine whether a tag originally declared in context \p OldDC can | ||||||
15289 | /// be redeclared with an unqualified name in \p NewDC (assuming name lookup | ||||||
15290 | /// found a declaration in \p OldDC as a previous decl, perhaps through a | ||||||
15291 | /// using-declaration). | ||||||
15292 | static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, | ||||||
15293 | DeclContext *NewDC) { | ||||||
15294 | OldDC = OldDC->getRedeclContext(); | ||||||
15295 | NewDC = NewDC->getRedeclContext(); | ||||||
15296 | |||||||
15297 | if (OldDC->Equals(NewDC)) | ||||||
15298 | return true; | ||||||
15299 | |||||||
15300 | // In MSVC mode, we allow a redeclaration if the contexts are related (either | ||||||
15301 | // encloses the other). | ||||||
15302 | if (S.getLangOpts().MSVCCompat && | ||||||
15303 | (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) | ||||||
15304 | return true; | ||||||
15305 | |||||||
15306 | return false; | ||||||
15307 | } | ||||||
15308 | |||||||
15309 | /// This is invoked when we see 'struct foo' or 'struct {'. In the | ||||||
15310 | /// former case, Name will be non-null. In the later case, Name will be null. | ||||||
15311 | /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a | ||||||
15312 | /// reference/declaration/definition of a tag. | ||||||
15313 | /// | ||||||
15314 | /// \param IsTypeSpecifier \c true if this is a type-specifier (or | ||||||
15315 | /// trailing-type-specifier) other than one in an alias-declaration. | ||||||
15316 | /// | ||||||
15317 | /// \param SkipBody If non-null, will be set to indicate if the caller should | ||||||
15318 | /// skip the definition of this tag and treat it as if it were a declaration. | ||||||
15319 | Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, | ||||||
15320 | SourceLocation KWLoc, CXXScopeSpec &SS, | ||||||
15321 | IdentifierInfo *Name, SourceLocation NameLoc, | ||||||
15322 | const ParsedAttributesView &Attrs, AccessSpecifier AS, | ||||||
15323 | SourceLocation ModulePrivateLoc, | ||||||
15324 | MultiTemplateParamsArg TemplateParameterLists, | ||||||
15325 | bool &OwnedDecl, bool &IsDependent, | ||||||
15326 | SourceLocation ScopedEnumKWLoc, | ||||||
15327 | bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, | ||||||
15328 | bool IsTypeSpecifier, bool IsTemplateParamOrArg, | ||||||
15329 | SkipBodyInfo *SkipBody) { | ||||||
15330 | // If this is not a definition, it must have a name. | ||||||
15331 | IdentifierInfo *OrigName = Name; | ||||||
15332 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 15333, __PRETTY_FUNCTION__)) | ||||||
15333 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 15333, __PRETTY_FUNCTION__)); | ||||||
15334 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 15334, __PRETTY_FUNCTION__)); | ||||||
15335 | |||||||
15336 | OwnedDecl = false; | ||||||
15337 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); | ||||||
15338 | bool ScopedEnum = ScopedEnumKWLoc.isValid(); | ||||||
15339 | |||||||
15340 | // FIXME: Check member specializations more carefully. | ||||||
15341 | bool isMemberSpecialization = false; | ||||||
15342 | bool Invalid = false; | ||||||
15343 | |||||||
15344 | // We only need to do this matching if we have template parameters | ||||||
15345 | // or a scope specifier, which also conveniently avoids this work | ||||||
15346 | // for non-C++ cases. | ||||||
15347 | if (TemplateParameterLists.size() > 0 || | ||||||
15348 | (SS.isNotEmpty() && TUK != TUK_Reference)) { | ||||||
15349 | if (TemplateParameterList *TemplateParams = | ||||||
15350 | MatchTemplateParametersToScopeSpecifier( | ||||||
15351 | KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, | ||||||
15352 | TUK == TUK_Friend, isMemberSpecialization, Invalid)) { | ||||||
15353 | if (Kind == TTK_Enum) { | ||||||
15354 | Diag(KWLoc, diag::err_enum_template); | ||||||
15355 | return nullptr; | ||||||
15356 | } | ||||||
15357 | |||||||
15358 | if (TemplateParams->size() > 0) { | ||||||
15359 | // This is a declaration or definition of a class template (which may | ||||||
15360 | // be a member of another template). | ||||||
15361 | |||||||
15362 | if (Invalid) | ||||||
15363 | return nullptr; | ||||||
15364 | |||||||
15365 | OwnedDecl = false; | ||||||
15366 | DeclResult Result = CheckClassTemplate( | ||||||
15367 | S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, | ||||||
15368 | AS, ModulePrivateLoc, | ||||||
15369 | /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, | ||||||
15370 | TemplateParameterLists.data(), SkipBody); | ||||||
15371 | return Result.get(); | ||||||
15372 | } else { | ||||||
15373 | // The "template<>" header is extraneous. | ||||||
15374 | Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) | ||||||
15375 | << TypeWithKeyword::getTagTypeKindName(Kind) << Name; | ||||||
15376 | isMemberSpecialization = true; | ||||||
15377 | } | ||||||
15378 | } | ||||||
15379 | |||||||
15380 | if (!TemplateParameterLists.empty() && isMemberSpecialization && | ||||||
15381 | CheckTemplateDeclScope(S, TemplateParameterLists.back())) | ||||||
15382 | return nullptr; | ||||||
15383 | } | ||||||
15384 | |||||||
15385 | // Figure out the underlying type if this a enum declaration. We need to do | ||||||
15386 | // this early, because it's needed to detect if this is an incompatible | ||||||
15387 | // redeclaration. | ||||||
15388 | llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; | ||||||
15389 | bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; | ||||||
15390 | |||||||
15391 | if (Kind == TTK_Enum) { | ||||||
15392 | if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { | ||||||
15393 | // No underlying type explicitly specified, or we failed to parse the | ||||||
15394 | // type, default to int. | ||||||
15395 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
15396 | } else if (UnderlyingType.get()) { | ||||||
15397 | // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an | ||||||
15398 | // integral type; any cv-qualification is ignored. | ||||||
15399 | TypeSourceInfo *TI = nullptr; | ||||||
15400 | GetTypeFromParser(UnderlyingType.get(), &TI); | ||||||
15401 | EnumUnderlying = TI; | ||||||
15402 | |||||||
15403 | if (CheckEnumUnderlyingType(TI)) | ||||||
15404 | // Recover by falling back to int. | ||||||
15405 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
15406 | |||||||
15407 | if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, | ||||||
15408 | UPPC_FixedUnderlyingType)) | ||||||
15409 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
15410 | |||||||
15411 | } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { | ||||||
15412 | // For MSVC ABI compatibility, unfixed enums must use an underlying type | ||||||
15413 | // of 'int'. However, if this is an unfixed forward declaration, don't set | ||||||
15414 | // the underlying type unless the user enables -fms-compatibility. This | ||||||
15415 | // makes unfixed forward declared enums incomplete and is more conforming. | ||||||
15416 | if (TUK == TUK_Definition || getLangOpts().MSVCCompat) | ||||||
15417 | EnumUnderlying = Context.IntTy.getTypePtr(); | ||||||
15418 | } | ||||||
15419 | } | ||||||
15420 | |||||||
15421 | DeclContext *SearchDC = CurContext; | ||||||
15422 | DeclContext *DC = CurContext; | ||||||
15423 | bool isStdBadAlloc = false; | ||||||
15424 | bool isStdAlignValT = false; | ||||||
15425 | |||||||
15426 | RedeclarationKind Redecl = forRedeclarationInCurContext(); | ||||||
15427 | if (TUK == TUK_Friend || TUK == TUK_Reference) | ||||||
15428 | Redecl = NotForRedeclaration; | ||||||
15429 | |||||||
15430 | /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C | ||||||
15431 | /// implemented asks for structural equivalence checking, the returned decl | ||||||
15432 | /// here is passed back to the parser, allowing the tag body to be parsed. | ||||||
15433 | auto createTagFromNewDecl = [&]() -> TagDecl * { | ||||||
15434 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 15434, __PRETTY_FUNCTION__)); | ||||||
15435 | // If there is an identifier, use the location of the identifier as the | ||||||
15436 | // location of the decl, otherwise use the location of the struct/union | ||||||
15437 | // keyword. | ||||||
15438 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | ||||||
15439 | TagDecl *New = nullptr; | ||||||
15440 | |||||||
15441 | if (Kind == TTK_Enum) { | ||||||
15442 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, | ||||||
15443 | ScopedEnum, ScopedEnumUsesClassTag, IsFixed); | ||||||
15444 | // If this is an undefined enum, bail. | ||||||
15445 | if (TUK != TUK_Definition && !Invalid) | ||||||
15446 | return nullptr; | ||||||
15447 | if (EnumUnderlying) { | ||||||
15448 | EnumDecl *ED = cast<EnumDecl>(New); | ||||||
15449 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) | ||||||
15450 | ED->setIntegerTypeSourceInfo(TI); | ||||||
15451 | else | ||||||
15452 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); | ||||||
15453 | ED->setPromotionType(ED->getIntegerType()); | ||||||
15454 | } | ||||||
15455 | } else { // struct/union | ||||||
15456 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
15457 | nullptr); | ||||||
15458 | } | ||||||
15459 | |||||||
15460 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | ||||||
15461 | // Add alignment attributes if necessary; these attributes are checked | ||||||
15462 | // when the ASTContext lays out the structure. | ||||||
15463 | // | ||||||
15464 | // It is important for implementing the correct semantics that this | ||||||
15465 | // happen here (in ActOnTag). The #pragma pack stack is | ||||||
15466 | // maintained as a result of parser callbacks which can occur at | ||||||
15467 | // many points during the parsing of a struct declaration (because | ||||||
15468 | // the #pragma tokens are effectively skipped over during the | ||||||
15469 | // parsing of the struct). | ||||||
15470 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | ||||||
15471 | AddAlignmentAttributesForRecord(RD); | ||||||
15472 | AddMsStructLayoutForRecord(RD); | ||||||
15473 | } | ||||||
15474 | } | ||||||
15475 | New->setLexicalDeclContext(CurContext); | ||||||
15476 | return New; | ||||||
15477 | }; | ||||||
15478 | |||||||
15479 | LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); | ||||||
15480 | if (Name && SS.isNotEmpty()) { | ||||||
15481 | // We have a nested-name tag ('struct foo::bar'). | ||||||
15482 | |||||||
15483 | // Check for invalid 'foo::'. | ||||||
15484 | if (SS.isInvalid()) { | ||||||
15485 | Name = nullptr; | ||||||
15486 | goto CreateNewDecl; | ||||||
15487 | } | ||||||
15488 | |||||||
15489 | // If this is a friend or a reference to a class in a dependent | ||||||
15490 | // context, don't try to make a decl for it. | ||||||
15491 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | ||||||
15492 | DC = computeDeclContext(SS, false); | ||||||
15493 | if (!DC) { | ||||||
15494 | IsDependent = true; | ||||||
15495 | return nullptr; | ||||||
15496 | } | ||||||
15497 | } else { | ||||||
15498 | DC = computeDeclContext(SS, true); | ||||||
15499 | if (!DC) { | ||||||
15500 | Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) | ||||||
15501 | << SS.getRange(); | ||||||
15502 | return nullptr; | ||||||
15503 | } | ||||||
15504 | } | ||||||
15505 | |||||||
15506 | if (RequireCompleteDeclContext(SS, DC)) | ||||||
15507 | return nullptr; | ||||||
15508 | |||||||
15509 | SearchDC = DC; | ||||||
15510 | // Look-up name inside 'foo::'. | ||||||
15511 | LookupQualifiedName(Previous, DC); | ||||||
15512 | |||||||
15513 | if (Previous.isAmbiguous()) | ||||||
15514 | return nullptr; | ||||||
15515 | |||||||
15516 | if (Previous.empty()) { | ||||||
15517 | // Name lookup did not find anything. However, if the | ||||||
15518 | // nested-name-specifier refers to the current instantiation, | ||||||
15519 | // and that current instantiation has any dependent base | ||||||
15520 | // classes, we might find something at instantiation time: treat | ||||||
15521 | // this as a dependent elaborated-type-specifier. | ||||||
15522 | // But this only makes any sense for reference-like lookups. | ||||||
15523 | if (Previous.wasNotFoundInCurrentInstantiation() && | ||||||
15524 | (TUK == TUK_Reference || TUK == TUK_Friend)) { | ||||||
15525 | IsDependent = true; | ||||||
15526 | return nullptr; | ||||||
15527 | } | ||||||
15528 | |||||||
15529 | // A tag 'foo::bar' must already exist. | ||||||
15530 | Diag(NameLoc, diag::err_not_tag_in_scope) | ||||||
15531 | << Kind << Name << DC << SS.getRange(); | ||||||
15532 | Name = nullptr; | ||||||
15533 | Invalid = true; | ||||||
15534 | goto CreateNewDecl; | ||||||
15535 | } | ||||||
15536 | } else if (Name) { | ||||||
15537 | // C++14 [class.mem]p14: | ||||||
15538 | // If T is the name of a class, then each of the following shall have a | ||||||
15539 | // name different from T: | ||||||
15540 | // -- every member of class T that is itself a type | ||||||
15541 | if (TUK != TUK_Reference && TUK != TUK_Friend && | ||||||
15542 | DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) | ||||||
15543 | return nullptr; | ||||||
15544 | |||||||
15545 | // If this is a named struct, check to see if there was a previous forward | ||||||
15546 | // declaration or definition. | ||||||
15547 | // FIXME: We're looking into outer scopes here, even when we | ||||||
15548 | // shouldn't be. Doing so can result in ambiguities that we | ||||||
15549 | // shouldn't be diagnosing. | ||||||
15550 | LookupName(Previous, S); | ||||||
15551 | |||||||
15552 | // When declaring or defining a tag, ignore ambiguities introduced | ||||||
15553 | // by types using'ed into this scope. | ||||||
15554 | if (Previous.isAmbiguous() && | ||||||
15555 | (TUK == TUK_Definition || TUK == TUK_Declaration)) { | ||||||
15556 | LookupResult::Filter F = Previous.makeFilter(); | ||||||
15557 | while (F.hasNext()) { | ||||||
15558 | NamedDecl *ND = F.next(); | ||||||
15559 | if (!ND->getDeclContext()->getRedeclContext()->Equals( | ||||||
15560 | SearchDC->getRedeclContext())) | ||||||
15561 | F.erase(); | ||||||
15562 | } | ||||||
15563 | F.done(); | ||||||
15564 | } | ||||||
15565 | |||||||
15566 | // C++11 [namespace.memdef]p3: | ||||||
15567 | // If the name in a friend declaration is neither qualified nor | ||||||
15568 | // a template-id and the declaration is a function or an | ||||||
15569 | // elaborated-type-specifier, the lookup to determine whether | ||||||
15570 | // the entity has been previously declared shall not consider | ||||||
15571 | // any scopes outside the innermost enclosing namespace. | ||||||
15572 | // | ||||||
15573 | // MSVC doesn't implement the above rule for types, so a friend tag | ||||||
15574 | // declaration may be a redeclaration of a type declared in an enclosing | ||||||
15575 | // scope. They do implement this rule for friend functions. | ||||||
15576 | // | ||||||
15577 | // Does it matter that this should be by scope instead of by | ||||||
15578 | // semantic context? | ||||||
15579 | if (!Previous.empty() && TUK == TUK_Friend) { | ||||||
15580 | DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); | ||||||
15581 | LookupResult::Filter F = Previous.makeFilter(); | ||||||
15582 | bool FriendSawTagOutsideEnclosingNamespace = false; | ||||||
15583 | while (F.hasNext()) { | ||||||
15584 | NamedDecl *ND = F.next(); | ||||||
15585 | DeclContext *DC = ND->getDeclContext()->getRedeclContext(); | ||||||
15586 | if (DC->isFileContext() && | ||||||
15587 | !EnclosingNS->Encloses(ND->getDeclContext())) { | ||||||
15588 | if (getLangOpts().MSVCCompat) | ||||||
15589 | FriendSawTagOutsideEnclosingNamespace = true; | ||||||
15590 | else | ||||||
15591 | F.erase(); | ||||||
15592 | } | ||||||
15593 | } | ||||||
15594 | F.done(); | ||||||
15595 | |||||||
15596 | // Diagnose this MSVC extension in the easy case where lookup would have | ||||||
15597 | // unambiguously found something outside the enclosing namespace. | ||||||
15598 | if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { | ||||||
15599 | NamedDecl *ND = Previous.getFoundDecl(); | ||||||
15600 | Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) | ||||||
15601 | << createFriendTagNNSFixIt(*this, ND, S, NameLoc); | ||||||
15602 | } | ||||||
15603 | } | ||||||
15604 | |||||||
15605 | // Note: there used to be some attempt at recovery here. | ||||||
15606 | if (Previous.isAmbiguous()) | ||||||
15607 | return nullptr; | ||||||
15608 | |||||||
15609 | if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { | ||||||
15610 | // FIXME: This makes sure that we ignore the contexts associated | ||||||
15611 | // with C structs, unions, and enums when looking for a matching | ||||||
15612 | // tag declaration or definition. See the similar lookup tweak | ||||||
15613 | // in Sema::LookupName; is there a better way to deal with this? | ||||||
15614 | while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) | ||||||
15615 | SearchDC = SearchDC->getParent(); | ||||||
15616 | } | ||||||
15617 | } | ||||||
15618 | |||||||
15619 | if (Previous.isSingleResult() && | ||||||
15620 | Previous.getFoundDecl()->isTemplateParameter()) { | ||||||
15621 | // Maybe we will complain about the shadowed template parameter. | ||||||
15622 | DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); | ||||||
15623 | // Just pretend that we didn't see the previous declaration. | ||||||
15624 | Previous.clear(); | ||||||
15625 | } | ||||||
15626 | |||||||
15627 | if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && | ||||||
15628 | DC->Equals(getStdNamespace())) { | ||||||
15629 | if (Name->isStr("bad_alloc")) { | ||||||
15630 | // This is a declaration of or a reference to "std::bad_alloc". | ||||||
15631 | isStdBadAlloc = true; | ||||||
15632 | |||||||
15633 | // If std::bad_alloc has been implicitly declared (but made invisible to | ||||||
15634 | // name lookup), fill in this implicit declaration as the previous | ||||||
15635 | // declaration, so that the declarations get chained appropriately. | ||||||
15636 | if (Previous.empty() && StdBadAlloc) | ||||||
15637 | Previous.addDecl(getStdBadAlloc()); | ||||||
15638 | } else if (Name->isStr("align_val_t")) { | ||||||
15639 | isStdAlignValT = true; | ||||||
15640 | if (Previous.empty() && StdAlignValT) | ||||||
15641 | Previous.addDecl(getStdAlignValT()); | ||||||
15642 | } | ||||||
15643 | } | ||||||
15644 | |||||||
15645 | // If we didn't find a previous declaration, and this is a reference | ||||||
15646 | // (or friend reference), move to the correct scope. In C++, we | ||||||
15647 | // also need to do a redeclaration lookup there, just in case | ||||||
15648 | // there's a shadow friend decl. | ||||||
15649 | if (Name && Previous.empty() && | ||||||
15650 | (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { | ||||||
15651 | if (Invalid) goto CreateNewDecl; | ||||||
15652 | assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail ("SS.isEmpty()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 15652, __PRETTY_FUNCTION__)); | ||||||
15653 | |||||||
15654 | if (TUK == TUK_Reference || IsTemplateParamOrArg) { | ||||||
15655 | // C++ [basic.scope.pdecl]p5: | ||||||
15656 | // -- for an elaborated-type-specifier of the form | ||||||
15657 | // | ||||||
15658 | // class-key identifier | ||||||
15659 | // | ||||||
15660 | // if the elaborated-type-specifier is used in the | ||||||
15661 | // decl-specifier-seq or parameter-declaration-clause of a | ||||||
15662 | // function defined in namespace scope, the identifier is | ||||||
15663 | // declared as a class-name in the namespace that contains | ||||||
15664 | // the declaration; otherwise, except as a friend | ||||||
15665 | // declaration, the identifier is declared in the smallest | ||||||
15666 | // non-class, non-function-prototype scope that contains the | ||||||
15667 | // declaration. | ||||||
15668 | // | ||||||
15669 | // C99 6.7.2.3p8 has a similar (but not identical!) provision for | ||||||
15670 | // C structs and unions. | ||||||
15671 | // | ||||||
15672 | // It is an error in C++ to declare (rather than define) an enum | ||||||
15673 | // type, including via an elaborated type specifier. We'll | ||||||
15674 | // diagnose that later; for now, declare the enum in the same | ||||||
15675 | // scope as we would have picked for any other tag type. | ||||||
15676 | // | ||||||
15677 | // GNU C also supports this behavior as part of its incomplete | ||||||
15678 | // enum types extension, while GNU C++ does not. | ||||||
15679 | // | ||||||
15680 | // Find the context where we'll be declaring the tag. | ||||||
15681 | // FIXME: We would like to maintain the current DeclContext as the | ||||||
15682 | // lexical context, | ||||||
15683 | SearchDC = getTagInjectionContext(SearchDC); | ||||||
15684 | |||||||
15685 | // Find the scope where we'll be declaring the tag. | ||||||
15686 | S = getTagInjectionScope(S, getLangOpts()); | ||||||
15687 | } else { | ||||||
15688 | assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail ("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 15688, __PRETTY_FUNCTION__)); | ||||||
15689 | // C++ [namespace.memdef]p3: | ||||||
15690 | // If a friend declaration in a non-local class first declares a | ||||||
15691 | // class or function, the friend class or function is a member of | ||||||
15692 | // the innermost enclosing namespace. | ||||||
15693 | SearchDC = SearchDC->getEnclosingNamespaceContext(); | ||||||
15694 | } | ||||||
15695 | |||||||
15696 | // In C++, we need to do a redeclaration lookup to properly | ||||||
15697 | // diagnose some problems. | ||||||
15698 | // FIXME: redeclaration lookup is also used (with and without C++) to find a | ||||||
15699 | // hidden declaration so that we don't get ambiguity errors when using a | ||||||
15700 | // type declared by an elaborated-type-specifier. In C that is not correct | ||||||
15701 | // and we should instead merge compatible types found by lookup. | ||||||
15702 | if (getLangOpts().CPlusPlus) { | ||||||
15703 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | ||||||
15704 | LookupQualifiedName(Previous, SearchDC); | ||||||
15705 | } else { | ||||||
15706 | Previous.setRedeclarationKind(forRedeclarationInCurContext()); | ||||||
15707 | LookupName(Previous, S); | ||||||
15708 | } | ||||||
15709 | } | ||||||
15710 | |||||||
15711 | // If we have a known previous declaration to use, then use it. | ||||||
15712 | if (Previous.empty() && SkipBody && SkipBody->Previous) | ||||||
15713 | Previous.addDecl(SkipBody->Previous); | ||||||
15714 | |||||||
15715 | if (!Previous.empty()) { | ||||||
15716 | NamedDecl *PrevDecl = Previous.getFoundDecl(); | ||||||
15717 | NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); | ||||||
15718 | |||||||
15719 | // It's okay to have a tag decl in the same scope as a typedef | ||||||
15720 | // which hides a tag decl in the same scope. Finding this | ||||||
15721 | // insanity with a redeclaration lookup can only actually happen | ||||||
15722 | // in C++. | ||||||
15723 | // | ||||||
15724 | // This is also okay for elaborated-type-specifiers, which is | ||||||
15725 | // technically forbidden by the current standard but which is | ||||||
15726 | // okay according to the likely resolution of an open issue; | ||||||
15727 | // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 | ||||||
15728 | if (getLangOpts().CPlusPlus) { | ||||||
15729 | if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { | ||||||
15730 | if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { | ||||||
15731 | TagDecl *Tag = TT->getDecl(); | ||||||
15732 | if (Tag->getDeclName() == Name && | ||||||
15733 | Tag->getDeclContext()->getRedeclContext() | ||||||
15734 | ->Equals(TD->getDeclContext()->getRedeclContext())) { | ||||||
15735 | PrevDecl = Tag; | ||||||
15736 | Previous.clear(); | ||||||
15737 | Previous.addDecl(Tag); | ||||||
15738 | Previous.resolveKind(); | ||||||
15739 | } | ||||||
15740 | } | ||||||
15741 | } | ||||||
15742 | } | ||||||
15743 | |||||||
15744 | // If this is a redeclaration of a using shadow declaration, it must | ||||||
15745 | // declare a tag in the same context. In MSVC mode, we allow a | ||||||
15746 | // redefinition if either context is within the other. | ||||||
15747 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { | ||||||
15748 | auto *OldTag = dyn_cast<TagDecl>(PrevDecl); | ||||||
15749 | if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && | ||||||
15750 | isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && | ||||||
15751 | !(OldTag && isAcceptableTagRedeclContext( | ||||||
15752 | *this, OldTag->getDeclContext(), SearchDC))) { | ||||||
15753 | Diag(KWLoc, diag::err_using_decl_conflict_reverse); | ||||||
15754 | Diag(Shadow->getTargetDecl()->getLocation(), | ||||||
15755 | diag::note_using_decl_target); | ||||||
15756 | Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) | ||||||
15757 | << 0; | ||||||
15758 | // Recover by ignoring the old declaration. | ||||||
15759 | Previous.clear(); | ||||||
15760 | goto CreateNewDecl; | ||||||
15761 | } | ||||||
15762 | } | ||||||
15763 | |||||||
15764 | if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { | ||||||
15765 | // If this is a use of a previous tag, or if the tag is already declared | ||||||
15766 | // in the same scope (so that the definition/declaration completes or | ||||||
15767 | // rementions the tag), reuse the decl. | ||||||
15768 | if (TUK == TUK_Reference || TUK == TUK_Friend || | ||||||
15769 | isDeclInScope(DirectPrevDecl, SearchDC, S, | ||||||
15770 | SS.isNotEmpty() || isMemberSpecialization)) { | ||||||
15771 | // Make sure that this wasn't declared as an enum and now used as a | ||||||
15772 | // struct or something similar. | ||||||
15773 | if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, | ||||||
15774 | TUK == TUK_Definition, KWLoc, | ||||||
15775 | Name)) { | ||||||
15776 | bool SafeToContinue | ||||||
15777 | = (PrevTagDecl->getTagKind() != TTK_Enum && | ||||||
15778 | Kind != TTK_Enum); | ||||||
15779 | if (SafeToContinue) | ||||||
15780 | Diag(KWLoc, diag::err_use_with_wrong_tag) | ||||||
15781 | << Name | ||||||
15782 | << FixItHint::CreateReplacement(SourceRange(KWLoc), | ||||||
15783 | PrevTagDecl->getKindName()); | ||||||
15784 | else | ||||||
15785 | Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; | ||||||
15786 | Diag(PrevTagDecl->getLocation(), diag::note_previous_use); | ||||||
15787 | |||||||
15788 | if (SafeToContinue) | ||||||
15789 | Kind = PrevTagDecl->getTagKind(); | ||||||
15790 | else { | ||||||
15791 | // Recover by making this an anonymous redefinition. | ||||||
15792 | Name = nullptr; | ||||||
15793 | Previous.clear(); | ||||||
15794 | Invalid = true; | ||||||
15795 | } | ||||||
15796 | } | ||||||
15797 | |||||||
15798 | if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { | ||||||
15799 | const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); | ||||||
15800 | if (TUK == TUK_Reference || TUK == TUK_Friend) | ||||||
15801 | return PrevTagDecl; | ||||||
15802 | |||||||
15803 | QualType EnumUnderlyingTy; | ||||||
15804 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | ||||||
15805 | EnumUnderlyingTy = TI->getType().getUnqualifiedType(); | ||||||
15806 | else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) | ||||||
15807 | EnumUnderlyingTy = QualType(T, 0); | ||||||
15808 | |||||||
15809 | // All conflicts with previous declarations are recovered by | ||||||
15810 | // returning the previous declaration, unless this is a definition, | ||||||
15811 | // in which case we want the caller to bail out. | ||||||
15812 | if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, | ||||||
15813 | ScopedEnum, EnumUnderlyingTy, | ||||||
15814 | IsFixed, PrevEnum)) | ||||||
15815 | return TUK == TUK_Declaration ? PrevTagDecl : nullptr; | ||||||
15816 | } | ||||||
15817 | |||||||
15818 | // C++11 [class.mem]p1: | ||||||
15819 | // A member shall not be declared twice in the member-specification, | ||||||
15820 | // except that a nested class or member class template can be declared | ||||||
15821 | // and then later defined. | ||||||
15822 | if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && | ||||||
15823 | S->isDeclScope(PrevDecl)) { | ||||||
15824 | Diag(NameLoc, diag::ext_member_redeclared); | ||||||
15825 | Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); | ||||||
15826 | } | ||||||
15827 | |||||||
15828 | if (!Invalid) { | ||||||
15829 | // If this is a use, just return the declaration we found, unless | ||||||
15830 | // we have attributes. | ||||||
15831 | if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||||
15832 | if (!Attrs.empty()) { | ||||||
15833 | // FIXME: Diagnose these attributes. For now, we create a new | ||||||
15834 | // declaration to hold them. | ||||||
15835 | } else if (TUK == TUK_Reference && | ||||||
15836 | (PrevTagDecl->getFriendObjectKind() == | ||||||
15837 | Decl::FOK_Undeclared || | ||||||
15838 | PrevDecl->getOwningModule() != getCurrentModule()) && | ||||||
15839 | SS.isEmpty()) { | ||||||
15840 | // This declaration is a reference to an existing entity, but | ||||||
15841 | // has different visibility from that entity: it either makes | ||||||
15842 | // a friend visible or it makes a type visible in a new module. | ||||||
15843 | // In either case, create a new declaration. We only do this if | ||||||
15844 | // the declaration would have meant the same thing if no prior | ||||||
15845 | // declaration were found, that is, if it was found in the same | ||||||
15846 | // scope where we would have injected a declaration. | ||||||
15847 | if (!getTagInjectionContext(CurContext)->getRedeclContext() | ||||||
15848 | ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) | ||||||
15849 | return PrevTagDecl; | ||||||
15850 | // This is in the injected scope, create a new declaration in | ||||||
15851 | // that scope. | ||||||
15852 | S = getTagInjectionScope(S, getLangOpts()); | ||||||
15853 | } else { | ||||||
15854 | return PrevTagDecl; | ||||||
15855 | } | ||||||
15856 | } | ||||||
15857 | |||||||
15858 | // Diagnose attempts to redefine a tag. | ||||||
15859 | if (TUK == TUK_Definition) { | ||||||
15860 | if (NamedDecl *Def = PrevTagDecl->getDefinition()) { | ||||||
15861 | // If we're defining a specialization and the previous definition | ||||||
15862 | // is from an implicit instantiation, don't emit an error | ||||||
15863 | // here; we'll catch this in the general case below. | ||||||
15864 | bool IsExplicitSpecializationAfterInstantiation = false; | ||||||
15865 | if (isMemberSpecialization) { | ||||||
15866 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) | ||||||
15867 | IsExplicitSpecializationAfterInstantiation = | ||||||
15868 | RD->getTemplateSpecializationKind() != | ||||||
15869 | TSK_ExplicitSpecialization; | ||||||
15870 | else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) | ||||||
15871 | IsExplicitSpecializationAfterInstantiation = | ||||||
15872 | ED->getTemplateSpecializationKind() != | ||||||
15873 | TSK_ExplicitSpecialization; | ||||||
15874 | } | ||||||
15875 | |||||||
15876 | // Note that clang allows ODR-like semantics for ObjC/C, i.e., do | ||||||
15877 | // not keep more that one definition around (merge them). However, | ||||||
15878 | // ensure the decl passes the structural compatibility check in | ||||||
15879 | // C11 6.2.7/1 (or 6.1.2.6/1 in C89). | ||||||
15880 | NamedDecl *Hidden = nullptr; | ||||||
15881 | if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { | ||||||
15882 | // There is a definition of this tag, but it is not visible. We | ||||||
15883 | // explicitly make use of C++'s one definition rule here, and | ||||||
15884 | // assume that this definition is identical to the hidden one | ||||||
15885 | // we already have. Make the existing definition visible and | ||||||
15886 | // use it in place of this one. | ||||||
15887 | if (!getLangOpts().CPlusPlus) { | ||||||
15888 | // Postpone making the old definition visible until after we | ||||||
15889 | // complete parsing the new one and do the structural | ||||||
15890 | // comparison. | ||||||
15891 | SkipBody->CheckSameAsPrevious = true; | ||||||
15892 | SkipBody->New = createTagFromNewDecl(); | ||||||
15893 | SkipBody->Previous = Def; | ||||||
15894 | return Def; | ||||||
15895 | } else { | ||||||
15896 | SkipBody->ShouldSkip = true; | ||||||
15897 | SkipBody->Previous = Def; | ||||||
15898 | makeMergedDefinitionVisible(Hidden); | ||||||
15899 | // Carry on and handle it like a normal definition. We'll | ||||||
15900 | // skip starting the definitiion later. | ||||||
15901 | } | ||||||
15902 | } else if (!IsExplicitSpecializationAfterInstantiation) { | ||||||
15903 | // A redeclaration in function prototype scope in C isn't | ||||||
15904 | // visible elsewhere, so merely issue a warning. | ||||||
15905 | if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) | ||||||
15906 | Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; | ||||||
15907 | else | ||||||
15908 | Diag(NameLoc, diag::err_redefinition) << Name; | ||||||
15909 | notePreviousDefinition(Def, | ||||||
15910 | NameLoc.isValid() ? NameLoc : KWLoc); | ||||||
15911 | // If this is a redefinition, recover by making this | ||||||
15912 | // struct be anonymous, which will make any later | ||||||
15913 | // references get the previous definition. | ||||||
15914 | Name = nullptr; | ||||||
15915 | Previous.clear(); | ||||||
15916 | Invalid = true; | ||||||
15917 | } | ||||||
15918 | } else { | ||||||
15919 | // If the type is currently being defined, complain | ||||||
15920 | // about a nested redefinition. | ||||||
15921 | auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); | ||||||
15922 | if (TD->isBeingDefined()) { | ||||||
15923 | Diag(NameLoc, diag::err_nested_redefinition) << Name; | ||||||
15924 | Diag(PrevTagDecl->getLocation(), | ||||||
15925 | diag::note_previous_definition); | ||||||
15926 | Name = nullptr; | ||||||
15927 | Previous.clear(); | ||||||
15928 | Invalid = true; | ||||||
15929 | } | ||||||
15930 | } | ||||||
15931 | |||||||
15932 | // Okay, this is definition of a previously declared or referenced | ||||||
15933 | // tag. We're going to create a new Decl for it. | ||||||
15934 | } | ||||||
15935 | |||||||
15936 | // Okay, we're going to make a redeclaration. If this is some kind | ||||||
15937 | // of reference, make sure we build the redeclaration in the same DC | ||||||
15938 | // as the original, and ignore the current access specifier. | ||||||
15939 | if (TUK == TUK_Friend || TUK == TUK_Reference) { | ||||||
15940 | SearchDC = PrevTagDecl->getDeclContext(); | ||||||
15941 | AS = AS_none; | ||||||
15942 | } | ||||||
15943 | } | ||||||
15944 | // If we get here we have (another) forward declaration or we | ||||||
15945 | // have a definition. Just create a new decl. | ||||||
15946 | |||||||
15947 | } else { | ||||||
15948 | // If we get here, this is a definition of a new tag type in a nested | ||||||
15949 | // scope, e.g. "struct foo; void bar() { struct foo; }", just create a | ||||||
15950 | // new decl/type. We set PrevDecl to NULL so that the entities | ||||||
15951 | // have distinct types. | ||||||
15952 | Previous.clear(); | ||||||
15953 | } | ||||||
15954 | // If we get here, we're going to create a new Decl. If PrevDecl | ||||||
15955 | // is non-NULL, it's a definition of the tag declared by | ||||||
15956 | // PrevDecl. If it's NULL, we have a new definition. | ||||||
15957 | |||||||
15958 | // Otherwise, PrevDecl is not a tag, but was found with tag | ||||||
15959 | // lookup. This is only actually possible in C++, where a few | ||||||
15960 | // things like templates still live in the tag namespace. | ||||||
15961 | } else { | ||||||
15962 | // Use a better diagnostic if an elaborated-type-specifier | ||||||
15963 | // found the wrong kind of type on the first | ||||||
15964 | // (non-redeclaration) lookup. | ||||||
15965 | if ((TUK == TUK_Reference || TUK == TUK_Friend) && | ||||||
15966 | !Previous.isForRedeclaration()) { | ||||||
15967 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | ||||||
15968 | Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK | ||||||
15969 | << Kind; | ||||||
15970 | Diag(PrevDecl->getLocation(), diag::note_declared_at); | ||||||
15971 | Invalid = true; | ||||||
15972 | |||||||
15973 | // Otherwise, only diagnose if the declaration is in scope. | ||||||
15974 | } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, | ||||||
15975 | SS.isNotEmpty() || isMemberSpecialization)) { | ||||||
15976 | // do nothing | ||||||
15977 | |||||||
15978 | // Diagnose implicit declarations introduced by elaborated types. | ||||||
15979 | } else if (TUK == TUK_Reference || TUK == TUK_Friend) { | ||||||
15980 | NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); | ||||||
15981 | Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; | ||||||
15982 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | ||||||
15983 | Invalid = true; | ||||||
15984 | |||||||
15985 | // Otherwise it's a declaration. Call out a particularly common | ||||||
15986 | // case here. | ||||||
15987 | } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { | ||||||
15988 | unsigned Kind = 0; | ||||||
15989 | if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; | ||||||
15990 | Diag(NameLoc, diag::err_tag_definition_of_typedef) | ||||||
15991 | << Name << Kind << TND->getUnderlyingType(); | ||||||
15992 | Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; | ||||||
15993 | Invalid = true; | ||||||
15994 | |||||||
15995 | // Otherwise, diagnose. | ||||||
15996 | } else { | ||||||
15997 | // The tag name clashes with something else in the target scope, | ||||||
15998 | // issue an error and recover by making this tag be anonymous. | ||||||
15999 | Diag(NameLoc, diag::err_redefinition_different_kind) << Name; | ||||||
16000 | notePreviousDefinition(PrevDecl, NameLoc); | ||||||
16001 | Name = nullptr; | ||||||
16002 | Invalid = true; | ||||||
16003 | } | ||||||
16004 | |||||||
16005 | // The existing declaration isn't relevant to us; we're in a | ||||||
16006 | // new scope, so clear out the previous declaration. | ||||||
16007 | Previous.clear(); | ||||||
16008 | } | ||||||
16009 | } | ||||||
16010 | |||||||
16011 | CreateNewDecl: | ||||||
16012 | |||||||
16013 | TagDecl *PrevDecl = nullptr; | ||||||
16014 | if (Previous.isSingleResult()) | ||||||
16015 | PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); | ||||||
16016 | |||||||
16017 | // If there is an identifier, use the location of the identifier as the | ||||||
16018 | // location of the decl, otherwise use the location of the struct/union | ||||||
16019 | // keyword. | ||||||
16020 | SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; | ||||||
16021 | |||||||
16022 | // Otherwise, create a new declaration. If there is a previous | ||||||
16023 | // declaration of the same entity, the two will be linked via | ||||||
16024 | // PrevDecl. | ||||||
16025 | TagDecl *New; | ||||||
16026 | |||||||
16027 | if (Kind == TTK_Enum) { | ||||||
16028 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | ||||||
16029 | // enum X { A, B, C } D; D should chain to X. | ||||||
16030 | New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, | ||||||
16031 | cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, | ||||||
16032 | ScopedEnumUsesClassTag, IsFixed); | ||||||
16033 | |||||||
16034 | if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) | ||||||
16035 | StdAlignValT = cast<EnumDecl>(New); | ||||||
16036 | |||||||
16037 | // If this is an undefined enum, warn. | ||||||
16038 | if (TUK != TUK_Definition && !Invalid) { | ||||||
16039 | TagDecl *Def; | ||||||
16040 | if (IsFixed && cast<EnumDecl>(New)->isFixed()) { | ||||||
16041 | // C++0x: 7.2p2: opaque-enum-declaration. | ||||||
16042 | // Conflicts are diagnosed above. Do nothing. | ||||||
16043 | } | ||||||
16044 | else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { | ||||||
16045 | Diag(Loc, diag::ext_forward_ref_enum_def) | ||||||
16046 | << New; | ||||||
16047 | Diag(Def->getLocation(), diag::note_previous_definition); | ||||||
16048 | } else { | ||||||
16049 | unsigned DiagID = diag::ext_forward_ref_enum; | ||||||
16050 | if (getLangOpts().MSVCCompat) | ||||||
16051 | DiagID = diag::ext_ms_forward_ref_enum; | ||||||
16052 | else if (getLangOpts().CPlusPlus) | ||||||
16053 | DiagID = diag::err_forward_ref_enum; | ||||||
16054 | Diag(Loc, DiagID); | ||||||
16055 | } | ||||||
16056 | } | ||||||
16057 | |||||||
16058 | if (EnumUnderlying) { | ||||||
16059 | EnumDecl *ED = cast<EnumDecl>(New); | ||||||
16060 | if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) | ||||||
16061 | ED->setIntegerTypeSourceInfo(TI); | ||||||
16062 | else | ||||||
16063 | ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); | ||||||
16064 | ED->setPromotionType(ED->getIntegerType()); | ||||||
16065 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16065, __PRETTY_FUNCTION__)); | ||||||
16066 | } | ||||||
16067 | } else { | ||||||
16068 | // struct/union/class | ||||||
16069 | |||||||
16070 | // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: | ||||||
16071 | // struct X { int A; } D; D should chain to X. | ||||||
16072 | if (getLangOpts().CPlusPlus) { | ||||||
16073 | // FIXME: Look for a way to use RecordDecl for simple structs. | ||||||
16074 | New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
16075 | cast_or_null<CXXRecordDecl>(PrevDecl)); | ||||||
16076 | |||||||
16077 | if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) | ||||||
16078 | StdBadAlloc = cast<CXXRecordDecl>(New); | ||||||
16079 | } else | ||||||
16080 | New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, | ||||||
16081 | cast_or_null<RecordDecl>(PrevDecl)); | ||||||
16082 | } | ||||||
16083 | |||||||
16084 | // C++11 [dcl.type]p3: | ||||||
16085 | // A type-specifier-seq shall not define a class or enumeration [...]. | ||||||
16086 | if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && | ||||||
16087 | TUK == TUK_Definition) { | ||||||
16088 | Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) | ||||||
16089 | << Context.getTagDeclType(New); | ||||||
16090 | Invalid = true; | ||||||
16091 | } | ||||||
16092 | |||||||
16093 | if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && | ||||||
16094 | DC->getDeclKind() == Decl::Enum) { | ||||||
16095 | Diag(New->getLocation(), diag::err_type_defined_in_enum) | ||||||
16096 | << Context.getTagDeclType(New); | ||||||
16097 | Invalid = true; | ||||||
16098 | } | ||||||
16099 | |||||||
16100 | // Maybe add qualifier info. | ||||||
16101 | if (SS.isNotEmpty()) { | ||||||
16102 | if (SS.isSet()) { | ||||||
16103 | // If this is either a declaration or a definition, check the | ||||||
16104 | // nested-name-specifier against the current context. | ||||||
16105 | if ((TUK == TUK_Definition || TUK == TUK_Declaration) && | ||||||
16106 | diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, | ||||||
16107 | isMemberSpecialization)) | ||||||
16108 | Invalid = true; | ||||||
16109 | |||||||
16110 | New->setQualifierInfo(SS.getWithLocInContext(Context)); | ||||||
16111 | if (TemplateParameterLists.size() > 0) { | ||||||
16112 | New->setTemplateParameterListsInfo(Context, TemplateParameterLists); | ||||||
16113 | } | ||||||
16114 | } | ||||||
16115 | else | ||||||
16116 | Invalid = true; | ||||||
16117 | } | ||||||
16118 | |||||||
16119 | if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { | ||||||
16120 | // Add alignment attributes if necessary; these attributes are checked when | ||||||
16121 | // the ASTContext lays out the structure. | ||||||
16122 | // | ||||||
16123 | // It is important for implementing the correct semantics that this | ||||||
16124 | // happen here (in ActOnTag). The #pragma pack stack is | ||||||
16125 | // maintained as a result of parser callbacks which can occur at | ||||||
16126 | // many points during the parsing of a struct declaration (because | ||||||
16127 | // the #pragma tokens are effectively skipped over during the | ||||||
16128 | // parsing of the struct). | ||||||
16129 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { | ||||||
16130 | AddAlignmentAttributesForRecord(RD); | ||||||
16131 | AddMsStructLayoutForRecord(RD); | ||||||
16132 | } | ||||||
16133 | } | ||||||
16134 | |||||||
16135 | if (ModulePrivateLoc.isValid()) { | ||||||
16136 | if (isMemberSpecialization) | ||||||
16137 | Diag(New->getLocation(), diag::err_module_private_specialization) | ||||||
16138 | << 2 | ||||||
16139 | << FixItHint::CreateRemoval(ModulePrivateLoc); | ||||||
16140 | // __module_private__ does not apply to local classes. However, we only | ||||||
16141 | // diagnose this as an error when the declaration specifiers are | ||||||
16142 | // freestanding. Here, we just ignore the __module_private__. | ||||||
16143 | else if (!SearchDC->isFunctionOrMethod()) | ||||||
16144 | New->setModulePrivate(); | ||||||
16145 | } | ||||||
16146 | |||||||
16147 | // If this is a specialization of a member class (of a class template), | ||||||
16148 | // check the specialization. | ||||||
16149 | if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) | ||||||
16150 | Invalid = true; | ||||||
16151 | |||||||
16152 | // If we're declaring or defining a tag in function prototype scope in C, | ||||||
16153 | // note that this type can only be used within the function and add it to | ||||||
16154 | // the list of decls to inject into the function definition scope. | ||||||
16155 | if ((Name || Kind == TTK_Enum) && | ||||||
16156 | getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { | ||||||
16157 | if (getLangOpts().CPlusPlus) { | ||||||
16158 | // C++ [dcl.fct]p6: | ||||||
16159 | // Types shall not be defined in return or parameter types. | ||||||
16160 | if (TUK == TUK_Definition && !IsTypeSpecifier) { | ||||||
16161 | Diag(Loc, diag::err_type_defined_in_param_type) | ||||||
16162 | << Name; | ||||||
16163 | Invalid = true; | ||||||
16164 | } | ||||||
16165 | } else if (!PrevDecl) { | ||||||
16166 | Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); | ||||||
16167 | } | ||||||
16168 | } | ||||||
16169 | |||||||
16170 | if (Invalid) | ||||||
16171 | New->setInvalidDecl(); | ||||||
16172 | |||||||
16173 | // Set the lexical context. If the tag has a C++ scope specifier, the | ||||||
16174 | // lexical context will be different from the semantic context. | ||||||
16175 | New->setLexicalDeclContext(CurContext); | ||||||
16176 | |||||||
16177 | // Mark this as a friend decl if applicable. | ||||||
16178 | // In Microsoft mode, a friend declaration also acts as a forward | ||||||
16179 | // declaration so we always pass true to setObjectOfFriendDecl to make | ||||||
16180 | // the tag name visible. | ||||||
16181 | if (TUK == TUK_Friend) | ||||||
16182 | New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); | ||||||
16183 | |||||||
16184 | // Set the access specifier. | ||||||
16185 | if (!Invalid && SearchDC->isRecord()) | ||||||
16186 | SetMemberAccessSpecifier(New, PrevDecl, AS); | ||||||
16187 | |||||||
16188 | if (PrevDecl) | ||||||
16189 | CheckRedeclarationModuleOwnership(New, PrevDecl); | ||||||
16190 | |||||||
16191 | if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) | ||||||
16192 | New->startDefinition(); | ||||||
16193 | |||||||
16194 | ProcessDeclAttributeList(S, New, Attrs); | ||||||
16195 | AddPragmaAttributes(S, New); | ||||||
16196 | |||||||
16197 | // If this has an identifier, add it to the scope stack. | ||||||
16198 | if (TUK == TUK_Friend) { | ||||||
16199 | // We might be replacing an existing declaration in the lookup tables; | ||||||
16200 | // if so, borrow its access specifier. | ||||||
16201 | if (PrevDecl) | ||||||
16202 | New->setAccess(PrevDecl->getAccess()); | ||||||
16203 | |||||||
16204 | DeclContext *DC = New->getDeclContext()->getRedeclContext(); | ||||||
16205 | DC->makeDeclVisibleInContext(New); | ||||||
16206 | if (Name) // can be null along some error paths | ||||||
16207 | if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) | ||||||
16208 | PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); | ||||||
16209 | } else if (Name) { | ||||||
16210 | S = getNonFieldDeclScope(S); | ||||||
16211 | PushOnScopeChains(New, S, true); | ||||||
16212 | } else { | ||||||
16213 | CurContext->addDecl(New); | ||||||
16214 | } | ||||||
16215 | |||||||
16216 | // If this is the C FILE type, notify the AST context. | ||||||
16217 | if (IdentifierInfo *II = New->getIdentifier()) | ||||||
16218 | if (!New->isInvalidDecl() && | ||||||
16219 | New->getDeclContext()->getRedeclContext()->isTranslationUnit() && | ||||||
16220 | II->isStr("FILE")) | ||||||
16221 | Context.setFILEDecl(New); | ||||||
16222 | |||||||
16223 | if (PrevDecl) | ||||||
16224 | mergeDeclAttributes(New, PrevDecl); | ||||||
16225 | |||||||
16226 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) | ||||||
16227 | inferGslOwnerPointerAttribute(CXXRD); | ||||||
16228 | |||||||
16229 | // If there's a #pragma GCC visibility in scope, set the visibility of this | ||||||
16230 | // record. | ||||||
16231 | AddPushedVisibilityAttribute(New); | ||||||
16232 | |||||||
16233 | if (isMemberSpecialization && !New->isInvalidDecl()) | ||||||
16234 | CompleteMemberSpecialization(New, Previous); | ||||||
16235 | |||||||
16236 | OwnedDecl = true; | ||||||
16237 | // In C++, don't return an invalid declaration. We can't recover well from | ||||||
16238 | // the cases where we make the type anonymous. | ||||||
16239 | if (Invalid && getLangOpts().CPlusPlus) { | ||||||
16240 | if (New->isBeingDefined()) | ||||||
16241 | if (auto RD = dyn_cast<RecordDecl>(New)) | ||||||
16242 | RD->completeDefinition(); | ||||||
16243 | return nullptr; | ||||||
16244 | } else if (SkipBody && SkipBody->ShouldSkip) { | ||||||
16245 | return SkipBody->Previous; | ||||||
16246 | } else { | ||||||
16247 | return New; | ||||||
16248 | } | ||||||
16249 | } | ||||||
16250 | |||||||
16251 | void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { | ||||||
16252 | AdjustDeclIfTemplate(TagD); | ||||||
16253 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
16254 | |||||||
16255 | // Enter the tag context. | ||||||
16256 | PushDeclContext(S, Tag); | ||||||
16257 | |||||||
16258 | ActOnDocumentableDecl(TagD); | ||||||
16259 | |||||||
16260 | // If there's a #pragma GCC visibility in scope, set the visibility of this | ||||||
16261 | // record. | ||||||
16262 | AddPushedVisibilityAttribute(Tag); | ||||||
16263 | } | ||||||
16264 | |||||||
16265 | bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, | ||||||
16266 | SkipBodyInfo &SkipBody) { | ||||||
16267 | if (!hasStructuralCompatLayout(Prev, SkipBody.New)) | ||||||
16268 | return false; | ||||||
16269 | |||||||
16270 | // Make the previous decl visible. | ||||||
16271 | makeMergedDefinitionVisible(SkipBody.Previous); | ||||||
16272 | return true; | ||||||
16273 | } | ||||||
16274 | |||||||
16275 | Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { | ||||||
16276 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16277, __PRETTY_FUNCTION__)) | ||||||
16277 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16277, __PRETTY_FUNCTION__)); | ||||||
16278 | DeclContext *OCD = cast<DeclContext>(IDecl); | ||||||
16279 | assert(OCD->getLexicalParent() == CurContext &&((OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16280, __PRETTY_FUNCTION__)) | ||||||
16280 | "The next DeclContext should be lexically contained in the current one.")((OCD->getLexicalParent() == CurContext && "The next DeclContext should be lexically contained in the current one." ) ? static_cast<void> (0) : __assert_fail ("OCD->getLexicalParent() == CurContext && \"The next DeclContext should be lexically contained in the current one.\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16280, __PRETTY_FUNCTION__)); | ||||||
16281 | CurContext = OCD; | ||||||
16282 | return IDecl; | ||||||
16283 | } | ||||||
16284 | |||||||
16285 | void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, | ||||||
16286 | SourceLocation FinalLoc, | ||||||
16287 | bool IsFinalSpelledSealed, | ||||||
16288 | SourceLocation LBraceLoc) { | ||||||
16289 | AdjustDeclIfTemplate(TagD); | ||||||
16290 | CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); | ||||||
16291 | |||||||
16292 | FieldCollector->StartClass(); | ||||||
16293 | |||||||
16294 | if (!Record->getIdentifier()) | ||||||
16295 | return; | ||||||
16296 | |||||||
16297 | if (FinalLoc.isValid()) | ||||||
16298 | Record->addAttr(FinalAttr::Create( | ||||||
16299 | Context, FinalLoc, AttributeCommonInfo::AS_Keyword, | ||||||
16300 | static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); | ||||||
16301 | |||||||
16302 | // C++ [class]p2: | ||||||
16303 | // [...] The class-name is also inserted into the scope of the | ||||||
16304 | // class itself; this is known as the injected-class-name. For | ||||||
16305 | // purposes of access checking, the injected-class-name is treated | ||||||
16306 | // as if it were a public member name. | ||||||
16307 | CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( | ||||||
16308 | Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), | ||||||
16309 | Record->getLocation(), Record->getIdentifier(), | ||||||
16310 | /*PrevDecl=*/nullptr, | ||||||
16311 | /*DelayTypeCreation=*/true); | ||||||
16312 | Context.getTypeDeclType(InjectedClassName, Record); | ||||||
16313 | InjectedClassName->setImplicit(); | ||||||
16314 | InjectedClassName->setAccess(AS_public); | ||||||
16315 | if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) | ||||||
16316 | InjectedClassName->setDescribedClassTemplate(Template); | ||||||
16317 | PushOnScopeChains(InjectedClassName, S); | ||||||
16318 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16319, __PRETTY_FUNCTION__)) | ||||||
16319 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16319, __PRETTY_FUNCTION__)); | ||||||
16320 | } | ||||||
16321 | |||||||
16322 | void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, | ||||||
16323 | SourceRange BraceRange) { | ||||||
16324 | AdjustDeclIfTemplate(TagD); | ||||||
16325 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
16326 | Tag->setBraceRange(BraceRange); | ||||||
16327 | |||||||
16328 | // Make sure we "complete" the definition even it is invalid. | ||||||
16329 | if (Tag->isBeingDefined()) { | ||||||
16330 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16330, __PRETTY_FUNCTION__)); | ||||||
16331 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | ||||||
16332 | RD->completeDefinition(); | ||||||
16333 | } | ||||||
16334 | |||||||
16335 | if (isa<CXXRecordDecl>(Tag)) { | ||||||
16336 | FieldCollector->FinishClass(); | ||||||
16337 | } | ||||||
16338 | |||||||
16339 | // Exit this scope of this tag's definition. | ||||||
16340 | PopDeclContext(); | ||||||
16341 | |||||||
16342 | if (getCurLexicalContext()->isObjCContainer() && | ||||||
16343 | Tag->getDeclContext()->isFileContext()) | ||||||
16344 | Tag->setTopLevelDeclInObjCContainer(); | ||||||
16345 | |||||||
16346 | // Notify the consumer that we've defined a tag. | ||||||
16347 | if (!Tag->isInvalidDecl()) | ||||||
16348 | Consumer.HandleTagDeclDefinition(Tag); | ||||||
16349 | } | ||||||
16350 | |||||||
16351 | void Sema::ActOnObjCContainerFinishDefinition() { | ||||||
16352 | // Exit this scope of this interface definition. | ||||||
16353 | PopDeclContext(); | ||||||
16354 | } | ||||||
16355 | |||||||
16356 | void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { | ||||||
16357 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16357, __PRETTY_FUNCTION__)); | ||||||
16358 | OriginalLexicalContext = DC; | ||||||
16359 | ActOnObjCContainerFinishDefinition(); | ||||||
16360 | } | ||||||
16361 | |||||||
16362 | void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { | ||||||
16363 | ActOnObjCContainerStartDefinition(cast<Decl>(DC)); | ||||||
16364 | OriginalLexicalContext = nullptr; | ||||||
16365 | } | ||||||
16366 | |||||||
16367 | void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { | ||||||
16368 | AdjustDeclIfTemplate(TagD); | ||||||
16369 | TagDecl *Tag = cast<TagDecl>(TagD); | ||||||
16370 | Tag->setInvalidDecl(); | ||||||
16371 | |||||||
16372 | // Make sure we "complete" the definition even it is invalid. | ||||||
16373 | if (Tag->isBeingDefined()) { | ||||||
16374 | if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) | ||||||
16375 | RD->completeDefinition(); | ||||||
16376 | } | ||||||
16377 | |||||||
16378 | // We're undoing ActOnTagStartDefinition here, not | ||||||
16379 | // ActOnStartCXXMemberDeclarations, so we don't have to mess with | ||||||
16380 | // the FieldCollector. | ||||||
16381 | |||||||
16382 | PopDeclContext(); | ||||||
16383 | } | ||||||
16384 | |||||||
16385 | // Note that FieldName may be null for anonymous bitfields. | ||||||
16386 | ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, | ||||||
16387 | IdentifierInfo *FieldName, | ||||||
16388 | QualType FieldTy, bool IsMsStruct, | ||||||
16389 | Expr *BitWidth, bool *ZeroWidth) { | ||||||
16390 | assert(BitWidth)((BitWidth) ? static_cast<void> (0) : __assert_fail ("BitWidth" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16390, __PRETTY_FUNCTION__)); | ||||||
16391 | if (BitWidth->containsErrors()) | ||||||
16392 | return ExprError(); | ||||||
16393 | |||||||
16394 | // Default to true; that shouldn't confuse checks for emptiness | ||||||
16395 | if (ZeroWidth) | ||||||
16396 | *ZeroWidth = true; | ||||||
16397 | |||||||
16398 | // C99 6.7.2.1p4 - verify the field type. | ||||||
16399 | // C++ 9.6p3: A bit-field shall have integral or enumeration type. | ||||||
16400 | if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { | ||||||
16401 | // Handle incomplete and sizeless types with a specific error. | ||||||
16402 | if (RequireCompleteSizedType(FieldLoc, FieldTy, | ||||||
16403 | diag::err_field_incomplete_or_sizeless)) | ||||||
16404 | return ExprError(); | ||||||
16405 | if (FieldName) | ||||||
16406 | return Diag(FieldLoc, diag::err_not_integral_type_bitfield) | ||||||
16407 | << FieldName << FieldTy << BitWidth->getSourceRange(); | ||||||
16408 | return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) | ||||||
16409 | << FieldTy << BitWidth->getSourceRange(); | ||||||
16410 | } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), | ||||||
16411 | UPPC_BitFieldWidth)) | ||||||
16412 | return ExprError(); | ||||||
16413 | |||||||
16414 | // If the bit-width is type- or value-dependent, don't try to check | ||||||
16415 | // it now. | ||||||
16416 | if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) | ||||||
16417 | return BitWidth; | ||||||
16418 | |||||||
16419 | llvm::APSInt Value; | ||||||
16420 | ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); | ||||||
16421 | if (ICE.isInvalid()) | ||||||
16422 | return ICE; | ||||||
16423 | BitWidth = ICE.get(); | ||||||
16424 | |||||||
16425 | if (Value != 0 && ZeroWidth) | ||||||
16426 | *ZeroWidth = false; | ||||||
16427 | |||||||
16428 | // Zero-width bitfield is ok for anonymous field. | ||||||
16429 | if (Value == 0 && FieldName) | ||||||
16430 | return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; | ||||||
16431 | |||||||
16432 | if (Value.isSigned() && Value.isNegative()) { | ||||||
16433 | if (FieldName) | ||||||
16434 | return Diag(FieldLoc, diag::err_bitfield_has_negative_width) | ||||||
16435 | << FieldName << Value.toString(10); | ||||||
16436 | return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) | ||||||
16437 | << Value.toString(10); | ||||||
16438 | } | ||||||
16439 | |||||||
16440 | if (!FieldTy->isDependentType()) { | ||||||
16441 | uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); | ||||||
16442 | uint64_t TypeWidth = Context.getIntWidth(FieldTy); | ||||||
16443 | bool BitfieldIsOverwide = Value.ugt(TypeWidth); | ||||||
16444 | |||||||
16445 | // Over-wide bitfields are an error in C or when using the MSVC bitfield | ||||||
16446 | // ABI. | ||||||
16447 | bool CStdConstraintViolation = | ||||||
16448 | BitfieldIsOverwide && !getLangOpts().CPlusPlus; | ||||||
16449 | bool MSBitfieldViolation = | ||||||
16450 | Value.ugt(TypeStorageSize) && | ||||||
16451 | (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); | ||||||
16452 | if (CStdConstraintViolation || MSBitfieldViolation) { | ||||||
16453 | unsigned DiagWidth = | ||||||
16454 | CStdConstraintViolation ? TypeWidth : TypeStorageSize; | ||||||
16455 | if (FieldName) | ||||||
16456 | return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) | ||||||
16457 | << FieldName << (unsigned)Value.getZExtValue() | ||||||
16458 | << !CStdConstraintViolation << DiagWidth; | ||||||
16459 | |||||||
16460 | return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) | ||||||
16461 | << (unsigned)Value.getZExtValue() << !CStdConstraintViolation | ||||||
16462 | << DiagWidth; | ||||||
16463 | } | ||||||
16464 | |||||||
16465 | // Warn on types where the user might conceivably expect to get all | ||||||
16466 | // specified bits as value bits: that's all integral types other than | ||||||
16467 | // 'bool'. | ||||||
16468 | if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { | ||||||
16469 | if (FieldName) | ||||||
16470 | Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) | ||||||
16471 | << FieldName << (unsigned)Value.getZExtValue() | ||||||
16472 | << (unsigned)TypeWidth; | ||||||
16473 | else | ||||||
16474 | Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) | ||||||
16475 | << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; | ||||||
16476 | } | ||||||
16477 | } | ||||||
16478 | |||||||
16479 | return BitWidth; | ||||||
16480 | } | ||||||
16481 | |||||||
16482 | /// ActOnField - Each field of a C struct/union is passed into this in order | ||||||
16483 | /// to create a FieldDecl object for it. | ||||||
16484 | Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, | ||||||
16485 | Declarator &D, Expr *BitfieldWidth) { | ||||||
16486 | FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), | ||||||
16487 | DeclStart, D, static_cast<Expr*>(BitfieldWidth), | ||||||
16488 | /*InitStyle=*/ICIS_NoInit, AS_public); | ||||||
16489 | return Res; | ||||||
16490 | } | ||||||
16491 | |||||||
16492 | /// HandleField - Analyze a field of a C struct or a C++ data member. | ||||||
16493 | /// | ||||||
16494 | FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, | ||||||
16495 | SourceLocation DeclStart, | ||||||
16496 | Declarator &D, Expr *BitWidth, | ||||||
16497 | InClassInitStyle InitStyle, | ||||||
16498 | AccessSpecifier AS) { | ||||||
16499 | if (D.isDecompositionDeclarator()) { | ||||||
16500 | const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); | ||||||
16501 | Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) | ||||||
16502 | << Decomp.getSourceRange(); | ||||||
16503 | return nullptr; | ||||||
16504 | } | ||||||
16505 | |||||||
16506 | IdentifierInfo *II = D.getIdentifier(); | ||||||
16507 | SourceLocation Loc = DeclStart; | ||||||
16508 | if (II) Loc = D.getIdentifierLoc(); | ||||||
16509 | |||||||
16510 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
16511 | QualType T = TInfo->getType(); | ||||||
16512 | if (getLangOpts().CPlusPlus) { | ||||||
16513 | CheckExtraCXXDefaultArguments(D); | ||||||
16514 | |||||||
16515 | if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, | ||||||
16516 | UPPC_DataMemberType)) { | ||||||
16517 | D.setInvalidType(); | ||||||
16518 | T = Context.IntTy; | ||||||
16519 | TInfo = Context.getTrivialTypeSourceInfo(T, Loc); | ||||||
16520 | } | ||||||
16521 | } | ||||||
16522 | |||||||
16523 | DiagnoseFunctionSpecifiers(D.getDeclSpec()); | ||||||
16524 | |||||||
16525 | if (D.getDeclSpec().isInlineSpecified()) | ||||||
16526 | Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) | ||||||
16527 | << getLangOpts().CPlusPlus17; | ||||||
16528 | if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) | ||||||
16529 | Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), | ||||||
16530 | diag::err_invalid_thread) | ||||||
16531 | << DeclSpec::getSpecifierName(TSCS); | ||||||
16532 | |||||||
16533 | // Check to see if this name was declared as a member previously | ||||||
16534 | NamedDecl *PrevDecl = nullptr; | ||||||
16535 | LookupResult Previous(*this, II, Loc, LookupMemberName, | ||||||
16536 | ForVisibleRedeclaration); | ||||||
16537 | LookupName(Previous, S); | ||||||
16538 | switch (Previous.getResultKind()) { | ||||||
16539 | case LookupResult::Found: | ||||||
16540 | case LookupResult::FoundUnresolvedValue: | ||||||
16541 | PrevDecl = Previous.getAsSingle<NamedDecl>(); | ||||||
16542 | break; | ||||||
16543 | |||||||
16544 | case LookupResult::FoundOverloaded: | ||||||
16545 | PrevDecl = Previous.getRepresentativeDecl(); | ||||||
16546 | break; | ||||||
16547 | |||||||
16548 | case LookupResult::NotFound: | ||||||
16549 | case LookupResult::NotFoundInCurrentInstantiation: | ||||||
16550 | case LookupResult::Ambiguous: | ||||||
16551 | break; | ||||||
16552 | } | ||||||
16553 | Previous.suppressDiagnostics(); | ||||||
16554 | |||||||
16555 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||||
16556 | // Maybe we will complain about the shadowed template parameter. | ||||||
16557 | DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); | ||||||
16558 | // Just pretend that we didn't see the previous declaration. | ||||||
16559 | PrevDecl = nullptr; | ||||||
16560 | } | ||||||
16561 | |||||||
16562 | if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) | ||||||
16563 | PrevDecl = nullptr; | ||||||
16564 | |||||||
16565 | bool Mutable | ||||||
16566 | = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); | ||||||
16567 | SourceLocation TSSL = D.getBeginLoc(); | ||||||
16568 | FieldDecl *NewFD | ||||||
16569 | = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, | ||||||
16570 | TSSL, AS, PrevDecl, &D); | ||||||
16571 | |||||||
16572 | if (NewFD->isInvalidDecl()) | ||||||
16573 | Record->setInvalidDecl(); | ||||||
16574 | |||||||
16575 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
16576 | NewFD->setModulePrivate(); | ||||||
16577 | |||||||
16578 | if (NewFD->isInvalidDecl() && PrevDecl) { | ||||||
16579 | // Don't introduce NewFD into scope; there's already something | ||||||
16580 | // with the same name in the same scope. | ||||||
16581 | } else if (II) { | ||||||
16582 | PushOnScopeChains(NewFD, S); | ||||||
16583 | } else | ||||||
16584 | Record->addDecl(NewFD); | ||||||
16585 | |||||||
16586 | return NewFD; | ||||||
16587 | } | ||||||
16588 | |||||||
16589 | /// Build a new FieldDecl and check its well-formedness. | ||||||
16590 | /// | ||||||
16591 | /// This routine builds a new FieldDecl given the fields name, type, | ||||||
16592 | /// record, etc. \p PrevDecl should refer to any previous declaration | ||||||
16593 | /// with the same name and in the same scope as the field to be | ||||||
16594 | /// created. | ||||||
16595 | /// | ||||||
16596 | /// \returns a new FieldDecl. | ||||||
16597 | /// | ||||||
16598 | /// \todo The Declarator argument is a hack. It will be removed once | ||||||
16599 | FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, | ||||||
16600 | TypeSourceInfo *TInfo, | ||||||
16601 | RecordDecl *Record, SourceLocation Loc, | ||||||
16602 | bool Mutable, Expr *BitWidth, | ||||||
16603 | InClassInitStyle InitStyle, | ||||||
16604 | SourceLocation TSSL, | ||||||
16605 | AccessSpecifier AS, NamedDecl *PrevDecl, | ||||||
16606 | Declarator *D) { | ||||||
16607 | IdentifierInfo *II = Name.getAsIdentifierInfo(); | ||||||
16608 | bool InvalidDecl = false; | ||||||
16609 | if (D) InvalidDecl = D->isInvalidType(); | ||||||
16610 | |||||||
16611 | // If we receive a broken type, recover by assuming 'int' and | ||||||
16612 | // marking this declaration as invalid. | ||||||
16613 | if (T.isNull() || T->containsErrors()) { | ||||||
16614 | InvalidDecl = true; | ||||||
16615 | T = Context.IntTy; | ||||||
16616 | } | ||||||
16617 | |||||||
16618 | QualType EltTy = Context.getBaseElementType(T); | ||||||
16619 | if (!EltTy->isDependentType() && !EltTy->containsErrors()) { | ||||||
16620 | if (RequireCompleteSizedType(Loc, EltTy, | ||||||
16621 | diag::err_field_incomplete_or_sizeless)) { | ||||||
16622 | // Fields of incomplete type force their record to be invalid. | ||||||
16623 | Record->setInvalidDecl(); | ||||||
16624 | InvalidDecl = true; | ||||||
16625 | } else { | ||||||
16626 | NamedDecl *Def; | ||||||
16627 | EltTy->isIncompleteType(&Def); | ||||||
16628 | if (Def && Def->isInvalidDecl()) { | ||||||
16629 | Record->setInvalidDecl(); | ||||||
16630 | InvalidDecl = true; | ||||||
16631 | } | ||||||
16632 | } | ||||||
16633 | } | ||||||
16634 | |||||||
16635 | // TR 18037 does not allow fields to be declared with address space | ||||||
16636 | if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || | ||||||
16637 | T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { | ||||||
16638 | Diag(Loc, diag::err_field_with_address_space); | ||||||
16639 | Record->setInvalidDecl(); | ||||||
16640 | InvalidDecl = true; | ||||||
16641 | } | ||||||
16642 | |||||||
16643 | if (LangOpts.OpenCL) { | ||||||
16644 | // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be | ||||||
16645 | // used as structure or union field: image, sampler, event or block types. | ||||||
16646 | if (T->isEventT() || T->isImageType() || T->isSamplerT() || | ||||||
16647 | T->isBlockPointerType()) { | ||||||
16648 | Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; | ||||||
16649 | Record->setInvalidDecl(); | ||||||
16650 | InvalidDecl = true; | ||||||
16651 | } | ||||||
16652 | // OpenCL v1.2 s6.9.c: bitfields are not supported. | ||||||
16653 | if (BitWidth) { | ||||||
16654 | Diag(Loc, diag::err_opencl_bitfields); | ||||||
16655 | InvalidDecl = true; | ||||||
16656 | } | ||||||
16657 | } | ||||||
16658 | |||||||
16659 | // Anonymous bit-fields cannot be cv-qualified (CWG 2229). | ||||||
16660 | if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && | ||||||
16661 | T.hasQualifiers()) { | ||||||
16662 | InvalidDecl = true; | ||||||
16663 | Diag(Loc, diag::err_anon_bitfield_qualifiers); | ||||||
16664 | } | ||||||
16665 | |||||||
16666 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | ||||||
16667 | // than a variably modified type. | ||||||
16668 | if (!InvalidDecl && T->isVariablyModifiedType()) { | ||||||
16669 | bool SizeIsNegative; | ||||||
16670 | llvm::APSInt Oversized; | ||||||
16671 | |||||||
16672 | TypeSourceInfo *FixedTInfo = | ||||||
16673 | TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, | ||||||
16674 | SizeIsNegative, | ||||||
16675 | Oversized); | ||||||
16676 | if (FixedTInfo) { | ||||||
16677 | Diag(Loc, diag::warn_illegal_constant_array_size); | ||||||
16678 | TInfo = FixedTInfo; | ||||||
16679 | T = FixedTInfo->getType(); | ||||||
16680 | } else { | ||||||
16681 | if (SizeIsNegative) | ||||||
16682 | Diag(Loc, diag::err_typecheck_negative_array_size); | ||||||
16683 | else if (Oversized.getBoolValue()) | ||||||
16684 | Diag(Loc, diag::err_array_too_large) | ||||||
16685 | << Oversized.toString(10); | ||||||
16686 | else | ||||||
16687 | Diag(Loc, diag::err_typecheck_field_variable_size); | ||||||
16688 | InvalidDecl = true; | ||||||
16689 | } | ||||||
16690 | } | ||||||
16691 | |||||||
16692 | // Fields can not have abstract class types | ||||||
16693 | if (!InvalidDecl && RequireNonAbstractType(Loc, T, | ||||||
16694 | diag::err_abstract_type_in_decl, | ||||||
16695 | AbstractFieldType)) | ||||||
16696 | InvalidDecl = true; | ||||||
16697 | |||||||
16698 | bool ZeroWidth = false; | ||||||
16699 | if (InvalidDecl) | ||||||
16700 | BitWidth = nullptr; | ||||||
16701 | // If this is declared as a bit-field, check the bit-field. | ||||||
16702 | if (BitWidth) { | ||||||
16703 | BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, | ||||||
16704 | &ZeroWidth).get(); | ||||||
16705 | if (!BitWidth) { | ||||||
16706 | InvalidDecl = true; | ||||||
16707 | BitWidth = nullptr; | ||||||
16708 | ZeroWidth = false; | ||||||
16709 | } | ||||||
16710 | |||||||
16711 | // Only data members can have in-class initializers. | ||||||
16712 | if (BitWidth && !II && InitStyle) { | ||||||
16713 | Diag(Loc, diag::err_anon_bitfield_init); | ||||||
16714 | InvalidDecl = true; | ||||||
16715 | BitWidth = nullptr; | ||||||
16716 | ZeroWidth = false; | ||||||
16717 | } | ||||||
16718 | } | ||||||
16719 | |||||||
16720 | // Check that 'mutable' is consistent with the type of the declaration. | ||||||
16721 | if (!InvalidDecl && Mutable) { | ||||||
16722 | unsigned DiagID = 0; | ||||||
16723 | if (T->isReferenceType()) | ||||||
16724 | DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference | ||||||
16725 | : diag::err_mutable_reference; | ||||||
16726 | else if (T.isConstQualified()) | ||||||
16727 | DiagID = diag::err_mutable_const; | ||||||
16728 | |||||||
16729 | if (DiagID) { | ||||||
16730 | SourceLocation ErrLoc = Loc; | ||||||
16731 | if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) | ||||||
16732 | ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); | ||||||
16733 | Diag(ErrLoc, DiagID); | ||||||
16734 | if (DiagID != diag::ext_mutable_reference) { | ||||||
16735 | Mutable = false; | ||||||
16736 | InvalidDecl = true; | ||||||
16737 | } | ||||||
16738 | } | ||||||
16739 | } | ||||||
16740 | |||||||
16741 | // C++11 [class.union]p8 (DR1460): | ||||||
16742 | // At most one variant member of a union may have a | ||||||
16743 | // brace-or-equal-initializer. | ||||||
16744 | if (InitStyle != ICIS_NoInit) | ||||||
16745 | checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); | ||||||
16746 | |||||||
16747 | FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, | ||||||
16748 | BitWidth, Mutable, InitStyle); | ||||||
16749 | if (InvalidDecl) | ||||||
16750 | NewFD->setInvalidDecl(); | ||||||
16751 | |||||||
16752 | if (PrevDecl && !isa<TagDecl>(PrevDecl)) { | ||||||
16753 | Diag(Loc, diag::err_duplicate_member) << II; | ||||||
16754 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
16755 | NewFD->setInvalidDecl(); | ||||||
16756 | } | ||||||
16757 | |||||||
16758 | if (!InvalidDecl && getLangOpts().CPlusPlus) { | ||||||
16759 | if (Record->isUnion()) { | ||||||
16760 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | ||||||
16761 | CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||||
16762 | if (RDecl->getDefinition()) { | ||||||
16763 | // C++ [class.union]p1: An object of a class with a non-trivial | ||||||
16764 | // constructor, a non-trivial copy constructor, a non-trivial | ||||||
16765 | // destructor, or a non-trivial copy assignment operator | ||||||
16766 | // cannot be a member of a union, nor can an array of such | ||||||
16767 | // objects. | ||||||
16768 | if (CheckNontrivialField(NewFD)) | ||||||
16769 | NewFD->setInvalidDecl(); | ||||||
16770 | } | ||||||
16771 | } | ||||||
16772 | |||||||
16773 | // C++ [class.union]p1: If a union contains a member of reference type, | ||||||
16774 | // the program is ill-formed, except when compiling with MSVC extensions | ||||||
16775 | // enabled. | ||||||
16776 | if (EltTy->isReferenceType()) { | ||||||
16777 | Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? | ||||||
16778 | diag::ext_union_member_of_reference_type : | ||||||
16779 | diag::err_union_member_of_reference_type) | ||||||
16780 | << NewFD->getDeclName() << EltTy; | ||||||
16781 | if (!getLangOpts().MicrosoftExt) | ||||||
16782 | NewFD->setInvalidDecl(); | ||||||
16783 | } | ||||||
16784 | } | ||||||
16785 | } | ||||||
16786 | |||||||
16787 | // FIXME: We need to pass in the attributes given an AST | ||||||
16788 | // representation, not a parser representation. | ||||||
16789 | if (D) { | ||||||
16790 | // FIXME: The current scope is almost... but not entirely... correct here. | ||||||
16791 | ProcessDeclAttributes(getCurScope(), NewFD, *D); | ||||||
16792 | |||||||
16793 | if (NewFD->hasAttrs()) | ||||||
16794 | CheckAlignasUnderalignment(NewFD); | ||||||
16795 | } | ||||||
16796 | |||||||
16797 | // In auto-retain/release, infer strong retension for fields of | ||||||
16798 | // retainable type. | ||||||
16799 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) | ||||||
16800 | NewFD->setInvalidDecl(); | ||||||
16801 | |||||||
16802 | if (T.isObjCGCWeak()) | ||||||
16803 | Diag(Loc, diag::warn_attribute_weak_on_field); | ||||||
16804 | |||||||
16805 | NewFD->setAccess(AS); | ||||||
16806 | return NewFD; | ||||||
16807 | } | ||||||
16808 | |||||||
16809 | bool Sema::CheckNontrivialField(FieldDecl *FD) { | ||||||
16810 | assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16810, __PRETTY_FUNCTION__)); | ||||||
16811 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16811, __PRETTY_FUNCTION__)); | ||||||
16812 | |||||||
16813 | if (FD->isInvalidDecl() || FD->getType()->isDependentType()) | ||||||
16814 | return false; | ||||||
16815 | |||||||
16816 | QualType EltTy = Context.getBaseElementType(FD->getType()); | ||||||
16817 | if (const RecordType *RT = EltTy->getAs<RecordType>()) { | ||||||
16818 | CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); | ||||||
16819 | if (RDecl->getDefinition()) { | ||||||
16820 | // We check for copy constructors before constructors | ||||||
16821 | // because otherwise we'll never get complaints about | ||||||
16822 | // copy constructors. | ||||||
16823 | |||||||
16824 | CXXSpecialMember member = CXXInvalid; | ||||||
16825 | // We're required to check for any non-trivial constructors. Since the | ||||||
16826 | // implicit default constructor is suppressed if there are any | ||||||
16827 | // user-declared constructors, we just need to check that there is a | ||||||
16828 | // trivial default constructor and a trivial copy constructor. (We don't | ||||||
16829 | // worry about move constructors here, since this is a C++98 check.) | ||||||
16830 | if (RDecl->hasNonTrivialCopyConstructor()) | ||||||
16831 | member = CXXCopyConstructor; | ||||||
16832 | else if (!RDecl->hasTrivialDefaultConstructor()) | ||||||
16833 | member = CXXDefaultConstructor; | ||||||
16834 | else if (RDecl->hasNonTrivialCopyAssignment()) | ||||||
16835 | member = CXXCopyAssignment; | ||||||
16836 | else if (RDecl->hasNonTrivialDestructor()) | ||||||
16837 | member = CXXDestructor; | ||||||
16838 | |||||||
16839 | if (member != CXXInvalid) { | ||||||
16840 | if (!getLangOpts().CPlusPlus11 && | ||||||
16841 | getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { | ||||||
16842 | // Objective-C++ ARC: it is an error to have a non-trivial field of | ||||||
16843 | // a union. However, system headers in Objective-C programs | ||||||
16844 | // occasionally have Objective-C lifetime objects within unions, | ||||||
16845 | // and rather than cause the program to fail, we make those | ||||||
16846 | // members unavailable. | ||||||
16847 | SourceLocation Loc = FD->getLocation(); | ||||||
16848 | if (getSourceManager().isInSystemHeader(Loc)) { | ||||||
16849 | if (!FD->hasAttr<UnavailableAttr>()) | ||||||
16850 | FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", | ||||||
16851 | UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); | ||||||
16852 | return false; | ||||||
16853 | } | ||||||
16854 | } | ||||||
16855 | |||||||
16856 | Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? | ||||||
16857 | diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : | ||||||
16858 | diag::err_illegal_union_or_anon_struct_member) | ||||||
16859 | << FD->getParent()->isUnion() << FD->getDeclName() << member; | ||||||
16860 | DiagnoseNontrivial(RDecl, member); | ||||||
16861 | return !getLangOpts().CPlusPlus11; | ||||||
16862 | } | ||||||
16863 | } | ||||||
16864 | } | ||||||
16865 | |||||||
16866 | return false; | ||||||
16867 | } | ||||||
16868 | |||||||
16869 | /// TranslateIvarVisibility - Translate visibility from a token ID to an | ||||||
16870 | /// AST enum value. | ||||||
16871 | static ObjCIvarDecl::AccessControl | ||||||
16872 | TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { | ||||||
16873 | switch (ivarVisibility) { | ||||||
16874 | default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16874); | ||||||
16875 | case tok::objc_private: return ObjCIvarDecl::Private; | ||||||
16876 | case tok::objc_public: return ObjCIvarDecl::Public; | ||||||
16877 | case tok::objc_protected: return ObjCIvarDecl::Protected; | ||||||
16878 | case tok::objc_package: return ObjCIvarDecl::Package; | ||||||
16879 | } | ||||||
16880 | } | ||||||
16881 | |||||||
16882 | /// ActOnIvar - Each ivar field of an objective-c class is passed into this | ||||||
16883 | /// in order to create an IvarDecl object for it. | ||||||
16884 | Decl *Sema::ActOnIvar(Scope *S, | ||||||
16885 | SourceLocation DeclStart, | ||||||
16886 | Declarator &D, Expr *BitfieldWidth, | ||||||
16887 | tok::ObjCKeywordKind Visibility) { | ||||||
16888 | |||||||
16889 | IdentifierInfo *II = D.getIdentifier(); | ||||||
16890 | Expr *BitWidth = (Expr*)BitfieldWidth; | ||||||
16891 | SourceLocation Loc = DeclStart; | ||||||
16892 | if (II) Loc = D.getIdentifierLoc(); | ||||||
16893 | |||||||
16894 | // FIXME: Unnamed fields can be handled in various different ways, for | ||||||
16895 | // example, unnamed unions inject all members into the struct namespace! | ||||||
16896 | |||||||
16897 | TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); | ||||||
16898 | QualType T = TInfo->getType(); | ||||||
16899 | |||||||
16900 | if (BitWidth) { | ||||||
16901 | // 6.7.2.1p3, 6.7.2.1p4 | ||||||
16902 | BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); | ||||||
16903 | if (!BitWidth) | ||||||
16904 | D.setInvalidType(); | ||||||
16905 | } else { | ||||||
16906 | // Not a bitfield. | ||||||
16907 | |||||||
16908 | // validate II. | ||||||
16909 | |||||||
16910 | } | ||||||
16911 | if (T->isReferenceType()) { | ||||||
16912 | Diag(Loc, diag::err_ivar_reference_type); | ||||||
16913 | D.setInvalidType(); | ||||||
16914 | } | ||||||
16915 | // C99 6.7.2.1p8: A member of a structure or union may have any type other | ||||||
16916 | // than a variably modified type. | ||||||
16917 | else if (T->isVariablyModifiedType()) { | ||||||
16918 | Diag(Loc, diag::err_typecheck_ivar_variable_size); | ||||||
16919 | D.setInvalidType(); | ||||||
16920 | } | ||||||
16921 | |||||||
16922 | // Get the visibility (access control) for this ivar. | ||||||
16923 | ObjCIvarDecl::AccessControl ac = | ||||||
16924 | Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) | ||||||
16925 | : ObjCIvarDecl::None; | ||||||
16926 | // Must set ivar's DeclContext to its enclosing interface. | ||||||
16927 | ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); | ||||||
16928 | if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) | ||||||
16929 | return nullptr; | ||||||
16930 | ObjCContainerDecl *EnclosingContext; | ||||||
16931 | if (ObjCImplementationDecl *IMPDecl = | ||||||
16932 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | ||||||
16933 | if (LangOpts.ObjCRuntime.isFragile()) { | ||||||
16934 | // Case of ivar declared in an implementation. Context is that of its class. | ||||||
16935 | EnclosingContext = IMPDecl->getClassInterface(); | ||||||
16936 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 16936, __PRETTY_FUNCTION__)); | ||||||
16937 | } | ||||||
16938 | else | ||||||
16939 | EnclosingContext = EnclosingDecl; | ||||||
16940 | } else { | ||||||
16941 | if (ObjCCategoryDecl *CDecl = | ||||||
16942 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | ||||||
16943 | if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { | ||||||
16944 | Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); | ||||||
16945 | return nullptr; | ||||||
16946 | } | ||||||
16947 | } | ||||||
16948 | EnclosingContext = EnclosingDecl; | ||||||
16949 | } | ||||||
16950 | |||||||
16951 | // Construct the decl. | ||||||
16952 | ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, | ||||||
16953 | DeclStart, Loc, II, T, | ||||||
16954 | TInfo, ac, (Expr *)BitfieldWidth); | ||||||
16955 | |||||||
16956 | if (II) { | ||||||
16957 | NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, | ||||||
16958 | ForVisibleRedeclaration); | ||||||
16959 | if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) | ||||||
16960 | && !isa<TagDecl>(PrevDecl)) { | ||||||
16961 | Diag(Loc, diag::err_duplicate_member) << II; | ||||||
16962 | Diag(PrevDecl->getLocation(), diag::note_previous_declaration); | ||||||
16963 | NewID->setInvalidDecl(); | ||||||
16964 | } | ||||||
16965 | } | ||||||
16966 | |||||||
16967 | // Process attributes attached to the ivar. | ||||||
16968 | ProcessDeclAttributes(S, NewID, D); | ||||||
16969 | |||||||
16970 | if (D.isInvalidType()) | ||||||
16971 | NewID->setInvalidDecl(); | ||||||
16972 | |||||||
16973 | // In ARC, infer 'retaining' for ivars of retainable type. | ||||||
16974 | if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) | ||||||
16975 | NewID->setInvalidDecl(); | ||||||
16976 | |||||||
16977 | if (D.getDeclSpec().isModulePrivateSpecified()) | ||||||
16978 | NewID->setModulePrivate(); | ||||||
16979 | |||||||
16980 | if (II) { | ||||||
16981 | // FIXME: When interfaces are DeclContexts, we'll need to add | ||||||
16982 | // these to the interface. | ||||||
16983 | S->AddDecl(NewID); | ||||||
16984 | IdResolver.AddDecl(NewID); | ||||||
16985 | } | ||||||
16986 | |||||||
16987 | if (LangOpts.ObjCRuntime.isNonFragile() && | ||||||
16988 | !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) | ||||||
16989 | Diag(Loc, diag::warn_ivars_in_interface); | ||||||
16990 | |||||||
16991 | return NewID; | ||||||
16992 | } | ||||||
16993 | |||||||
16994 | /// ActOnLastBitfield - This routine handles synthesized bitfields rules for | ||||||
16995 | /// class and class extensions. For every class \@interface and class | ||||||
16996 | /// extension \@interface, if the last ivar is a bitfield of any type, | ||||||
16997 | /// then add an implicit `char :0` ivar to the end of that interface. | ||||||
16998 | void Sema::ActOnLastBitfield(SourceLocation DeclLoc, | ||||||
16999 | SmallVectorImpl<Decl *> &AllIvarDecls) { | ||||||
17000 | if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) | ||||||
17001 | return; | ||||||
17002 | |||||||
17003 | Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; | ||||||
17004 | ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); | ||||||
17005 | |||||||
17006 | if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) | ||||||
17007 | return; | ||||||
17008 | ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); | ||||||
17009 | if (!ID) { | ||||||
17010 | if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { | ||||||
17011 | if (!CD->IsClassExtension()) | ||||||
17012 | return; | ||||||
17013 | } | ||||||
17014 | // No need to add this to end of @implementation. | ||||||
17015 | else | ||||||
17016 | return; | ||||||
17017 | } | ||||||
17018 | // All conditions are met. Add a new bitfield to the tail end of ivars. | ||||||
17019 | llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); | ||||||
17020 | Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); | ||||||
17021 | |||||||
17022 | Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), | ||||||
17023 | DeclLoc, DeclLoc, nullptr, | ||||||
17024 | Context.CharTy, | ||||||
17025 | Context.getTrivialTypeSourceInfo(Context.CharTy, | ||||||
17026 | DeclLoc), | ||||||
17027 | ObjCIvarDecl::Private, BW, | ||||||
17028 | true); | ||||||
17029 | AllIvarDecls.push_back(Ivar); | ||||||
17030 | } | ||||||
17031 | |||||||
17032 | void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, | ||||||
17033 | ArrayRef<Decl *> Fields, SourceLocation LBrac, | ||||||
17034 | SourceLocation RBrac, | ||||||
17035 | const ParsedAttributesView &Attrs) { | ||||||
17036 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17036, __PRETTY_FUNCTION__)); | ||||||
17037 | |||||||
17038 | // If this is an Objective-C @implementation or category and we have | ||||||
17039 | // new fields here we should reset the layout of the interface since | ||||||
17040 | // it will now change. | ||||||
17041 | if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { | ||||||
17042 | ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); | ||||||
17043 | switch (DC->getKind()) { | ||||||
17044 | default: break; | ||||||
17045 | case Decl::ObjCCategory: | ||||||
17046 | Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); | ||||||
17047 | break; | ||||||
17048 | case Decl::ObjCImplementation: | ||||||
17049 | Context. | ||||||
17050 | ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); | ||||||
17051 | break; | ||||||
17052 | } | ||||||
17053 | } | ||||||
17054 | |||||||
17055 | RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); | ||||||
17056 | CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); | ||||||
17057 | |||||||
17058 | // Start counting up the number of named members; make sure to include | ||||||
17059 | // members of anonymous structs and unions in the total. | ||||||
17060 | unsigned NumNamedMembers = 0; | ||||||
17061 | if (Record) { | ||||||
17062 | for (const auto *I : Record->decls()) { | ||||||
17063 | if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) | ||||||
17064 | if (IFD->getDeclName()) | ||||||
17065 | ++NumNamedMembers; | ||||||
17066 | } | ||||||
17067 | } | ||||||
17068 | |||||||
17069 | // Verify that all the fields are okay. | ||||||
17070 | SmallVector<FieldDecl*, 32> RecFields; | ||||||
17071 | |||||||
17072 | for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); | ||||||
17073 | i != end; ++i) { | ||||||
17074 | FieldDecl *FD = cast<FieldDecl>(*i); | ||||||
17075 | |||||||
17076 | // Get the type for the field. | ||||||
17077 | const Type *FDTy = FD->getType().getTypePtr(); | ||||||
17078 | |||||||
17079 | if (!FD->isAnonymousStructOrUnion()) { | ||||||
17080 | // Remember all fields written by the user. | ||||||
17081 | RecFields.push_back(FD); | ||||||
17082 | } | ||||||
17083 | |||||||
17084 | // If the field is already invalid for some reason, don't emit more | ||||||
17085 | // diagnostics about it. | ||||||
17086 | if (FD->isInvalidDecl()) { | ||||||
17087 | EnclosingDecl->setInvalidDecl(); | ||||||
17088 | continue; | ||||||
17089 | } | ||||||
17090 | |||||||
17091 | // C99 6.7.2.1p2: | ||||||
17092 | // A structure or union shall not contain a member with | ||||||
17093 | // incomplete or function type (hence, a structure shall not | ||||||
17094 | // contain an instance of itself, but may contain a pointer to | ||||||
17095 | // an instance of itself), except that the last member of a | ||||||
17096 | // structure with more than one named member may have incomplete | ||||||
17097 | // array type; such a structure (and any union containing, | ||||||
17098 | // possibly recursively, a member that is such a structure) | ||||||
17099 | // shall not be a member of a structure or an element of an | ||||||
17100 | // array. | ||||||
17101 | bool IsLastField = (i + 1 == Fields.end()); | ||||||
17102 | if (FDTy->isFunctionType()) { | ||||||
17103 | // Field declared as a function. | ||||||
17104 | Diag(FD->getLocation(), diag::err_field_declared_as_function) | ||||||
17105 | << FD->getDeclName(); | ||||||
17106 | FD->setInvalidDecl(); | ||||||
17107 | EnclosingDecl->setInvalidDecl(); | ||||||
17108 | continue; | ||||||
17109 | } else if (FDTy->isIncompleteArrayType() && | ||||||
17110 | (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { | ||||||
17111 | if (Record) { | ||||||
17112 | // Flexible array member. | ||||||
17113 | // Microsoft and g++ is more permissive regarding flexible array. | ||||||
17114 | // It will accept flexible array in union and also | ||||||
17115 | // as the sole element of a struct/class. | ||||||
17116 | unsigned DiagID = 0; | ||||||
17117 | if (!Record->isUnion() && !IsLastField) { | ||||||
17118 | Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) | ||||||
17119 | << FD->getDeclName() << FD->getType() << Record->getTagKind(); | ||||||
17120 | Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); | ||||||
17121 | FD->setInvalidDecl(); | ||||||
17122 | EnclosingDecl->setInvalidDecl(); | ||||||
17123 | continue; | ||||||
17124 | } else if (Record->isUnion()) | ||||||
17125 | DiagID = getLangOpts().MicrosoftExt | ||||||
17126 | ? diag::ext_flexible_array_union_ms | ||||||
17127 | : getLangOpts().CPlusPlus | ||||||
17128 | ? diag::ext_flexible_array_union_gnu | ||||||
17129 | : diag::err_flexible_array_union; | ||||||
17130 | else if (NumNamedMembers < 1) | ||||||
17131 | DiagID = getLangOpts().MicrosoftExt | ||||||
17132 | ? diag::ext_flexible_array_empty_aggregate_ms | ||||||
17133 | : getLangOpts().CPlusPlus | ||||||
17134 | ? diag::ext_flexible_array_empty_aggregate_gnu | ||||||
17135 | : diag::err_flexible_array_empty_aggregate; | ||||||
17136 | |||||||
17137 | if (DiagID) | ||||||
17138 | Diag(FD->getLocation(), DiagID) << FD->getDeclName() | ||||||
17139 | << Record->getTagKind(); | ||||||
17140 | // While the layout of types that contain virtual bases is not specified | ||||||
17141 | // by the C++ standard, both the Itanium and Microsoft C++ ABIs place | ||||||
17142 | // virtual bases after the derived members. This would make a flexible | ||||||
17143 | // array member declared at the end of an object not adjacent to the end | ||||||
17144 | // of the type. | ||||||
17145 | if (CXXRecord && CXXRecord->getNumVBases() != 0) | ||||||
17146 | Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) | ||||||
17147 | << FD->getDeclName() << Record->getTagKind(); | ||||||
17148 | if (!getLangOpts().C99) | ||||||
17149 | Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) | ||||||
17150 | << FD->getDeclName() << Record->getTagKind(); | ||||||
17151 | |||||||
17152 | // If the element type has a non-trivial destructor, we would not | ||||||
17153 | // implicitly destroy the elements, so disallow it for now. | ||||||
17154 | // | ||||||
17155 | // FIXME: GCC allows this. We should probably either implicitly delete | ||||||
17156 | // the destructor of the containing class, or just allow this. | ||||||
17157 | QualType BaseElem = Context.getBaseElementType(FD->getType()); | ||||||
17158 | if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { | ||||||
17159 | Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) | ||||||
17160 | << FD->getDeclName() << FD->getType(); | ||||||
17161 | FD->setInvalidDecl(); | ||||||
17162 | EnclosingDecl->setInvalidDecl(); | ||||||
17163 | continue; | ||||||
17164 | } | ||||||
17165 | // Okay, we have a legal flexible array member at the end of the struct. | ||||||
17166 | Record->setHasFlexibleArrayMember(true); | ||||||
17167 | } else { | ||||||
17168 | // In ObjCContainerDecl ivars with incomplete array type are accepted, | ||||||
17169 | // unless they are followed by another ivar. That check is done | ||||||
17170 | // elsewhere, after synthesized ivars are known. | ||||||
17171 | } | ||||||
17172 | } else if (!FDTy->isDependentType() && | ||||||
17173 | RequireCompleteSizedType( | ||||||
17174 | FD->getLocation(), FD->getType(), | ||||||
17175 | diag::err_field_incomplete_or_sizeless)) { | ||||||
17176 | // Incomplete type | ||||||
17177 | FD->setInvalidDecl(); | ||||||
17178 | EnclosingDecl->setInvalidDecl(); | ||||||
17179 | continue; | ||||||
17180 | } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { | ||||||
17181 | if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { | ||||||
17182 | // A type which contains a flexible array member is considered to be a | ||||||
17183 | // flexible array member. | ||||||
17184 | Record->setHasFlexibleArrayMember(true); | ||||||
17185 | if (!Record->isUnion()) { | ||||||
17186 | // If this is a struct/class and this is not the last element, reject | ||||||
17187 | // it. Note that GCC supports variable sized arrays in the middle of | ||||||
17188 | // structures. | ||||||
17189 | if (!IsLastField) | ||||||
17190 | Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) | ||||||
17191 | << FD->getDeclName() << FD->getType(); | ||||||
17192 | else { | ||||||
17193 | // We support flexible arrays at the end of structs in | ||||||
17194 | // other structs as an extension. | ||||||
17195 | Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) | ||||||
17196 | << FD->getDeclName(); | ||||||
17197 | } | ||||||
17198 | } | ||||||
17199 | } | ||||||
17200 | if (isa<ObjCContainerDecl>(EnclosingDecl) && | ||||||
17201 | RequireNonAbstractType(FD->getLocation(), FD->getType(), | ||||||
17202 | diag::err_abstract_type_in_decl, | ||||||
17203 | AbstractIvarType)) { | ||||||
17204 | // Ivars can not have abstract class types | ||||||
17205 | FD->setInvalidDecl(); | ||||||
17206 | } | ||||||
17207 | if (Record && FDTTy->getDecl()->hasObjectMember()) | ||||||
17208 | Record->setHasObjectMember(true); | ||||||
17209 | if (Record && FDTTy->getDecl()->hasVolatileMember()) | ||||||
17210 | Record->setHasVolatileMember(true); | ||||||
17211 | } else if (FDTy->isObjCObjectType()) { | ||||||
17212 | /// A field cannot be an Objective-c object | ||||||
17213 | Diag(FD->getLocation(), diag::err_statically_allocated_object) | ||||||
17214 | << FixItHint::CreateInsertion(FD->getLocation(), "*"); | ||||||
17215 | QualType T = Context.getObjCObjectPointerType(FD->getType()); | ||||||
17216 | FD->setType(T); | ||||||
17217 | } else if (Record && Record->isUnion() && | ||||||
17218 | FD->getType().hasNonTrivialObjCLifetime() && | ||||||
17219 | getSourceManager().isInSystemHeader(FD->getLocation()) && | ||||||
17220 | !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && | ||||||
17221 | (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || | ||||||
17222 | !Context.hasDirectOwnershipQualifier(FD->getType()))) { | ||||||
17223 | // For backward compatibility, fields of C unions declared in system | ||||||
17224 | // headers that have non-trivial ObjC ownership qualifications are marked | ||||||
17225 | // as unavailable unless the qualifier is explicit and __strong. This can | ||||||
17226 | // break ABI compatibility between programs compiled with ARC and MRR, but | ||||||
17227 | // is a better option than rejecting programs using those unions under | ||||||
17228 | // ARC. | ||||||
17229 | FD->addAttr(UnavailableAttr::CreateImplicit( | ||||||
17230 | Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, | ||||||
17231 | FD->getLocation())); | ||||||
17232 | } else if (getLangOpts().ObjC && | ||||||
17233 | getLangOpts().getGC() != LangOptions::NonGC && Record && | ||||||
17234 | !Record->hasObjectMember()) { | ||||||
17235 | if (FD->getType()->isObjCObjectPointerType() || | ||||||
17236 | FD->getType().isObjCGCStrong()) | ||||||
17237 | Record->setHasObjectMember(true); | ||||||
17238 | else if (Context.getAsArrayType(FD->getType())) { | ||||||
17239 | QualType BaseType = Context.getBaseElementType(FD->getType()); | ||||||
17240 | if (BaseType->isRecordType() && | ||||||
17241 | BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) | ||||||
17242 | Record->setHasObjectMember(true); | ||||||
17243 | else if (BaseType->isObjCObjectPointerType() || | ||||||
17244 | BaseType.isObjCGCStrong()) | ||||||
17245 | Record->setHasObjectMember(true); | ||||||
17246 | } | ||||||
17247 | } | ||||||
17248 | |||||||
17249 | if (Record && !getLangOpts().CPlusPlus && | ||||||
17250 | !shouldIgnoreForRecordTriviality(FD)) { | ||||||
17251 | QualType FT = FD->getType(); | ||||||
17252 | if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { | ||||||
17253 | Record->setNonTrivialToPrimitiveDefaultInitialize(true); | ||||||
17254 | if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || | ||||||
17255 | Record->isUnion()) | ||||||
17256 | Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); | ||||||
17257 | } | ||||||
17258 | QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); | ||||||
17259 | if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { | ||||||
17260 | Record->setNonTrivialToPrimitiveCopy(true); | ||||||
17261 | if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) | ||||||
17262 | Record->setHasNonTrivialToPrimitiveCopyCUnion(true); | ||||||
17263 | } | ||||||
17264 | if (FT.isDestructedType()) { | ||||||
17265 | Record->setNonTrivialToPrimitiveDestroy(true); | ||||||
17266 | Record->setParamDestroyedInCallee(true); | ||||||
17267 | if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) | ||||||
17268 | Record->setHasNonTrivialToPrimitiveDestructCUnion(true); | ||||||
17269 | } | ||||||
17270 | |||||||
17271 | if (const auto *RT = FT->getAs<RecordType>()) { | ||||||
17272 | if (RT->getDecl()->getArgPassingRestrictions() == | ||||||
17273 | RecordDecl::APK_CanNeverPassInRegs) | ||||||
17274 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | ||||||
17275 | } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) | ||||||
17276 | Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); | ||||||
17277 | } | ||||||
17278 | |||||||
17279 | if (Record && FD->getType().isVolatileQualified()) | ||||||
17280 | Record->setHasVolatileMember(true); | ||||||
17281 | // Keep track of the number of named members. | ||||||
17282 | if (FD->getIdentifier()) | ||||||
17283 | ++NumNamedMembers; | ||||||
17284 | } | ||||||
17285 | |||||||
17286 | // Okay, we successfully defined 'Record'. | ||||||
17287 | if (Record) { | ||||||
17288 | bool Completed = false; | ||||||
17289 | if (CXXRecord) { | ||||||
17290 | if (!CXXRecord->isInvalidDecl()) { | ||||||
17291 | // Set access bits correctly on the directly-declared conversions. | ||||||
17292 | for (CXXRecordDecl::conversion_iterator | ||||||
17293 | I = CXXRecord->conversion_begin(), | ||||||
17294 | E = CXXRecord->conversion_end(); I != E; ++I) | ||||||
17295 | I.setAccess((*I)->getAccess()); | ||||||
17296 | } | ||||||
17297 | |||||||
17298 | // Add any implicitly-declared members to this class. | ||||||
17299 | AddImplicitlyDeclaredMembersToClass(CXXRecord); | ||||||
17300 | |||||||
17301 | if (!CXXRecord->isDependentType()) { | ||||||
17302 | if (!CXXRecord->isInvalidDecl()) { | ||||||
17303 | // If we have virtual base classes, we may end up finding multiple | ||||||
17304 | // final overriders for a given virtual function. Check for this | ||||||
17305 | // problem now. | ||||||
17306 | if (CXXRecord->getNumVBases()) { | ||||||
17307 | CXXFinalOverriderMap FinalOverriders; | ||||||
17308 | CXXRecord->getFinalOverriders(FinalOverriders); | ||||||
17309 | |||||||
17310 | for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), | ||||||
17311 | MEnd = FinalOverriders.end(); | ||||||
17312 | M != MEnd; ++M) { | ||||||
17313 | for (OverridingMethods::iterator SO = M->second.begin(), | ||||||
17314 | SOEnd = M->second.end(); | ||||||
17315 | SO != SOEnd; ++SO) { | ||||||
17316 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17317, __PRETTY_FUNCTION__)) | ||||||
17317 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17317, __PRETTY_FUNCTION__)); | ||||||
17318 | if (SO->second.size() == 1) | ||||||
17319 | continue; | ||||||
17320 | |||||||
17321 | // C++ [class.virtual]p2: | ||||||
17322 | // In a derived class, if a virtual member function of a base | ||||||
17323 | // class subobject has more than one final overrider the | ||||||
17324 | // program is ill-formed. | ||||||
17325 | Diag(Record->getLocation(), diag::err_multiple_final_overriders) | ||||||
17326 | << (const NamedDecl *)M->first << Record; | ||||||
17327 | Diag(M->first->getLocation(), | ||||||
17328 | diag::note_overridden_virtual_function); | ||||||
17329 | for (OverridingMethods::overriding_iterator | ||||||
17330 | OM = SO->second.begin(), | ||||||
17331 | OMEnd = SO->second.end(); | ||||||
17332 | OM != OMEnd; ++OM) | ||||||
17333 | Diag(OM->Method->getLocation(), diag::note_final_overrider) | ||||||
17334 | << (const NamedDecl *)M->first << OM->Method->getParent(); | ||||||
17335 | |||||||
17336 | Record->setInvalidDecl(); | ||||||
17337 | } | ||||||
17338 | } | ||||||
17339 | CXXRecord->completeDefinition(&FinalOverriders); | ||||||
17340 | Completed = true; | ||||||
17341 | } | ||||||
17342 | } | ||||||
17343 | } | ||||||
17344 | } | ||||||
17345 | |||||||
17346 | if (!Completed) | ||||||
17347 | Record->completeDefinition(); | ||||||
17348 | |||||||
17349 | // Handle attributes before checking the layout. | ||||||
17350 | ProcessDeclAttributeList(S, Record, Attrs); | ||||||
17351 | |||||||
17352 | // We may have deferred checking for a deleted destructor. Check now. | ||||||
17353 | if (CXXRecord) { | ||||||
17354 | auto *Dtor = CXXRecord->getDestructor(); | ||||||
17355 | if (Dtor && Dtor->isImplicit() && | ||||||
17356 | ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { | ||||||
17357 | CXXRecord->setImplicitDestructorIsDeleted(); | ||||||
17358 | SetDeclDeleted(Dtor, CXXRecord->getLocation()); | ||||||
17359 | } | ||||||
17360 | } | ||||||
17361 | |||||||
17362 | if (Record->hasAttrs()) { | ||||||
17363 | CheckAlignasUnderalignment(Record); | ||||||
17364 | |||||||
17365 | if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) | ||||||
17366 | checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), | ||||||
17367 | IA->getRange(), IA->getBestCase(), | ||||||
17368 | IA->getInheritanceModel()); | ||||||
17369 | } | ||||||
17370 | |||||||
17371 | // Check if the structure/union declaration is a type that can have zero | ||||||
17372 | // size in C. For C this is a language extension, for C++ it may cause | ||||||
17373 | // compatibility problems. | ||||||
17374 | bool CheckForZeroSize; | ||||||
17375 | if (!getLangOpts().CPlusPlus) { | ||||||
17376 | CheckForZeroSize = true; | ||||||
17377 | } else { | ||||||
17378 | // For C++ filter out types that cannot be referenced in C code. | ||||||
17379 | CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); | ||||||
17380 | CheckForZeroSize = | ||||||
17381 | CXXRecord->getLexicalDeclContext()->isExternCContext() && | ||||||
17382 | !CXXRecord->isDependentType() && !inTemplateInstantiation() && | ||||||
17383 | CXXRecord->isCLike(); | ||||||
17384 | } | ||||||
17385 | if (CheckForZeroSize) { | ||||||
17386 | bool ZeroSize = true; | ||||||
17387 | bool IsEmpty = true; | ||||||
17388 | unsigned NonBitFields = 0; | ||||||
17389 | for (RecordDecl::field_iterator I = Record->field_begin(), | ||||||
17390 | E = Record->field_end(); | ||||||
17391 | (NonBitFields == 0 || ZeroSize) && I != E; ++I) { | ||||||
17392 | IsEmpty = false; | ||||||
17393 | if (I->isUnnamedBitfield()) { | ||||||
17394 | if (!I->isZeroLengthBitField(Context)) | ||||||
17395 | ZeroSize = false; | ||||||
17396 | } else { | ||||||
17397 | ++NonBitFields; | ||||||
17398 | QualType FieldType = I->getType(); | ||||||
17399 | if (FieldType->isIncompleteType() || | ||||||
17400 | !Context.getTypeSizeInChars(FieldType).isZero()) | ||||||
17401 | ZeroSize = false; | ||||||
17402 | } | ||||||
17403 | } | ||||||
17404 | |||||||
17405 | // Empty structs are an extension in C (C99 6.7.2.1p7). They are | ||||||
17406 | // allowed in C++, but warn if its declaration is inside | ||||||
17407 | // extern "C" block. | ||||||
17408 | if (ZeroSize) { | ||||||
17409 | Diag(RecLoc, getLangOpts().CPlusPlus ? | ||||||
17410 | diag::warn_zero_size_struct_union_in_extern_c : | ||||||
17411 | diag::warn_zero_size_struct_union_compat) | ||||||
17412 | << IsEmpty << Record->isUnion() << (NonBitFields > 1); | ||||||
17413 | } | ||||||
17414 | |||||||
17415 | // Structs without named members are extension in C (C99 6.7.2.1p7), | ||||||
17416 | // but are accepted by GCC. | ||||||
17417 | if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { | ||||||
17418 | Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : | ||||||
17419 | diag::ext_no_named_members_in_struct_union) | ||||||
17420 | << Record->isUnion(); | ||||||
17421 | } | ||||||
17422 | } | ||||||
17423 | } else { | ||||||
17424 | ObjCIvarDecl **ClsFields = | ||||||
17425 | reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); | ||||||
17426 | if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { | ||||||
17427 | ID->setEndOfDefinitionLoc(RBrac); | ||||||
17428 | // Add ivar's to class's DeclContext. | ||||||
17429 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | ||||||
17430 | ClsFields[i]->setLexicalDeclContext(ID); | ||||||
17431 | ID->addDecl(ClsFields[i]); | ||||||
17432 | } | ||||||
17433 | // Must enforce the rule that ivars in the base classes may not be | ||||||
17434 | // duplicates. | ||||||
17435 | if (ID->getSuperClass()) | ||||||
17436 | DiagnoseDuplicateIvars(ID, ID->getSuperClass()); | ||||||
17437 | } else if (ObjCImplementationDecl *IMPDecl = | ||||||
17438 | dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { | ||||||
17439 | assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl" ) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17439, __PRETTY_FUNCTION__)); | ||||||
17440 | for (unsigned I = 0, N = RecFields.size(); I != N; ++I) | ||||||
17441 | // Ivar declared in @implementation never belongs to the implementation. | ||||||
17442 | // Only it is in implementation's lexical context. | ||||||
17443 | ClsFields[I]->setLexicalDeclContext(IMPDecl); | ||||||
17444 | CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); | ||||||
17445 | IMPDecl->setIvarLBraceLoc(LBrac); | ||||||
17446 | IMPDecl->setIvarRBraceLoc(RBrac); | ||||||
17447 | } else if (ObjCCategoryDecl *CDecl = | ||||||
17448 | dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { | ||||||
17449 | // case of ivars in class extension; all other cases have been | ||||||
17450 | // reported as errors elsewhere. | ||||||
17451 | // FIXME. Class extension does not have a LocEnd field. | ||||||
17452 | // CDecl->setLocEnd(RBrac); | ||||||
17453 | // Add ivar's to class extension's DeclContext. | ||||||
17454 | // Diagnose redeclaration of private ivars. | ||||||
17455 | ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); | ||||||
17456 | for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { | ||||||
17457 | if (IDecl) { | ||||||
17458 | if (const ObjCIvarDecl *ClsIvar = | ||||||
17459 | IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { | ||||||
17460 | Diag(ClsFields[i]->getLocation(), | ||||||
17461 | diag::err_duplicate_ivar_declaration); | ||||||
17462 | Diag(ClsIvar->getLocation(), diag::note_previous_definition); | ||||||
17463 | continue; | ||||||
17464 | } | ||||||
17465 | for (const auto *Ext : IDecl->known_extensions()) { | ||||||
17466 | if (const ObjCIvarDecl *ClsExtIvar | ||||||
17467 | = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { | ||||||
17468 | Diag(ClsFields[i]->getLocation(), | ||||||
17469 | diag::err_duplicate_ivar_declaration); | ||||||
17470 | Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); | ||||||
17471 | continue; | ||||||
17472 | } | ||||||
17473 | } | ||||||
17474 | } | ||||||
17475 | ClsFields[i]->setLexicalDeclContext(CDecl); | ||||||
17476 | CDecl->addDecl(ClsFields[i]); | ||||||
17477 | } | ||||||
17478 | CDecl->setIvarLBraceLoc(LBrac); | ||||||
17479 | CDecl->setIvarRBraceLoc(RBrac); | ||||||
17480 | } | ||||||
17481 | } | ||||||
17482 | } | ||||||
17483 | |||||||
17484 | /// Determine whether the given integral value is representable within | ||||||
17485 | /// the given type T. | ||||||
17486 | static bool isRepresentableIntegerValue(ASTContext &Context, | ||||||
17487 | llvm::APSInt &Value, | ||||||
17488 | QualType T) { | ||||||
17489 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17490, __PRETTY_FUNCTION__)) | ||||||
17490 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17490, __PRETTY_FUNCTION__)); | ||||||
17491 | unsigned BitWidth = Context.getIntWidth(T); | ||||||
17492 | |||||||
17493 | if (Value.isUnsigned() || Value.isNonNegative()) { | ||||||
17494 | if (T->isSignedIntegerOrEnumerationType()) | ||||||
17495 | --BitWidth; | ||||||
17496 | return Value.getActiveBits() <= BitWidth; | ||||||
17497 | } | ||||||
17498 | return Value.getMinSignedBits() <= BitWidth; | ||||||
17499 | } | ||||||
17500 | |||||||
17501 | // Given an integral type, return the next larger integral type | ||||||
17502 | // (or a NULL type of no such type exists). | ||||||
17503 | static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { | ||||||
17504 | // FIXME: Int128/UInt128 support, which also needs to be introduced into | ||||||
17505 | // enum checking below. | ||||||
17506 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17507, __PRETTY_FUNCTION__)) | ||||||
17507 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17507, __PRETTY_FUNCTION__)); | ||||||
17508 | const unsigned NumTypes = 4; | ||||||
17509 | QualType SignedIntegralTypes[NumTypes] = { | ||||||
17510 | Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy | ||||||
17511 | }; | ||||||
17512 | QualType UnsignedIntegralTypes[NumTypes] = { | ||||||
17513 | Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, | ||||||
17514 | Context.UnsignedLongLongTy | ||||||
17515 | }; | ||||||
17516 | |||||||
17517 | unsigned BitWidth = Context.getTypeSize(T); | ||||||
17518 | QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes | ||||||
17519 | : UnsignedIntegralTypes; | ||||||
17520 | for (unsigned I = 0; I != NumTypes; ++I) | ||||||
17521 | if (Context.getTypeSize(Types[I]) > BitWidth) | ||||||
17522 | return Types[I]; | ||||||
17523 | |||||||
17524 | return QualType(); | ||||||
17525 | } | ||||||
17526 | |||||||
17527 | EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, | ||||||
17528 | EnumConstantDecl *LastEnumConst, | ||||||
17529 | SourceLocation IdLoc, | ||||||
17530 | IdentifierInfo *Id, | ||||||
17531 | Expr *Val) { | ||||||
17532 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | ||||||
17533 | llvm::APSInt EnumVal(IntWidth); | ||||||
17534 | QualType EltTy; | ||||||
17535 | |||||||
17536 | if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) | ||||||
17537 | Val = nullptr; | ||||||
17538 | |||||||
17539 | if (Val) | ||||||
17540 | Val = DefaultLvalueConversion(Val).get(); | ||||||
17541 | |||||||
17542 | if (Val) { | ||||||
17543 | if (Enum->isDependentType() || Val->isTypeDependent()) | ||||||
17544 | EltTy = Context.DependentTy; | ||||||
17545 | else { | ||||||
17546 | if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { | ||||||
17547 | // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the | ||||||
17548 | // constant-expression in the enumerator-definition shall be a converted | ||||||
17549 | // constant expression of the underlying type. | ||||||
17550 | EltTy = Enum->getIntegerType(); | ||||||
17551 | ExprResult Converted = | ||||||
17552 | CheckConvertedConstantExpression(Val, EltTy, EnumVal, | ||||||
17553 | CCEK_Enumerator); | ||||||
17554 | if (Converted.isInvalid()) | ||||||
17555 | Val = nullptr; | ||||||
17556 | else | ||||||
17557 | Val = Converted.get(); | ||||||
17558 | } else if (!Val->isValueDependent() && | ||||||
17559 | !(Val = VerifyIntegerConstantExpression(Val, | ||||||
17560 | &EnumVal).get())) { | ||||||
17561 | // C99 6.7.2.2p2: Make sure we have an integer constant expression. | ||||||
17562 | } else { | ||||||
17563 | if (Enum->isComplete()) { | ||||||
17564 | EltTy = Enum->getIntegerType(); | ||||||
17565 | |||||||
17566 | // In Obj-C and Microsoft mode, require the enumeration value to be | ||||||
17567 | // representable in the underlying type of the enumeration. In C++11, | ||||||
17568 | // we perform a non-narrowing conversion as part of converted constant | ||||||
17569 | // expression checking. | ||||||
17570 | if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | ||||||
17571 | if (Context.getTargetInfo() | ||||||
17572 | .getTriple() | ||||||
17573 | .isWindowsMSVCEnvironment()) { | ||||||
17574 | Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; | ||||||
17575 | } else { | ||||||
17576 | Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; | ||||||
17577 | } | ||||||
17578 | } | ||||||
17579 | |||||||
17580 | // Cast to the underlying type. | ||||||
17581 | Val = ImpCastExprToType(Val, EltTy, | ||||||
17582 | EltTy->isBooleanType() ? CK_IntegralToBoolean | ||||||
17583 | : CK_IntegralCast) | ||||||
17584 | .get(); | ||||||
17585 | } else if (getLangOpts().CPlusPlus) { | ||||||
17586 | // C++11 [dcl.enum]p5: | ||||||
17587 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17588 | // is the type of its initializing value: | ||||||
17589 | // - If an initializer is specified for an enumerator, the | ||||||
17590 | // initializing value has the same type as the expression. | ||||||
17591 | EltTy = Val->getType(); | ||||||
17592 | } else { | ||||||
17593 | // C99 6.7.2.2p2: | ||||||
17594 | // The expression that defines the value of an enumeration constant | ||||||
17595 | // shall be an integer constant expression that has a value | ||||||
17596 | // representable as an int. | ||||||
17597 | |||||||
17598 | // Complain if the value is not representable in an int. | ||||||
17599 | if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) | ||||||
17600 | Diag(IdLoc, diag::ext_enum_value_not_int) | ||||||
17601 | << EnumVal.toString(10) << Val->getSourceRange() | ||||||
17602 | << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); | ||||||
17603 | else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { | ||||||
17604 | // Force the type of the expression to 'int'. | ||||||
17605 | Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); | ||||||
17606 | } | ||||||
17607 | EltTy = Val->getType(); | ||||||
17608 | } | ||||||
17609 | } | ||||||
17610 | } | ||||||
17611 | } | ||||||
17612 | |||||||
17613 | if (!Val) { | ||||||
17614 | if (Enum->isDependentType()) | ||||||
17615 | EltTy = Context.DependentTy; | ||||||
17616 | else if (!LastEnumConst) { | ||||||
17617 | // C++0x [dcl.enum]p5: | ||||||
17618 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17619 | // is the type of its initializing value: | ||||||
17620 | // - If no initializer is specified for the first enumerator, the | ||||||
17621 | // initializing value has an unspecified integral type. | ||||||
17622 | // | ||||||
17623 | // GCC uses 'int' for its unspecified integral type, as does | ||||||
17624 | // C99 6.7.2.2p3. | ||||||
17625 | if (Enum->isFixed()) { | ||||||
17626 | EltTy = Enum->getIntegerType(); | ||||||
17627 | } | ||||||
17628 | else { | ||||||
17629 | EltTy = Context.IntTy; | ||||||
17630 | } | ||||||
17631 | } else { | ||||||
17632 | // Assign the last value + 1. | ||||||
17633 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17634 | ++EnumVal; | ||||||
17635 | EltTy = LastEnumConst->getType(); | ||||||
17636 | |||||||
17637 | // Check for overflow on increment. | ||||||
17638 | if (EnumVal < LastEnumConst->getInitVal()) { | ||||||
17639 | // C++0x [dcl.enum]p5: | ||||||
17640 | // If the underlying type is not fixed, the type of each enumerator | ||||||
17641 | // is the type of its initializing value: | ||||||
17642 | // | ||||||
17643 | // - Otherwise the type of the initializing value is the same as | ||||||
17644 | // the type of the initializing value of the preceding enumerator | ||||||
17645 | // unless the incremented value is not representable in that type, | ||||||
17646 | // in which case the type is an unspecified integral type | ||||||
17647 | // sufficient to contain the incremented value. If no such type | ||||||
17648 | // exists, the program is ill-formed. | ||||||
17649 | QualType T = getNextLargerIntegralType(Context, EltTy); | ||||||
17650 | if (T.isNull() || Enum->isFixed()) { | ||||||
17651 | // There is no integral type larger enough to represent this | ||||||
17652 | // value. Complain, then allow the value to wrap around. | ||||||
17653 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17654 | EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); | ||||||
17655 | ++EnumVal; | ||||||
17656 | if (Enum->isFixed()) | ||||||
17657 | // When the underlying type is fixed, this is ill-formed. | ||||||
17658 | Diag(IdLoc, diag::err_enumerator_wrapped) | ||||||
17659 | << EnumVal.toString(10) | ||||||
17660 | << EltTy; | ||||||
17661 | else | ||||||
17662 | Diag(IdLoc, diag::ext_enumerator_increment_too_large) | ||||||
17663 | << EnumVal.toString(10); | ||||||
17664 | } else { | ||||||
17665 | EltTy = T; | ||||||
17666 | } | ||||||
17667 | |||||||
17668 | // Retrieve the last enumerator's value, extent that type to the | ||||||
17669 | // type that is supposed to be large enough to represent the incremented | ||||||
17670 | // value, then increment. | ||||||
17671 | EnumVal = LastEnumConst->getInitVal(); | ||||||
17672 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | ||||||
17673 | EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); | ||||||
17674 | ++EnumVal; | ||||||
17675 | |||||||
17676 | // If we're not in C++, diagnose the overflow of enumerator values, | ||||||
17677 | // which in C99 means that the enumerator value is not representable in | ||||||
17678 | // an int (C99 6.7.2.2p2). However, we support GCC's extension that | ||||||
17679 | // permits enumerator values that are representable in some larger | ||||||
17680 | // integral type. | ||||||
17681 | if (!getLangOpts().CPlusPlus && !T.isNull()) | ||||||
17682 | Diag(IdLoc, diag::warn_enum_value_overflow); | ||||||
17683 | } else if (!getLangOpts().CPlusPlus && | ||||||
17684 | !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { | ||||||
17685 | // Enforce C99 6.7.2.2p2 even when we compute the next value. | ||||||
17686 | Diag(IdLoc, diag::ext_enum_value_not_int) | ||||||
17687 | << EnumVal.toString(10) << 1; | ||||||
17688 | } | ||||||
17689 | } | ||||||
17690 | } | ||||||
17691 | |||||||
17692 | if (!EltTy->isDependentType()) { | ||||||
17693 | // Make the enumerator value match the signedness and size of the | ||||||
17694 | // enumerator's type. | ||||||
17695 | EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); | ||||||
17696 | EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); | ||||||
17697 | } | ||||||
17698 | |||||||
17699 | return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, | ||||||
17700 | Val, EnumVal); | ||||||
17701 | } | ||||||
17702 | |||||||
17703 | Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, | ||||||
17704 | SourceLocation IILoc) { | ||||||
17705 | if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || | ||||||
17706 | !getLangOpts().CPlusPlus) | ||||||
17707 | return SkipBodyInfo(); | ||||||
17708 | |||||||
17709 | // We have an anonymous enum definition. Look up the first enumerator to | ||||||
17710 | // determine if we should merge the definition with an existing one and | ||||||
17711 | // skip the body. | ||||||
17712 | NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, | ||||||
17713 | forRedeclarationInCurContext()); | ||||||
17714 | auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); | ||||||
17715 | if (!PrevECD) | ||||||
17716 | return SkipBodyInfo(); | ||||||
17717 | |||||||
17718 | EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); | ||||||
17719 | NamedDecl *Hidden; | ||||||
17720 | if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { | ||||||
17721 | SkipBodyInfo Skip; | ||||||
17722 | Skip.Previous = Hidden; | ||||||
17723 | return Skip; | ||||||
17724 | } | ||||||
17725 | |||||||
17726 | return SkipBodyInfo(); | ||||||
17727 | } | ||||||
17728 | |||||||
17729 | Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, | ||||||
17730 | SourceLocation IdLoc, IdentifierInfo *Id, | ||||||
17731 | const ParsedAttributesView &Attrs, | ||||||
17732 | SourceLocation EqualLoc, Expr *Val) { | ||||||
17733 | EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); | ||||||
17734 | EnumConstantDecl *LastEnumConst = | ||||||
17735 | cast_or_null<EnumConstantDecl>(lastEnumConst); | ||||||
17736 | |||||||
17737 | // The scope passed in may not be a decl scope. Zip up the scope tree until | ||||||
17738 | // we find one that is. | ||||||
17739 | S = getNonFieldDeclScope(S); | ||||||
17740 | |||||||
17741 | // Verify that there isn't already something declared with this name in this | ||||||
17742 | // scope. | ||||||
17743 | LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); | ||||||
17744 | LookupName(R, S); | ||||||
17745 | NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); | ||||||
17746 | |||||||
17747 | if (PrevDecl && PrevDecl->isTemplateParameter()) { | ||||||
17748 | // Maybe we will complain about the shadowed template parameter. | ||||||
17749 | DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); | ||||||
17750 | // Just pretend that we didn't see the previous declaration. | ||||||
17751 | PrevDecl = nullptr; | ||||||
17752 | } | ||||||
17753 | |||||||
17754 | // C++ [class.mem]p15: | ||||||
17755 | // If T is the name of a class, then each of the following shall have a name | ||||||
17756 | // different from T: | ||||||
17757 | // - every enumerator of every member of class T that is an unscoped | ||||||
17758 | // enumerated type | ||||||
17759 | if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) | ||||||
17760 | DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), | ||||||
17761 | DeclarationNameInfo(Id, IdLoc)); | ||||||
17762 | |||||||
17763 | EnumConstantDecl *New = | ||||||
17764 | CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); | ||||||
17765 | if (!New) | ||||||
17766 | return nullptr; | ||||||
17767 | |||||||
17768 | if (PrevDecl) { | ||||||
17769 | if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { | ||||||
17770 | // Check for other kinds of shadowing not already handled. | ||||||
17771 | CheckShadow(New, PrevDecl, R); | ||||||
17772 | } | ||||||
17773 | |||||||
17774 | // When in C++, we may get a TagDecl with the same name; in this case the | ||||||
17775 | // enum constant will 'hide' the tag. | ||||||
17776 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17777, __PRETTY_FUNCTION__)) | ||||||
17777 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17777, __PRETTY_FUNCTION__)); | ||||||
17778 | if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { | ||||||
17779 | if (isa<EnumConstantDecl>(PrevDecl)) | ||||||
17780 | Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; | ||||||
17781 | else | ||||||
17782 | Diag(IdLoc, diag::err_redefinition) << Id; | ||||||
17783 | notePreviousDefinition(PrevDecl, IdLoc); | ||||||
17784 | return nullptr; | ||||||
17785 | } | ||||||
17786 | } | ||||||
17787 | |||||||
17788 | // Process attributes. | ||||||
17789 | ProcessDeclAttributeList(S, New, Attrs); | ||||||
17790 | AddPragmaAttributes(S, New); | ||||||
17791 | |||||||
17792 | // Register this decl in the current scope stack. | ||||||
17793 | New->setAccess(TheEnumDecl->getAccess()); | ||||||
17794 | PushOnScopeChains(New, S); | ||||||
17795 | |||||||
17796 | ActOnDocumentableDecl(New); | ||||||
17797 | |||||||
17798 | return New; | ||||||
17799 | } | ||||||
17800 | |||||||
17801 | // Returns true when the enum initial expression does not trigger the | ||||||
17802 | // duplicate enum warning. A few common cases are exempted as follows: | ||||||
17803 | // Element2 = Element1 | ||||||
17804 | // Element2 = Element1 + 1 | ||||||
17805 | // Element2 = Element1 - 1 | ||||||
17806 | // Where Element2 and Element1 are from the same enum. | ||||||
17807 | static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { | ||||||
17808 | Expr *InitExpr = ECD->getInitExpr(); | ||||||
17809 | if (!InitExpr) | ||||||
17810 | return true; | ||||||
17811 | InitExpr = InitExpr->IgnoreImpCasts(); | ||||||
17812 | |||||||
17813 | if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { | ||||||
17814 | if (!BO->isAdditiveOp()) | ||||||
17815 | return true; | ||||||
17816 | IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); | ||||||
17817 | if (!IL) | ||||||
17818 | return true; | ||||||
17819 | if (IL->getValue() != 1) | ||||||
17820 | return true; | ||||||
17821 | |||||||
17822 | InitExpr = BO->getLHS(); | ||||||
17823 | } | ||||||
17824 | |||||||
17825 | // This checks if the elements are from the same enum. | ||||||
17826 | DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); | ||||||
17827 | if (!DRE) | ||||||
17828 | return true; | ||||||
17829 | |||||||
17830 | EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); | ||||||
17831 | if (!EnumConstant) | ||||||
17832 | return true; | ||||||
17833 | |||||||
17834 | if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != | ||||||
17835 | Enum) | ||||||
17836 | return true; | ||||||
17837 | |||||||
17838 | return false; | ||||||
17839 | } | ||||||
17840 | |||||||
17841 | // Emits a warning when an element is implicitly set a value that | ||||||
17842 | // a previous element has already been set to. | ||||||
17843 | static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, | ||||||
17844 | EnumDecl *Enum, QualType EnumType) { | ||||||
17845 | // Avoid anonymous enums | ||||||
17846 | if (!Enum->getIdentifier()) | ||||||
17847 | return; | ||||||
17848 | |||||||
17849 | // Only check for small enums. | ||||||
17850 | if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) | ||||||
17851 | return; | ||||||
17852 | |||||||
17853 | if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) | ||||||
17854 | return; | ||||||
17855 | |||||||
17856 | typedef SmallVector<EnumConstantDecl *, 3> ECDVector; | ||||||
17857 | typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; | ||||||
17858 | |||||||
17859 | typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; | ||||||
17860 | |||||||
17861 | // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. | ||||||
17862 | typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; | ||||||
17863 | |||||||
17864 | // Use int64_t as a key to avoid needing special handling for map keys. | ||||||
17865 | auto EnumConstantToKey = [](const EnumConstantDecl *D) { | ||||||
17866 | llvm::APSInt Val = D->getInitVal(); | ||||||
17867 | return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); | ||||||
17868 | }; | ||||||
17869 | |||||||
17870 | DuplicatesVector DupVector; | ||||||
17871 | ValueToVectorMap EnumMap; | ||||||
17872 | |||||||
17873 | // Populate the EnumMap with all values represented by enum constants without | ||||||
17874 | // an initializer. | ||||||
17875 | for (auto *Element : Elements) { | ||||||
17876 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); | ||||||
17877 | |||||||
17878 | // Null EnumConstantDecl means a previous diagnostic has been emitted for | ||||||
17879 | // this constant. Skip this enum since it may be ill-formed. | ||||||
17880 | if (!ECD) { | ||||||
17881 | return; | ||||||
17882 | } | ||||||
17883 | |||||||
17884 | // Constants with initalizers are handled in the next loop. | ||||||
17885 | if (ECD->getInitExpr()) | ||||||
17886 | continue; | ||||||
17887 | |||||||
17888 | // Duplicate values are handled in the next loop. | ||||||
17889 | EnumMap.insert({EnumConstantToKey(ECD), ECD}); | ||||||
17890 | } | ||||||
17891 | |||||||
17892 | if (EnumMap.size() == 0) | ||||||
17893 | return; | ||||||
17894 | |||||||
17895 | // Create vectors for any values that has duplicates. | ||||||
17896 | for (auto *Element : Elements) { | ||||||
17897 | // The last loop returned if any constant was null. | ||||||
17898 | EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); | ||||||
17899 | if (!ValidDuplicateEnum(ECD, Enum)) | ||||||
17900 | continue; | ||||||
17901 | |||||||
17902 | auto Iter = EnumMap.find(EnumConstantToKey(ECD)); | ||||||
17903 | if (Iter == EnumMap.end()) | ||||||
17904 | continue; | ||||||
17905 | |||||||
17906 | DeclOrVector& Entry = Iter->second; | ||||||
17907 | if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { | ||||||
17908 | // Ensure constants are different. | ||||||
17909 | if (D == ECD) | ||||||
17910 | continue; | ||||||
17911 | |||||||
17912 | // Create new vector and push values onto it. | ||||||
17913 | auto Vec = std::make_unique<ECDVector>(); | ||||||
17914 | Vec->push_back(D); | ||||||
17915 | Vec->push_back(ECD); | ||||||
17916 | |||||||
17917 | // Update entry to point to the duplicates vector. | ||||||
17918 | Entry = Vec.get(); | ||||||
17919 | |||||||
17920 | // Store the vector somewhere we can consult later for quick emission of | ||||||
17921 | // diagnostics. | ||||||
17922 | DupVector.emplace_back(std::move(Vec)); | ||||||
17923 | continue; | ||||||
17924 | } | ||||||
17925 | |||||||
17926 | ECDVector *Vec = Entry.get<ECDVector*>(); | ||||||
17927 | // Make sure constants are not added more than once. | ||||||
17928 | if (*Vec->begin() == ECD) | ||||||
17929 | continue; | ||||||
17930 | |||||||
17931 | Vec->push_back(ECD); | ||||||
17932 | } | ||||||
17933 | |||||||
17934 | // Emit diagnostics. | ||||||
17935 | for (const auto &Vec : DupVector) { | ||||||
17936 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17936, __PRETTY_FUNCTION__)); | ||||||
17937 | |||||||
17938 | // Emit warning for one enum constant. | ||||||
17939 | auto *FirstECD = Vec->front(); | ||||||
17940 | S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) | ||||||
17941 | << FirstECD << FirstECD->getInitVal().toString(10) | ||||||
17942 | << FirstECD->getSourceRange(); | ||||||
17943 | |||||||
17944 | // Emit one note for each of the remaining enum constants with | ||||||
17945 | // the same value. | ||||||
17946 | for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) | ||||||
17947 | S.Diag(ECD->getLocation(), diag::note_duplicate_element) | ||||||
17948 | << ECD << ECD->getInitVal().toString(10) | ||||||
17949 | << ECD->getSourceRange(); | ||||||
17950 | } | ||||||
17951 | } | ||||||
17952 | |||||||
17953 | bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, | ||||||
17954 | bool AllowMask) const { | ||||||
17955 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17955, __PRETTY_FUNCTION__)); | ||||||
17956 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 17956, __PRETTY_FUNCTION__)); | ||||||
17957 | |||||||
17958 | auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); | ||||||
17959 | llvm::APInt &FlagBits = R.first->second; | ||||||
17960 | |||||||
17961 | if (R.second) { | ||||||
17962 | for (auto *E : ED->enumerators()) { | ||||||
17963 | const auto &EVal = E->getInitVal(); | ||||||
17964 | // Only single-bit enumerators introduce new flag values. | ||||||
17965 | if (EVal.isPowerOf2()) | ||||||
17966 | FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; | ||||||
17967 | } | ||||||
17968 | } | ||||||
17969 | |||||||
17970 | // A value is in a flag enum if either its bits are a subset of the enum's | ||||||
17971 | // flag bits (the first condition) or we are allowing masks and the same is | ||||||
17972 | // true of its complement (the second condition). When masks are allowed, we | ||||||
17973 | // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. | ||||||
17974 | // | ||||||
17975 | // While it's true that any value could be used as a mask, the assumption is | ||||||
17976 | // that a mask will have all of the insignificant bits set. Anything else is | ||||||
17977 | // likely a logic error. | ||||||
17978 | llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); | ||||||
17979 | return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); | ||||||
17980 | } | ||||||
17981 | |||||||
17982 | void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, | ||||||
17983 | Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, | ||||||
17984 | const ParsedAttributesView &Attrs) { | ||||||
17985 | EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); | ||||||
17986 | QualType EnumType = Context.getTypeDeclType(Enum); | ||||||
17987 | |||||||
17988 | ProcessDeclAttributeList(S, Enum, Attrs); | ||||||
17989 | |||||||
17990 | if (Enum->isDependentType()) { | ||||||
17991 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | ||||||
17992 | EnumConstantDecl *ECD = | ||||||
17993 | cast_or_null<EnumConstantDecl>(Elements[i]); | ||||||
17994 | if (!ECD) continue; | ||||||
17995 | |||||||
17996 | ECD->setType(EnumType); | ||||||
17997 | } | ||||||
17998 | |||||||
17999 | Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); | ||||||
18000 | return; | ||||||
18001 | } | ||||||
18002 | |||||||
18003 | // TODO: If the result value doesn't fit in an int, it must be a long or long | ||||||
18004 | // long value. ISO C does not support this, but GCC does as an extension, | ||||||
18005 | // emit a warning. | ||||||
18006 | unsigned IntWidth = Context.getTargetInfo().getIntWidth(); | ||||||
18007 | unsigned CharWidth = Context.getTargetInfo().getCharWidth(); | ||||||
18008 | unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); | ||||||
18009 | |||||||
18010 | // Verify that all the values are okay, compute the size of the values, and | ||||||
18011 | // reverse the list. | ||||||
18012 | unsigned NumNegativeBits = 0; | ||||||
18013 | unsigned NumPositiveBits = 0; | ||||||
18014 | |||||||
18015 | // Keep track of whether all elements have type int. | ||||||
18016 | bool AllElementsInt = true; | ||||||
18017 | |||||||
18018 | for (unsigned i = 0, e = Elements.size(); i != e; ++i) { | ||||||
18019 | EnumConstantDecl *ECD = | ||||||
18020 | cast_or_null<EnumConstantDecl>(Elements[i]); | ||||||
18021 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
18022 | |||||||
18023 | const llvm::APSInt &InitVal = ECD->getInitVal(); | ||||||
18024 | |||||||
18025 | // Keep track of the size of positive and negative values. | ||||||
18026 | if (InitVal.isUnsigned() || InitVal.isNonNegative()) | ||||||
18027 | NumPositiveBits = std::max(NumPositiveBits, | ||||||
18028 | (unsigned)InitVal.getActiveBits()); | ||||||
18029 | else | ||||||
18030 | NumNegativeBits = std::max(NumNegativeBits, | ||||||
18031 | (unsigned)InitVal.getMinSignedBits()); | ||||||
18032 | |||||||
18033 | // Keep track of whether every enum element has type int (very common). | ||||||
18034 | if (AllElementsInt) | ||||||
18035 | AllElementsInt = ECD->getType() == Context.IntTy; | ||||||
18036 | } | ||||||
18037 | |||||||
18038 | // Figure out the type that should be used for this enum. | ||||||
18039 | QualType BestType; | ||||||
18040 | unsigned BestWidth; | ||||||
18041 | |||||||
18042 | // C++0x N3000 [conv.prom]p3: | ||||||
18043 | // An rvalue of an unscoped enumeration type whose underlying | ||||||
18044 | // type is not fixed can be converted to an rvalue of the first | ||||||
18045 | // of the following types that can represent all the values of | ||||||
18046 | // the enumeration: int, unsigned int, long int, unsigned long | ||||||
18047 | // int, long long int, or unsigned long long int. | ||||||
18048 | // C99 6.4.4.3p2: | ||||||
18049 | // An identifier declared as an enumeration constant has type int. | ||||||
18050 | // The C99 rule is modified by a gcc extension | ||||||
18051 | QualType BestPromotionType; | ||||||
18052 | |||||||
18053 | bool Packed = Enum->hasAttr<PackedAttr>(); | ||||||
18054 | // -fshort-enums is the equivalent to specifying the packed attribute on all | ||||||
18055 | // enum definitions. | ||||||
18056 | if (LangOpts.ShortEnums) | ||||||
18057 | Packed = true; | ||||||
18058 | |||||||
18059 | // If the enum already has a type because it is fixed or dictated by the | ||||||
18060 | // target, promote that type instead of analyzing the enumerators. | ||||||
18061 | if (Enum->isComplete()) { | ||||||
18062 | BestType = Enum->getIntegerType(); | ||||||
18063 | if (BestType->isPromotableIntegerType()) | ||||||
18064 | BestPromotionType = Context.getPromotedIntegerType(BestType); | ||||||
18065 | else | ||||||
18066 | BestPromotionType = BestType; | ||||||
18067 | |||||||
18068 | BestWidth = Context.getIntWidth(BestType); | ||||||
18069 | } | ||||||
18070 | else if (NumNegativeBits) { | ||||||
18071 | // If there is a negative value, figure out the smallest integer type (of | ||||||
18072 | // int/long/longlong) that fits. | ||||||
18073 | // If it's packed, check also if it fits a char or a short. | ||||||
18074 | if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { | ||||||
18075 | BestType = Context.SignedCharTy; | ||||||
18076 | BestWidth = CharWidth; | ||||||
18077 | } else if (Packed && NumNegativeBits <= ShortWidth && | ||||||
18078 | NumPositiveBits < ShortWidth) { | ||||||
18079 | BestType = Context.ShortTy; | ||||||
18080 | BestWidth = ShortWidth; | ||||||
18081 | } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { | ||||||
18082 | BestType = Context.IntTy; | ||||||
18083 | BestWidth = IntWidth; | ||||||
18084 | } else { | ||||||
18085 | BestWidth = Context.getTargetInfo().getLongWidth(); | ||||||
18086 | |||||||
18087 | if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { | ||||||
18088 | BestType = Context.LongTy; | ||||||
18089 | } else { | ||||||
18090 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | ||||||
18091 | |||||||
18092 | if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) | ||||||
18093 | Diag(Enum->getLocation(), diag::ext_enum_too_large); | ||||||
18094 | BestType = Context.LongLongTy; | ||||||
18095 | } | ||||||
18096 | } | ||||||
18097 | BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); | ||||||
18098 | } else { | ||||||
18099 | // If there is no negative value, figure out the smallest type that fits | ||||||
18100 | // all of the enumerator values. | ||||||
18101 | // If it's packed, check also if it fits a char or a short. | ||||||
18102 | if (Packed && NumPositiveBits <= CharWidth) { | ||||||
18103 | BestType = Context.UnsignedCharTy; | ||||||
18104 | BestPromotionType = Context.IntTy; | ||||||
18105 | BestWidth = CharWidth; | ||||||
18106 | } else if (Packed && NumPositiveBits <= ShortWidth) { | ||||||
18107 | BestType = Context.UnsignedShortTy; | ||||||
18108 | BestPromotionType = Context.IntTy; | ||||||
18109 | BestWidth = ShortWidth; | ||||||
18110 | } else if (NumPositiveBits <= IntWidth) { | ||||||
18111 | BestType = Context.UnsignedIntTy; | ||||||
18112 | BestWidth = IntWidth; | ||||||
18113 | BestPromotionType | ||||||
18114 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
18115 | ? Context.UnsignedIntTy : Context.IntTy; | ||||||
18116 | } else if (NumPositiveBits <= | ||||||
18117 | (BestWidth = Context.getTargetInfo().getLongWidth())) { | ||||||
18118 | BestType = Context.UnsignedLongTy; | ||||||
18119 | BestPromotionType | ||||||
18120 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
18121 | ? Context.UnsignedLongTy : Context.LongTy; | ||||||
18122 | } else { | ||||||
18123 | BestWidth = Context.getTargetInfo().getLongLongWidth(); | ||||||
18124 | 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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 18125, __PRETTY_FUNCTION__)) | ||||||
18125 | "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-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp" , 18125, __PRETTY_FUNCTION__)); | ||||||
18126 | BestType = Context.UnsignedLongLongTy; | ||||||
18127 | BestPromotionType | ||||||
18128 | = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) | ||||||
18129 | ? Context.UnsignedLongLongTy : Context.LongLongTy; | ||||||
18130 | } | ||||||
18131 | } | ||||||
18132 | |||||||
18133 | // Loop over all of the enumerator constants, changing their types to match | ||||||
18134 | // the type of the enum if needed. | ||||||
18135 | for (auto *D : Elements) { | ||||||
18136 | auto *ECD = cast_or_null<EnumConstantDecl>(D); | ||||||
18137 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
18138 | |||||||
18139 | // Standard C says the enumerators have int type, but we allow, as an | ||||||
18140 | // extension, the enumerators to be larger than int size. If each | ||||||
18141 | // enumerator value fits in an int, type it as an int, otherwise type it the | ||||||
18142 | // same as the enumerator decl itself. This means that in "enum { X = 1U }" | ||||||
18143 | // that X has type 'int', not 'unsigned'. | ||||||
18144 | |||||||
18145 | // Determine whether the value fits into an int. | ||||||
18146 | llvm::APSInt InitVal = ECD->getInitVal(); | ||||||
18147 | |||||||
18148 | // If it fits into an integer type, force it. Otherwise force it to match | ||||||
18149 | // the enum decl type. | ||||||
18150 | QualType NewTy; | ||||||
18151 | unsigned NewWidth; | ||||||
18152 | bool NewSign; | ||||||
18153 | if (!getLangOpts().CPlusPlus && | ||||||
18154 | !Enum->isFixed() && | ||||||
18155 | isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { | ||||||
18156 | NewTy = Context.IntTy; | ||||||
18157 | NewWidth = IntWidth; | ||||||
18158 | NewSign = true; | ||||||
18159 | } else if (ECD->getType() == BestType) { | ||||||
18160 | // Already the right type! | ||||||
18161 | if (getLangOpts().CPlusPlus) | ||||||
18162 | // C++ [dcl.enum]p4: Following the closing brace of an | ||||||
18163 | // enum-specifier, each enumerator has the type of its | ||||||
18164 | // enumeration. | ||||||
18165 | ECD->setType(EnumType); | ||||||
18166 | continue; | ||||||
18167 | } else { | ||||||
18168 | NewTy = BestType; | ||||||
18169 | NewWidth = BestWidth; | ||||||
18170 | NewSign = BestType->isSignedIntegerOrEnumerationType(); | ||||||
18171 | } | ||||||
18172 | |||||||
18173 | // Adjust the APSInt value. | ||||||
18174 | InitVal = InitVal.extOrTrunc(NewWidth); | ||||||
18175 | InitVal.setIsSigned(NewSign); | ||||||
18176 | ECD->setInitVal(InitVal); | ||||||
18177 | |||||||
18178 | // Adjust the Expr initializer and type. | ||||||
18179 | if (ECD->getInitExpr() && | ||||||
18180 | !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) | ||||||
18181 | ECD->setInitExpr(ImplicitCastExpr::Create( | ||||||
18182 | Context, NewTy, CK_IntegralCast, ECD->getInitExpr(), | ||||||
18183 | /*base paths*/ nullptr, VK_RValue, FPOptionsOverride())); | ||||||
18184 | if (getLangOpts().CPlusPlus) | ||||||
18185 | // C++ [dcl.enum]p4: Following the closing brace of an | ||||||
18186 | // enum-specifier, each enumerator has the type of its | ||||||
18187 | // enumeration. | ||||||
18188 | ECD->setType(EnumType); | ||||||
18189 | else | ||||||
18190 | ECD->setType(NewTy); | ||||||
18191 | } | ||||||
18192 | |||||||
18193 | Enum->completeDefinition(BestType, BestPromotionType, | ||||||
18194 | NumPositiveBits, NumNegativeBits); | ||||||
18195 | |||||||
18196 | CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); | ||||||
18197 | |||||||
18198 | if (Enum->isClosedFlag()) { | ||||||
18199 | for (Decl *D : Elements) { | ||||||
18200 | EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); | ||||||
18201 | if (!ECD) continue; // Already issued a diagnostic. | ||||||
18202 | |||||||
18203 | llvm::APSInt InitVal = ECD->getInitVal(); | ||||||
18204 | if (InitVal != 0 && !InitVal.isPowerOf2() && | ||||||
18205 | !IsValueInFlagEnum(Enum, InitVal, true)) | ||||||
18206 | Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) | ||||||
18207 | << ECD << Enum; | ||||||
18208 | } | ||||||
18209 | } | ||||||
18210 | |||||||
18211 | // Now that the enum type is defined, ensure it's not been underaligned. | ||||||
18212 | if (Enum->hasAttrs()) | ||||||
18213 | CheckAlignasUnderalignment(Enum); | ||||||
18214 | } | ||||||
18215 | |||||||
18216 | Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, | ||||||
18217 | SourceLocation StartLoc, | ||||||
18218 | SourceLocation EndLoc) { | ||||||
18219 | StringLiteral *AsmString = cast<StringLiteral>(expr); | ||||||
18220 | |||||||
18221 | FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, | ||||||
18222 | AsmString, StartLoc, | ||||||
18223 | EndLoc); | ||||||
18224 | CurContext->addDecl(New); | ||||||
18225 | return New; | ||||||
18226 | } | ||||||
18227 | |||||||
18228 | void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, | ||||||
18229 | IdentifierInfo* AliasName, | ||||||
18230 | SourceLocation PragmaLoc, | ||||||
18231 | SourceLocation NameLoc, | ||||||
18232 | SourceLocation AliasNameLoc) { | ||||||
18233 | NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, | ||||||
18234 | LookupOrdinaryName); | ||||||
18235 | AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), | ||||||
18236 | AttributeCommonInfo::AS_Pragma); | ||||||
18237 | AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( | ||||||
18238 | Context, AliasName->getName(), /*LiteralLabel=*/true, Info); | ||||||
18239 | |||||||
18240 | // If a declaration that: | ||||||
18241 | // 1) declares a function or a variable | ||||||
18242 | // 2) has external linkage | ||||||
18243 | // already exists, add a label attribute to it. | ||||||
18244 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | ||||||
18245 | if (isDeclExternC(PrevDecl)) | ||||||
18246 | PrevDecl->addAttr(Attr); | ||||||
18247 | else | ||||||
18248 | Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) | ||||||
18249 | << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; | ||||||
18250 | // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. | ||||||
18251 | } else | ||||||
18252 | (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); | ||||||
18253 | } | ||||||
18254 | |||||||
18255 | void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, | ||||||
18256 | SourceLocation PragmaLoc, | ||||||
18257 | SourceLocation NameLoc) { | ||||||
18258 | Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); | ||||||
18259 | |||||||
18260 | if (PrevDecl) { | ||||||
18261 | PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); | ||||||
18262 | } else { | ||||||
18263 | (void)WeakUndeclaredIdentifiers.insert( | ||||||
18264 | std::pair<IdentifierInfo*,WeakInfo> | ||||||
18265 | (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); | ||||||
18266 | } | ||||||
18267 | } | ||||||
18268 | |||||||
18269 | void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, | ||||||
18270 | IdentifierInfo* AliasName, | ||||||
18271 | SourceLocation PragmaLoc, | ||||||
18272 | SourceLocation NameLoc, | ||||||
18273 | SourceLocation AliasNameLoc) { | ||||||
18274 | Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, | ||||||
18275 | LookupOrdinaryName); | ||||||
18276 | WeakInfo W = WeakInfo(Name, NameLoc); | ||||||
18277 | |||||||
18278 | if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { | ||||||
18279 | if (!PrevDecl->hasAttr<AliasAttr>()) | ||||||
18280 | if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) | ||||||
18281 | DeclApplyPragmaWeak(TUScope, ND, W); | ||||||
18282 | } else { | ||||||
18283 | (void)WeakUndeclaredIdentifiers.insert( | ||||||
18284 | std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); | ||||||
18285 | } | ||||||
18286 | } | ||||||
18287 | |||||||
18288 | Decl *Sema::getObjCDeclContext() const { | ||||||
18289 | return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); | ||||||
18290 | } | ||||||
18291 | |||||||
18292 | Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD, | ||||||
18293 | bool Final) { | ||||||
18294 | // SYCL functions can be template, so we check if they have appropriate | ||||||
18295 | // attribute prior to checking if it is a template. | ||||||
18296 | if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>()) | ||||||
18297 | return FunctionEmissionStatus::Emitted; | ||||||
18298 | |||||||
18299 | // Templates are emitted when they're instantiated. | ||||||
18300 | if (FD->isDependentContext()) | ||||||
18301 | return FunctionEmissionStatus::TemplateDiscarded; | ||||||
18302 | |||||||
18303 | FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; | ||||||
18304 | if (LangOpts.OpenMPIsDevice) { | ||||||
18305 | Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = | ||||||
18306 | OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); | ||||||
18307 | if (DevTy.hasValue()) { | ||||||
18308 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) | ||||||
18309 | OMPES = FunctionEmissionStatus::OMPDiscarded; | ||||||
18310 | else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || | ||||||
18311 | *DevTy == OMPDeclareTargetDeclAttr::DT_Any) { | ||||||
18312 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
18313 | } | ||||||
18314 | } | ||||||
18315 | } else if (LangOpts.OpenMP) { | ||||||
18316 | // In OpenMP 4.5 all the functions are host functions. | ||||||
18317 | if (LangOpts.OpenMP <= 45) { | ||||||
18318 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
18319 | } else { | ||||||
18320 | Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = | ||||||
18321 | OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); | ||||||
18322 | // In OpenMP 5.0 or above, DevTy may be changed later by | ||||||
18323 | // #pragma omp declare target to(*) device_type(*). Therefore DevTy | ||||||
18324 | // having no value does not imply host. The emission status will be | ||||||
18325 | // checked again at the end of compilation unit. | ||||||
18326 | if (DevTy.hasValue()) { | ||||||
18327 | if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { | ||||||
18328 | OMPES = FunctionEmissionStatus::OMPDiscarded; | ||||||
18329 | } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host || | ||||||
18330 | *DevTy == OMPDeclareTargetDeclAttr::DT_Any) | ||||||
18331 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
18332 | } else if (Final) | ||||||
18333 | OMPES = FunctionEmissionStatus::Emitted; | ||||||
18334 | } | ||||||
18335 | } | ||||||
18336 | if (OMPES == FunctionEmissionStatus::OMPDiscarded || | ||||||
18337 | (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) | ||||||
18338 | return OMPES; | ||||||
18339 | |||||||
18340 | if (LangOpts.CUDA) { | ||||||
18341 | // When compiling for device, host functions are never emitted. Similarly, | ||||||
18342 | // when compiling for host, device and global functions are never emitted. | ||||||
18343 | // (Technically, we do emit a host-side stub for global functions, but this | ||||||
18344 | // doesn't count for our purposes here.) | ||||||
18345 | Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); | ||||||
18346 | if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) | ||||||
18347 | return FunctionEmissionStatus::CUDADiscarded; | ||||||
18348 | if (!LangOpts.CUDAIsDevice && | ||||||
18349 | (T == Sema::CFT_Device || T == Sema::CFT_Global)) | ||||||
18350 | return FunctionEmissionStatus::CUDADiscarded; | ||||||
18351 | |||||||
18352 | // Check whether this function is externally visible -- if so, it's | ||||||
18353 | // known-emitted. | ||||||
18354 | // | ||||||
18355 | // We have to check the GVA linkage of the function's *definition* -- if we | ||||||
18356 | // only have a declaration, we don't know whether or not the function will | ||||||
18357 | // be emitted, because (say) the definition could include "inline". | ||||||
18358 | FunctionDecl *Def = FD->getDefinition(); | ||||||
18359 | |||||||
18360 | if (Def && | ||||||
18361 | !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) | ||||||
18362 | && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) | ||||||
18363 | return FunctionEmissionStatus::Emitted; | ||||||
18364 | } | ||||||
18365 | |||||||
18366 | // Otherwise, the function is known-emitted if it's in our set of | ||||||
18367 | // known-emitted functions. | ||||||
18368 | return FunctionEmissionStatus::Unknown; | ||||||
18369 | } | ||||||
18370 | |||||||
18371 | bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { | ||||||
18372 | // Host-side references to a __global__ function refer to the stub, so the | ||||||
18373 | // function itself is never emitted and therefore should not be marked. | ||||||
18374 | // If we have host fn calls kernel fn calls host+device, the HD function | ||||||
18375 | // does not get instantiated on the host. We model this by omitting at the | ||||||
18376 | // call to the kernel from the callgraph. This ensures that, when compiling | ||||||
18377 | // for host, only HD functions actually called from the host get marked as | ||||||
18378 | // known-emitted. | ||||||
18379 | return LangOpts.CUDA && !LangOpts.CUDAIsDevice && | ||||||
18380 | IdentifyCUDATarget(Callee) == CFT_Global; | ||||||
18381 | } |
1 | //===- Decl.h - Classes for representing 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 | // This file defines the Decl subclasses. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_AST_DECL_H |
14 | #define LLVM_CLANG_AST_DECL_H |
15 | |
16 | #include "clang/AST/APValue.h" |
17 | #include "clang/AST/ASTContextAllocate.h" |
18 | #include "clang/AST/DeclAccessPair.h" |
19 | #include "clang/AST/DeclBase.h" |
20 | #include "clang/AST/DeclarationName.h" |
21 | #include "clang/AST/ExternalASTSource.h" |
22 | #include "clang/AST/NestedNameSpecifier.h" |
23 | #include "clang/AST/Redeclarable.h" |
24 | #include "clang/AST/Type.h" |
25 | #include "clang/Basic/AddressSpaces.h" |
26 | #include "clang/Basic/Diagnostic.h" |
27 | #include "clang/Basic/IdentifierTable.h" |
28 | #include "clang/Basic/LLVM.h" |
29 | #include "clang/Basic/Linkage.h" |
30 | #include "clang/Basic/OperatorKinds.h" |
31 | #include "clang/Basic/PartialDiagnostic.h" |
32 | #include "clang/Basic/PragmaKinds.h" |
33 | #include "clang/Basic/SourceLocation.h" |
34 | #include "clang/Basic/Specifiers.h" |
35 | #include "clang/Basic/Visibility.h" |
36 | #include "llvm/ADT/APSInt.h" |
37 | #include "llvm/ADT/ArrayRef.h" |
38 | #include "llvm/ADT/Optional.h" |
39 | #include "llvm/ADT/PointerIntPair.h" |
40 | #include "llvm/ADT/PointerUnion.h" |
41 | #include "llvm/ADT/StringRef.h" |
42 | #include "llvm/ADT/iterator_range.h" |
43 | #include "llvm/Support/Casting.h" |
44 | #include "llvm/Support/Compiler.h" |
45 | #include "llvm/Support/TrailingObjects.h" |
46 | #include <cassert> |
47 | #include <cstddef> |
48 | #include <cstdint> |
49 | #include <string> |
50 | #include <utility> |
51 | |
52 | namespace clang { |
53 | |
54 | class ASTContext; |
55 | struct ASTTemplateArgumentListInfo; |
56 | class Attr; |
57 | class CompoundStmt; |
58 | class DependentFunctionTemplateSpecializationInfo; |
59 | class EnumDecl; |
60 | class Expr; |
61 | class FunctionTemplateDecl; |
62 | class FunctionTemplateSpecializationInfo; |
63 | class FunctionTypeLoc; |
64 | class LabelStmt; |
65 | class MemberSpecializationInfo; |
66 | class Module; |
67 | class NamespaceDecl; |
68 | class ParmVarDecl; |
69 | class RecordDecl; |
70 | class Stmt; |
71 | class StringLiteral; |
72 | class TagDecl; |
73 | class TemplateArgumentList; |
74 | class TemplateArgumentListInfo; |
75 | class TemplateParameterList; |
76 | class TypeAliasTemplateDecl; |
77 | class TypeLoc; |
78 | class UnresolvedSetImpl; |
79 | class VarTemplateDecl; |
80 | |
81 | /// The top declaration context. |
82 | class TranslationUnitDecl : public Decl, public DeclContext { |
83 | ASTContext &Ctx; |
84 | |
85 | /// The (most recently entered) anonymous namespace for this |
86 | /// translation unit, if one has been created. |
87 | NamespaceDecl *AnonymousNamespace = nullptr; |
88 | |
89 | explicit TranslationUnitDecl(ASTContext &ctx); |
90 | |
91 | virtual void anchor(); |
92 | |
93 | public: |
94 | ASTContext &getASTContext() const { return Ctx; } |
95 | |
96 | NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } |
97 | void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } |
98 | |
99 | static TranslationUnitDecl *Create(ASTContext &C); |
100 | |
101 | // Implement isa/cast/dyncast/etc. |
102 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
103 | static bool classofKind(Kind K) { return K == TranslationUnit; } |
104 | static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { |
105 | return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D)); |
106 | } |
107 | static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { |
108 | return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC)); |
109 | } |
110 | }; |
111 | |
112 | /// Represents a `#pragma comment` line. Always a child of |
113 | /// TranslationUnitDecl. |
114 | class PragmaCommentDecl final |
115 | : public Decl, |
116 | private llvm::TrailingObjects<PragmaCommentDecl, char> { |
117 | friend class ASTDeclReader; |
118 | friend class ASTDeclWriter; |
119 | friend TrailingObjects; |
120 | |
121 | PragmaMSCommentKind CommentKind; |
122 | |
123 | PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc, |
124 | PragmaMSCommentKind CommentKind) |
125 | : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {} |
126 | |
127 | virtual void anchor(); |
128 | |
129 | public: |
130 | static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC, |
131 | SourceLocation CommentLoc, |
132 | PragmaMSCommentKind CommentKind, |
133 | StringRef Arg); |
134 | static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
135 | unsigned ArgSize); |
136 | |
137 | PragmaMSCommentKind getCommentKind() const { return CommentKind; } |
138 | |
139 | StringRef getArg() const { return getTrailingObjects<char>(); } |
140 | |
141 | // Implement isa/cast/dyncast/etc. |
142 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
143 | static bool classofKind(Kind K) { return K == PragmaComment; } |
144 | }; |
145 | |
146 | /// Represents a `#pragma detect_mismatch` line. Always a child of |
147 | /// TranslationUnitDecl. |
148 | class PragmaDetectMismatchDecl final |
149 | : public Decl, |
150 | private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> { |
151 | friend class ASTDeclReader; |
152 | friend class ASTDeclWriter; |
153 | friend TrailingObjects; |
154 | |
155 | size_t ValueStart; |
156 | |
157 | PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc, |
158 | size_t ValueStart) |
159 | : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {} |
160 | |
161 | virtual void anchor(); |
162 | |
163 | public: |
164 | static PragmaDetectMismatchDecl *Create(const ASTContext &C, |
165 | TranslationUnitDecl *DC, |
166 | SourceLocation Loc, StringRef Name, |
167 | StringRef Value); |
168 | static PragmaDetectMismatchDecl * |
169 | CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize); |
170 | |
171 | StringRef getName() const { return getTrailingObjects<char>(); } |
172 | StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; } |
173 | |
174 | // Implement isa/cast/dyncast/etc. |
175 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
176 | static bool classofKind(Kind K) { return K == PragmaDetectMismatch; } |
177 | }; |
178 | |
179 | /// Declaration context for names declared as extern "C" in C++. This |
180 | /// is neither the semantic nor lexical context for such declarations, but is |
181 | /// used to check for conflicts with other extern "C" declarations. Example: |
182 | /// |
183 | /// \code |
184 | /// namespace N { extern "C" void f(); } // #1 |
185 | /// void N::f() {} // #2 |
186 | /// namespace M { extern "C" void f(); } // #3 |
187 | /// \endcode |
188 | /// |
189 | /// The semantic context of #1 is namespace N and its lexical context is the |
190 | /// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical |
191 | /// context is the TU. However, both declarations are also visible in the |
192 | /// extern "C" context. |
193 | /// |
194 | /// The declaration at #3 finds it is a redeclaration of \c N::f through |
195 | /// lookup in the extern "C" context. |
196 | class ExternCContextDecl : public Decl, public DeclContext { |
197 | explicit ExternCContextDecl(TranslationUnitDecl *TU) |
198 | : Decl(ExternCContext, TU, SourceLocation()), |
199 | DeclContext(ExternCContext) {} |
200 | |
201 | virtual void anchor(); |
202 | |
203 | public: |
204 | static ExternCContextDecl *Create(const ASTContext &C, |
205 | TranslationUnitDecl *TU); |
206 | |
207 | // Implement isa/cast/dyncast/etc. |
208 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
209 | static bool classofKind(Kind K) { return K == ExternCContext; } |
210 | static DeclContext *castToDeclContext(const ExternCContextDecl *D) { |
211 | return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D)); |
212 | } |
213 | static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) { |
214 | return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC)); |
215 | } |
216 | }; |
217 | |
218 | /// This represents a decl that may have a name. Many decls have names such |
219 | /// as ObjCMethodDecl, but not \@class, etc. |
220 | /// |
221 | /// Note that not every NamedDecl is actually named (e.g., a struct might |
222 | /// be anonymous), and not every name is an identifier. |
223 | class NamedDecl : public Decl { |
224 | /// The name of this declaration, which is typically a normal |
225 | /// identifier but may also be a special kind of name (C++ |
226 | /// constructor, Objective-C selector, etc.) |
227 | DeclarationName Name; |
228 | |
229 | virtual void anchor(); |
230 | |
231 | private: |
232 | NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__)); |
233 | |
234 | protected: |
235 | NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) |
236 | : Decl(DK, DC, L), Name(N) {} |
237 | |
238 | public: |
239 | /// Get the identifier that names this declaration, if there is one. |
240 | /// |
241 | /// This will return NULL if this declaration has no name (e.g., for |
242 | /// an unnamed class) or if the name is a special name (C++ constructor, |
243 | /// Objective-C selector, etc.). |
244 | IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } |
245 | |
246 | /// Get the name of identifier for this declaration as a StringRef. |
247 | /// |
248 | /// This requires that the declaration have a name and that it be a simple |
249 | /// identifier. |
250 | StringRef getName() const { |
251 | assert(Name.isIdentifier() && "Name is not a simple identifier")((Name.isIdentifier() && "Name is not a simple identifier" ) ? static_cast<void> (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 251, __PRETTY_FUNCTION__)); |
252 | return getIdentifier() ? getIdentifier()->getName() : ""; |
253 | } |
254 | |
255 | /// Get a human-readable name for the declaration, even if it is one of the |
256 | /// special kinds of names (C++ constructor, Objective-C selector, etc). |
257 | /// |
258 | /// Creating this name requires expensive string manipulation, so it should |
259 | /// be called only when performance doesn't matter. For simple declarations, |
260 | /// getNameAsCString() should suffice. |
261 | // |
262 | // FIXME: This function should be renamed to indicate that it is not just an |
263 | // alternate form of getName(), and clients should move as appropriate. |
264 | // |
265 | // FIXME: Deprecated, move clients to getName(). |
266 | std::string getNameAsString() const { return Name.getAsString(); } |
267 | |
268 | /// Pretty-print the unqualified name of this declaration. Can be overloaded |
269 | /// by derived classes to provide a more user-friendly name when appropriate. |
270 | virtual void printName(raw_ostream &os) const; |
271 | |
272 | /// Get the actual, stored name of the declaration, which may be a special |
273 | /// name. |
274 | /// |
275 | /// Note that generally in diagnostics, the non-null \p NamedDecl* itself |
276 | /// should be sent into the diagnostic instead of using the result of |
277 | /// \p getDeclName(). |
278 | /// |
279 | /// A \p DeclarationName in a diagnostic will just be streamed to the output, |
280 | /// which will directly result in a call to \p DeclarationName::print. |
281 | /// |
282 | /// A \p NamedDecl* in a diagnostic will also ultimately result in a call to |
283 | /// \p DeclarationName::print, but with two customisation points along the |
284 | /// way (\p getNameForDiagnostic and \p printName). These are used to print |
285 | /// the template arguments if any, and to provide a user-friendly name for |
286 | /// some entities (such as unnamed variables and anonymous records). |
287 | DeclarationName getDeclName() const { return Name; } |
288 | |
289 | /// Set the name of this declaration. |
290 | void setDeclName(DeclarationName N) { Name = N; } |
291 | |
292 | /// Returns a human-readable qualified name for this declaration, like |
293 | /// A::B::i, for i being member of namespace A::B. |
294 | /// |
295 | /// If the declaration is not a member of context which can be named (record, |
296 | /// namespace), it will return the same result as printName(). |
297 | /// |
298 | /// Creating this name is expensive, so it should be called only when |
299 | /// performance doesn't matter. |
300 | void printQualifiedName(raw_ostream &OS) const; |
301 | void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const; |
302 | |
303 | /// Print only the nested name specifier part of a fully-qualified name, |
304 | /// including the '::' at the end. E.g. |
305 | /// when `printQualifiedName(D)` prints "A::B::i", |
306 | /// this function prints "A::B::". |
307 | void printNestedNameSpecifier(raw_ostream &OS) const; |
308 | void printNestedNameSpecifier(raw_ostream &OS, |
309 | const PrintingPolicy &Policy) const; |
310 | |
311 | // FIXME: Remove string version. |
312 | std::string getQualifiedNameAsString() const; |
313 | |
314 | /// Appends a human-readable name for this declaration into the given stream. |
315 | /// |
316 | /// This is the method invoked by Sema when displaying a NamedDecl |
317 | /// in a diagnostic. It does not necessarily produce the same |
318 | /// result as printName(); for example, class template |
319 | /// specializations are printed with their template arguments. |
320 | virtual void getNameForDiagnostic(raw_ostream &OS, |
321 | const PrintingPolicy &Policy, |
322 | bool Qualified) const; |
323 | |
324 | /// Determine whether this declaration, if known to be well-formed within |
325 | /// its context, will replace the declaration OldD if introduced into scope. |
326 | /// |
327 | /// A declaration will replace another declaration if, for example, it is |
328 | /// a redeclaration of the same variable or function, but not if it is a |
329 | /// declaration of a different kind (function vs. class) or an overloaded |
330 | /// function. |
331 | /// |
332 | /// \param IsKnownNewer \c true if this declaration is known to be newer |
333 | /// than \p OldD (for instance, if this declaration is newly-created). |
334 | bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const; |
335 | |
336 | /// Determine whether this declaration has linkage. |
337 | bool hasLinkage() const; |
338 | |
339 | using Decl::isModulePrivate; |
340 | using Decl::setModulePrivate; |
341 | |
342 | /// Determine whether this declaration is a C++ class member. |
343 | bool isCXXClassMember() const { |
344 | const DeclContext *DC = getDeclContext(); |
345 | |
346 | // C++0x [class.mem]p1: |
347 | // The enumerators of an unscoped enumeration defined in |
348 | // the class are members of the class. |
349 | if (isa<EnumDecl>(DC)) |
350 | DC = DC->getRedeclContext(); |
351 | |
352 | return DC->isRecord(); |
353 | } |
354 | |
355 | /// Determine whether the given declaration is an instance member of |
356 | /// a C++ class. |
357 | bool isCXXInstanceMember() const; |
358 | |
359 | /// Determine what kind of linkage this entity has. |
360 | /// |
361 | /// This is not the linkage as defined by the standard or the codegen notion |
362 | /// of linkage. It is just an implementation detail that is used to compute |
363 | /// those. |
364 | Linkage getLinkageInternal() const; |
365 | |
366 | /// Get the linkage from a semantic point of view. Entities in |
367 | /// anonymous namespaces are external (in c++98). |
368 | Linkage getFormalLinkage() const { |
369 | return clang::getFormalLinkage(getLinkageInternal()); |
370 | } |
371 | |
372 | /// True if this decl has external linkage. |
373 | bool hasExternalFormalLinkage() const { |
374 | return isExternalFormalLinkage(getLinkageInternal()); |
375 | } |
376 | |
377 | bool isExternallyVisible() const { |
378 | return clang::isExternallyVisible(getLinkageInternal()); |
379 | } |
380 | |
381 | /// Determine whether this declaration can be redeclared in a |
382 | /// different translation unit. |
383 | bool isExternallyDeclarable() const { |
384 | return isExternallyVisible() && !getOwningModuleForLinkage(); |
385 | } |
386 | |
387 | /// Determines the visibility of this entity. |
388 | Visibility getVisibility() const { |
389 | return getLinkageAndVisibility().getVisibility(); |
390 | } |
391 | |
392 | /// Determines the linkage and visibility of this entity. |
393 | LinkageInfo getLinkageAndVisibility() const; |
394 | |
395 | /// Kinds of explicit visibility. |
396 | enum ExplicitVisibilityKind { |
397 | /// Do an LV computation for, ultimately, a type. |
398 | /// Visibility may be restricted by type visibility settings and |
399 | /// the visibility of template arguments. |
400 | VisibilityForType, |
401 | |
402 | /// Do an LV computation for, ultimately, a non-type declaration. |
403 | /// Visibility may be restricted by value visibility settings and |
404 | /// the visibility of template arguments. |
405 | VisibilityForValue |
406 | }; |
407 | |
408 | /// If visibility was explicitly specified for this |
409 | /// declaration, return that visibility. |
410 | Optional<Visibility> |
411 | getExplicitVisibility(ExplicitVisibilityKind kind) const; |
412 | |
413 | /// True if the computed linkage is valid. Used for consistency |
414 | /// checking. Should always return true. |
415 | bool isLinkageValid() const; |
416 | |
417 | /// True if something has required us to compute the linkage |
418 | /// of this declaration. |
419 | /// |
420 | /// Language features which can retroactively change linkage (like a |
421 | /// typedef name for linkage purposes) may need to consider this, |
422 | /// but hopefully only in transitory ways during parsing. |
423 | bool hasLinkageBeenComputed() const { |
424 | return hasCachedLinkage(); |
425 | } |
426 | |
427 | /// Looks through UsingDecls and ObjCCompatibleAliasDecls for |
428 | /// the underlying named decl. |
429 | NamedDecl *getUnderlyingDecl() { |
430 | // Fast-path the common case. |
431 | if (this->getKind() != UsingShadow && |
432 | this->getKind() != ConstructorUsingShadow && |
433 | this->getKind() != ObjCCompatibleAlias && |
434 | this->getKind() != NamespaceAlias) |
435 | return this; |
436 | |
437 | return getUnderlyingDeclImpl(); |
438 | } |
439 | const NamedDecl *getUnderlyingDecl() const { |
440 | return const_cast<NamedDecl*>(this)->getUnderlyingDecl(); |
441 | } |
442 | |
443 | NamedDecl *getMostRecentDecl() { |
444 | return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl()); |
445 | } |
446 | const NamedDecl *getMostRecentDecl() const { |
447 | return const_cast<NamedDecl*>(this)->getMostRecentDecl(); |
448 | } |
449 | |
450 | ObjCStringFormatFamily getObjCFStringFormattingFamily() const; |
451 | |
452 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
453 | static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } |
454 | }; |
455 | |
456 | inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) { |
457 | ND.printName(OS); |
458 | return OS; |
459 | } |
460 | |
461 | /// Represents the declaration of a label. Labels also have a |
462 | /// corresponding LabelStmt, which indicates the position that the label was |
463 | /// defined at. For normal labels, the location of the decl is the same as the |
464 | /// location of the statement. For GNU local labels (__label__), the decl |
465 | /// location is where the __label__ is. |
466 | class LabelDecl : public NamedDecl { |
467 | LabelStmt *TheStmt; |
468 | StringRef MSAsmName; |
469 | bool MSAsmNameResolved = false; |
470 | |
471 | /// For normal labels, this is the same as the main declaration |
472 | /// label, i.e., the location of the identifier; for GNU local labels, |
473 | /// this is the location of the __label__ keyword. |
474 | SourceLocation LocStart; |
475 | |
476 | LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, |
477 | LabelStmt *S, SourceLocation StartL) |
478 | : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} |
479 | |
480 | void anchor() override; |
481 | |
482 | public: |
483 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
484 | SourceLocation IdentL, IdentifierInfo *II); |
485 | static LabelDecl *Create(ASTContext &C, DeclContext *DC, |
486 | SourceLocation IdentL, IdentifierInfo *II, |
487 | SourceLocation GnuLabelL); |
488 | static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
489 | |
490 | LabelStmt *getStmt() const { return TheStmt; } |
491 | void setStmt(LabelStmt *T) { TheStmt = T; } |
492 | |
493 | bool isGnuLocal() const { return LocStart != getLocation(); } |
494 | void setLocStart(SourceLocation L) { LocStart = L; } |
495 | |
496 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
497 | return SourceRange(LocStart, getLocation()); |
498 | } |
499 | |
500 | bool isMSAsmLabel() const { return !MSAsmName.empty(); } |
501 | bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; } |
502 | void setMSAsmLabel(StringRef Name); |
503 | StringRef getMSAsmLabel() const { return MSAsmName; } |
504 | void setMSAsmLabelResolved() { MSAsmNameResolved = true; } |
505 | |
506 | // Implement isa/cast/dyncast/etc. |
507 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
508 | static bool classofKind(Kind K) { return K == Label; } |
509 | }; |
510 | |
511 | /// Represent a C++ namespace. |
512 | class NamespaceDecl : public NamedDecl, public DeclContext, |
513 | public Redeclarable<NamespaceDecl> |
514 | { |
515 | /// The starting location of the source range, pointing |
516 | /// to either the namespace or the inline keyword. |
517 | SourceLocation LocStart; |
518 | |
519 | /// The ending location of the source range. |
520 | SourceLocation RBraceLoc; |
521 | |
522 | /// A pointer to either the anonymous namespace that lives just inside |
523 | /// this namespace or to the first namespace in the chain (the latter case |
524 | /// only when this is not the first in the chain), along with a |
525 | /// boolean value indicating whether this is an inline namespace. |
526 | llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline; |
527 | |
528 | NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline, |
529 | SourceLocation StartLoc, SourceLocation IdLoc, |
530 | IdentifierInfo *Id, NamespaceDecl *PrevDecl); |
531 | |
532 | using redeclarable_base = Redeclarable<NamespaceDecl>; |
533 | |
534 | NamespaceDecl *getNextRedeclarationImpl() override; |
535 | NamespaceDecl *getPreviousDeclImpl() override; |
536 | NamespaceDecl *getMostRecentDeclImpl() override; |
537 | |
538 | public: |
539 | friend class ASTDeclReader; |
540 | friend class ASTDeclWriter; |
541 | |
542 | static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, |
543 | bool Inline, SourceLocation StartLoc, |
544 | SourceLocation IdLoc, IdentifierInfo *Id, |
545 | NamespaceDecl *PrevDecl); |
546 | |
547 | static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
548 | |
549 | using redecl_range = redeclarable_base::redecl_range; |
550 | using redecl_iterator = redeclarable_base::redecl_iterator; |
551 | |
552 | using redeclarable_base::redecls_begin; |
553 | using redeclarable_base::redecls_end; |
554 | using redeclarable_base::redecls; |
555 | using redeclarable_base::getPreviousDecl; |
556 | using redeclarable_base::getMostRecentDecl; |
557 | using redeclarable_base::isFirstDecl; |
558 | |
559 | /// Returns true if this is an anonymous namespace declaration. |
560 | /// |
561 | /// For example: |
562 | /// \code |
563 | /// namespace { |
564 | /// ... |
565 | /// }; |
566 | /// \endcode |
567 | /// q.v. C++ [namespace.unnamed] |
568 | bool isAnonymousNamespace() const { |
569 | return !getIdentifier(); |
570 | } |
571 | |
572 | /// Returns true if this is an inline namespace declaration. |
573 | bool isInline() const { |
574 | return AnonOrFirstNamespaceAndInline.getInt(); |
575 | } |
576 | |
577 | /// Set whether this is an inline namespace declaration. |
578 | void setInline(bool Inline) { |
579 | AnonOrFirstNamespaceAndInline.setInt(Inline); |
580 | } |
581 | |
582 | /// Get the original (first) namespace declaration. |
583 | NamespaceDecl *getOriginalNamespace(); |
584 | |
585 | /// Get the original (first) namespace declaration. |
586 | const NamespaceDecl *getOriginalNamespace() const; |
587 | |
588 | /// Return true if this declaration is an original (first) declaration |
589 | /// of the namespace. This is false for non-original (subsequent) namespace |
590 | /// declarations and anonymous namespaces. |
591 | bool isOriginalNamespace() const; |
592 | |
593 | /// Retrieve the anonymous namespace nested inside this namespace, |
594 | /// if any. |
595 | NamespaceDecl *getAnonymousNamespace() const { |
596 | return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer(); |
597 | } |
598 | |
599 | void setAnonymousNamespace(NamespaceDecl *D) { |
600 | getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D); |
601 | } |
602 | |
603 | /// Retrieves the canonical declaration of this namespace. |
604 | NamespaceDecl *getCanonicalDecl() override { |
605 | return getOriginalNamespace(); |
606 | } |
607 | const NamespaceDecl *getCanonicalDecl() const { |
608 | return getOriginalNamespace(); |
609 | } |
610 | |
611 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
612 | return SourceRange(LocStart, RBraceLoc); |
613 | } |
614 | |
615 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
616 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
617 | void setLocStart(SourceLocation L) { LocStart = L; } |
618 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
619 | |
620 | // Implement isa/cast/dyncast/etc. |
621 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
622 | static bool classofKind(Kind K) { return K == Namespace; } |
623 | static DeclContext *castToDeclContext(const NamespaceDecl *D) { |
624 | return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D)); |
625 | } |
626 | static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { |
627 | return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC)); |
628 | } |
629 | }; |
630 | |
631 | /// Represent the declaration of a variable (in which case it is |
632 | /// an lvalue) a function (in which case it is a function designator) or |
633 | /// an enum constant. |
634 | class ValueDecl : public NamedDecl { |
635 | QualType DeclType; |
636 | |
637 | void anchor() override; |
638 | |
639 | protected: |
640 | ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, |
641 | DeclarationName N, QualType T) |
642 | : NamedDecl(DK, DC, L, N), DeclType(T) {} |
643 | |
644 | public: |
645 | QualType getType() const { return DeclType; } |
646 | void setType(QualType newType) { DeclType = newType; } |
647 | |
648 | /// Determine whether this symbol is weakly-imported, |
649 | /// or declared with the weak or weak-ref attr. |
650 | bool isWeak() const; |
651 | |
652 | // Implement isa/cast/dyncast/etc. |
653 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
654 | static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } |
655 | }; |
656 | |
657 | /// A struct with extended info about a syntactic |
658 | /// name qualifier, to be used for the case of out-of-line declarations. |
659 | struct QualifierInfo { |
660 | NestedNameSpecifierLoc QualifierLoc; |
661 | |
662 | /// The number of "outer" template parameter lists. |
663 | /// The count includes all of the template parameter lists that were matched |
664 | /// against the template-ids occurring into the NNS and possibly (in the |
665 | /// case of an explicit specialization) a final "template <>". |
666 | unsigned NumTemplParamLists = 0; |
667 | |
668 | /// A new-allocated array of size NumTemplParamLists, |
669 | /// containing pointers to the "outer" template parameter lists. |
670 | /// It includes all of the template parameter lists that were matched |
671 | /// against the template-ids occurring into the NNS and possibly (in the |
672 | /// case of an explicit specialization) a final "template <>". |
673 | TemplateParameterList** TemplParamLists = nullptr; |
674 | |
675 | QualifierInfo() = default; |
676 | QualifierInfo(const QualifierInfo &) = delete; |
677 | QualifierInfo& operator=(const QualifierInfo &) = delete; |
678 | |
679 | /// Sets info about "outer" template parameter lists. |
680 | void setTemplateParameterListsInfo(ASTContext &Context, |
681 | ArrayRef<TemplateParameterList *> TPLists); |
682 | }; |
683 | |
684 | /// Represents a ValueDecl that came out of a declarator. |
685 | /// Contains type source information through TypeSourceInfo. |
686 | class DeclaratorDecl : public ValueDecl { |
687 | // A struct representing a TInfo, a trailing requires-clause and a syntactic |
688 | // qualifier, to be used for the (uncommon) case of out-of-line declarations |
689 | // and constrained function decls. |
690 | struct ExtInfo : public QualifierInfo { |
691 | TypeSourceInfo *TInfo; |
692 | Expr *TrailingRequiresClause = nullptr; |
693 | }; |
694 | |
695 | llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo; |
696 | |
697 | /// The start of the source range for this declaration, |
698 | /// ignoring outer template declarations. |
699 | SourceLocation InnerLocStart; |
700 | |
701 | bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); } |
702 | ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); } |
703 | const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); } |
704 | |
705 | protected: |
706 | DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, |
707 | DeclarationName N, QualType T, TypeSourceInfo *TInfo, |
708 | SourceLocation StartL) |
709 | : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {} |
710 | |
711 | public: |
712 | friend class ASTDeclReader; |
713 | friend class ASTDeclWriter; |
714 | |
715 | TypeSourceInfo *getTypeSourceInfo() const { |
716 | return hasExtInfo() |
717 | ? getExtInfo()->TInfo |
718 | : DeclInfo.get<TypeSourceInfo*>(); |
719 | } |
720 | |
721 | void setTypeSourceInfo(TypeSourceInfo *TI) { |
722 | if (hasExtInfo()) |
723 | getExtInfo()->TInfo = TI; |
724 | else |
725 | DeclInfo = TI; |
726 | } |
727 | |
728 | /// Return start of source range ignoring outer template declarations. |
729 | SourceLocation getInnerLocStart() const { return InnerLocStart; } |
730 | void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } |
731 | |
732 | /// Return start of source range taking into account any outer template |
733 | /// declarations. |
734 | SourceLocation getOuterLocStart() const; |
735 | |
736 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
737 | |
738 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
739 | return getOuterLocStart(); |
740 | } |
741 | |
742 | /// Retrieve the nested-name-specifier that qualifies the name of this |
743 | /// declaration, if it was present in the source. |
744 | NestedNameSpecifier *getQualifier() const { |
745 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
746 | : nullptr; |
747 | } |
748 | |
749 | /// Retrieve the nested-name-specifier (with source-location |
750 | /// information) that qualifies the name of this declaration, if it was |
751 | /// present in the source. |
752 | NestedNameSpecifierLoc getQualifierLoc() const { |
753 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
754 | : NestedNameSpecifierLoc(); |
755 | } |
756 | |
757 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
758 | |
759 | /// \brief Get the constraint-expression introduced by the trailing |
760 | /// requires-clause in the function/member declaration, or null if no |
761 | /// requires-clause was provided. |
762 | Expr *getTrailingRequiresClause() { |
763 | return hasExtInfo() ? getExtInfo()->TrailingRequiresClause |
764 | : nullptr; |
765 | } |
766 | |
767 | const Expr *getTrailingRequiresClause() const { |
768 | return hasExtInfo() ? getExtInfo()->TrailingRequiresClause |
769 | : nullptr; |
770 | } |
771 | |
772 | void setTrailingRequiresClause(Expr *TrailingRequiresClause); |
773 | |
774 | unsigned getNumTemplateParameterLists() const { |
775 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
776 | } |
777 | |
778 | TemplateParameterList *getTemplateParameterList(unsigned index) const { |
779 | assert(index < getNumTemplateParameterLists())((index < getNumTemplateParameterLists()) ? static_cast< void> (0) : __assert_fail ("index < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 779, __PRETTY_FUNCTION__)); |
780 | return getExtInfo()->TemplParamLists[index]; |
781 | } |
782 | |
783 | void setTemplateParameterListsInfo(ASTContext &Context, |
784 | ArrayRef<TemplateParameterList *> TPLists); |
785 | |
786 | SourceLocation getTypeSpecStartLoc() const; |
787 | SourceLocation getTypeSpecEndLoc() const; |
788 | |
789 | // Implement isa/cast/dyncast/etc. |
790 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
791 | static bool classofKind(Kind K) { |
792 | return K >= firstDeclarator && K <= lastDeclarator; |
793 | } |
794 | }; |
795 | |
796 | /// Structure used to store a statement, the constant value to |
797 | /// which it was evaluated (if any), and whether or not the statement |
798 | /// is an integral constant expression (if known). |
799 | struct EvaluatedStmt { |
800 | /// Whether this statement was already evaluated. |
801 | bool WasEvaluated : 1; |
802 | |
803 | /// Whether this statement is being evaluated. |
804 | bool IsEvaluating : 1; |
805 | |
806 | /// Whether we already checked whether this statement was an |
807 | /// integral constant expression. |
808 | bool CheckedICE : 1; |
809 | |
810 | /// Whether we are checking whether this statement is an |
811 | /// integral constant expression. |
812 | bool CheckingICE : 1; |
813 | |
814 | /// Whether this statement is an integral constant expression, |
815 | /// or in C++11, whether the statement is a constant expression. Only |
816 | /// valid if CheckedICE is true. |
817 | bool IsICE : 1; |
818 | |
819 | /// Whether this variable is known to have constant destruction. That is, |
820 | /// whether running the destructor on the initial value is a side-effect |
821 | /// (and doesn't inspect any state that might have changed during program |
822 | /// execution). This is currently only computed if the destructor is |
823 | /// non-trivial. |
824 | bool HasConstantDestruction : 1; |
825 | |
826 | Stmt *Value; |
827 | APValue Evaluated; |
828 | |
829 | EvaluatedStmt() |
830 | : WasEvaluated(false), IsEvaluating(false), CheckedICE(false), |
831 | CheckingICE(false), IsICE(false), HasConstantDestruction(false) {} |
832 | }; |
833 | |
834 | /// Represents a variable declaration or definition. |
835 | class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> { |
836 | public: |
837 | /// Initialization styles. |
838 | enum InitializationStyle { |
839 | /// C-style initialization with assignment |
840 | CInit, |
841 | |
842 | /// Call-style initialization (C++98) |
843 | CallInit, |
844 | |
845 | /// Direct list-initialization (C++11) |
846 | ListInit |
847 | }; |
848 | |
849 | /// Kinds of thread-local storage. |
850 | enum TLSKind { |
851 | /// Not a TLS variable. |
852 | TLS_None, |
853 | |
854 | /// TLS with a known-constant initializer. |
855 | TLS_Static, |
856 | |
857 | /// TLS with a dynamic initializer. |
858 | TLS_Dynamic |
859 | }; |
860 | |
861 | /// Return the string used to specify the storage class \p SC. |
862 | /// |
863 | /// It is illegal to call this function with SC == None. |
864 | static const char *getStorageClassSpecifierString(StorageClass SC); |
865 | |
866 | protected: |
867 | // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we |
868 | // have allocated the auxiliary struct of information there. |
869 | // |
870 | // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for |
871 | // this as *many* VarDecls are ParmVarDecls that don't have default |
872 | // arguments. We could save some space by moving this pointer union to be |
873 | // allocated in trailing space when necessary. |
874 | using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>; |
875 | |
876 | /// The initializer for this variable or, for a ParmVarDecl, the |
877 | /// C++ default argument. |
878 | mutable InitType Init; |
879 | |
880 | private: |
881 | friend class ASTDeclReader; |
882 | friend class ASTNodeImporter; |
883 | friend class StmtIteratorBase; |
884 | |
885 | class VarDeclBitfields { |
886 | friend class ASTDeclReader; |
887 | friend class VarDecl; |
888 | |
889 | unsigned SClass : 3; |
890 | unsigned TSCSpec : 2; |
891 | unsigned InitStyle : 2; |
892 | |
893 | /// Whether this variable is an ARC pseudo-__strong variable; see |
894 | /// isARCPseudoStrong() for details. |
895 | unsigned ARCPseudoStrong : 1; |
896 | }; |
897 | enum { NumVarDeclBits = 8 }; |
898 | |
899 | protected: |
900 | enum { NumParameterIndexBits = 8 }; |
901 | |
902 | enum DefaultArgKind { |
903 | DAK_None, |
904 | DAK_Unparsed, |
905 | DAK_Uninstantiated, |
906 | DAK_Normal |
907 | }; |
908 | |
909 | enum { NumScopeDepthOrObjCQualsBits = 7 }; |
910 | |
911 | class ParmVarDeclBitfields { |
912 | friend class ASTDeclReader; |
913 | friend class ParmVarDecl; |
914 | |
915 | unsigned : NumVarDeclBits; |
916 | |
917 | /// Whether this parameter inherits a default argument from a |
918 | /// prior declaration. |
919 | unsigned HasInheritedDefaultArg : 1; |
920 | |
921 | /// Describes the kind of default argument for this parameter. By default |
922 | /// this is none. If this is normal, then the default argument is stored in |
923 | /// the \c VarDecl initializer expression unless we were unable to parse |
924 | /// (even an invalid) expression for the default argument. |
925 | unsigned DefaultArgKind : 2; |
926 | |
927 | /// Whether this parameter undergoes K&R argument promotion. |
928 | unsigned IsKNRPromoted : 1; |
929 | |
930 | /// Whether this parameter is an ObjC method parameter or not. |
931 | unsigned IsObjCMethodParam : 1; |
932 | |
933 | /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier. |
934 | /// Otherwise, the number of function parameter scopes enclosing |
935 | /// the function parameter scope in which this parameter was |
936 | /// declared. |
937 | unsigned ScopeDepthOrObjCQuals : NumScopeDepthOrObjCQualsBits; |
938 | |
939 | /// The number of parameters preceding this parameter in the |
940 | /// function parameter scope in which it was declared. |
941 | unsigned ParameterIndex : NumParameterIndexBits; |
942 | }; |
943 | |
944 | class NonParmVarDeclBitfields { |
945 | friend class ASTDeclReader; |
946 | friend class ImplicitParamDecl; |
947 | friend class VarDecl; |
948 | |
949 | unsigned : NumVarDeclBits; |
950 | |
951 | // FIXME: We need something similar to CXXRecordDecl::DefinitionData. |
952 | /// Whether this variable is a definition which was demoted due to |
953 | /// module merge. |
954 | unsigned IsThisDeclarationADemotedDefinition : 1; |
955 | |
956 | /// Whether this variable is the exception variable in a C++ catch |
957 | /// or an Objective-C @catch statement. |
958 | unsigned ExceptionVar : 1; |
959 | |
960 | /// Whether this local variable could be allocated in the return |
961 | /// slot of its function, enabling the named return value optimization |
962 | /// (NRVO). |
963 | unsigned NRVOVariable : 1; |
964 | |
965 | /// Whether this variable is the for-range-declaration in a C++0x |
966 | /// for-range statement. |
967 | unsigned CXXForRangeDecl : 1; |
968 | |
969 | /// Whether this variable is the for-in loop declaration in Objective-C. |
970 | unsigned ObjCForDecl : 1; |
971 | |
972 | /// Whether this variable is (C++1z) inline. |
973 | unsigned IsInline : 1; |
974 | |
975 | /// Whether this variable has (C++1z) inline explicitly specified. |
976 | unsigned IsInlineSpecified : 1; |
977 | |
978 | /// Whether this variable is (C++0x) constexpr. |
979 | unsigned IsConstexpr : 1; |
980 | |
981 | /// Whether this variable is the implicit variable for a lambda |
982 | /// init-capture. |
983 | unsigned IsInitCapture : 1; |
984 | |
985 | /// Whether this local extern variable's previous declaration was |
986 | /// declared in the same block scope. This controls whether we should merge |
987 | /// the type of this declaration with its previous declaration. |
988 | unsigned PreviousDeclInSameBlockScope : 1; |
989 | |
990 | /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or |
991 | /// something else. |
992 | unsigned ImplicitParamKind : 3; |
993 | |
994 | unsigned EscapingByref : 1; |
995 | }; |
996 | |
997 | union { |
998 | unsigned AllBits; |
999 | VarDeclBitfields VarDeclBits; |
1000 | ParmVarDeclBitfields ParmVarDeclBits; |
1001 | NonParmVarDeclBitfields NonParmVarDeclBits; |
1002 | }; |
1003 | |
1004 | VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1005 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
1006 | TypeSourceInfo *TInfo, StorageClass SC); |
1007 | |
1008 | using redeclarable_base = Redeclarable<VarDecl>; |
1009 | |
1010 | VarDecl *getNextRedeclarationImpl() override { |
1011 | return getNextRedeclaration(); |
1012 | } |
1013 | |
1014 | VarDecl *getPreviousDeclImpl() override { |
1015 | return getPreviousDecl(); |
1016 | } |
1017 | |
1018 | VarDecl *getMostRecentDeclImpl() override { |
1019 | return getMostRecentDecl(); |
1020 | } |
1021 | |
1022 | public: |
1023 | using redecl_range = redeclarable_base::redecl_range; |
1024 | using redecl_iterator = redeclarable_base::redecl_iterator; |
1025 | |
1026 | using redeclarable_base::redecls_begin; |
1027 | using redeclarable_base::redecls_end; |
1028 | using redeclarable_base::redecls; |
1029 | using redeclarable_base::getPreviousDecl; |
1030 | using redeclarable_base::getMostRecentDecl; |
1031 | using redeclarable_base::isFirstDecl; |
1032 | |
1033 | static VarDecl *Create(ASTContext &C, DeclContext *DC, |
1034 | SourceLocation StartLoc, SourceLocation IdLoc, |
1035 | IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, |
1036 | StorageClass S); |
1037 | |
1038 | static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1039 | |
1040 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1041 | |
1042 | /// Returns the storage class as written in the source. For the |
1043 | /// computed linkage of symbol, see getLinkage. |
1044 | StorageClass getStorageClass() const { |
1045 | return (StorageClass) VarDeclBits.SClass; |
1046 | } |
1047 | void setStorageClass(StorageClass SC); |
1048 | |
1049 | void setTSCSpec(ThreadStorageClassSpecifier TSC) { |
1050 | VarDeclBits.TSCSpec = TSC; |
1051 | assert(VarDeclBits.TSCSpec == TSC && "truncation")((VarDeclBits.TSCSpec == TSC && "truncation") ? static_cast <void> (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1051, __PRETTY_FUNCTION__)); |
1052 | } |
1053 | ThreadStorageClassSpecifier getTSCSpec() const { |
1054 | return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec); |
1055 | } |
1056 | TLSKind getTLSKind() const; |
1057 | |
1058 | /// Returns true if a variable with function scope is a non-static local |
1059 | /// variable. |
1060 | bool hasLocalStorage() const { |
1061 | if (getStorageClass() == SC_None) { |
1062 | // OpenCL v1.2 s6.5.3: The __constant or constant address space name is |
1063 | // used to describe variables allocated in global memory and which are |
1064 | // accessed inside a kernel(s) as read-only variables. As such, variables |
1065 | // in constant address space cannot have local storage. |
1066 | if (getType().getAddressSpace() == LangAS::opencl_constant) |
1067 | return false; |
1068 | // Second check is for C++11 [dcl.stc]p4. |
1069 | return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified; |
1070 | } |
1071 | |
1072 | // Global Named Register (GNU extension) |
1073 | if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm()) |
1074 | return false; |
1075 | |
1076 | // Return true for: Auto, Register. |
1077 | // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal. |
1078 | |
1079 | return getStorageClass() >= SC_Auto; |
1080 | } |
1081 | |
1082 | /// Returns true if a variable with function scope is a static local |
1083 | /// variable. |
1084 | bool isStaticLocal() const { |
1085 | return (getStorageClass() == SC_Static || |
1086 | // C++11 [dcl.stc]p4 |
1087 | (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local)) |
1088 | && !isFileVarDecl(); |
1089 | } |
1090 | |
1091 | /// Returns true if a variable has extern or __private_extern__ |
1092 | /// storage. |
1093 | bool hasExternalStorage() const { |
1094 | return getStorageClass() == SC_Extern || |
1095 | getStorageClass() == SC_PrivateExtern; |
1096 | } |
1097 | |
1098 | /// Returns true for all variables that do not have local storage. |
1099 | /// |
1100 | /// This includes all global variables as well as static variables declared |
1101 | /// within a function. |
1102 | bool hasGlobalStorage() const { return !hasLocalStorage(); } |
1103 | |
1104 | /// Get the storage duration of this variable, per C++ [basic.stc]. |
1105 | StorageDuration getStorageDuration() const { |
1106 | return hasLocalStorage() ? SD_Automatic : |
1107 | getTSCSpec() ? SD_Thread : SD_Static; |
1108 | } |
1109 | |
1110 | /// Compute the language linkage. |
1111 | LanguageLinkage getLanguageLinkage() const; |
1112 | |
1113 | /// Determines whether this variable is a variable with external, C linkage. |
1114 | bool isExternC() const; |
1115 | |
1116 | /// Determines whether this variable's context is, or is nested within, |
1117 | /// a C++ extern "C" linkage spec. |
1118 | bool isInExternCContext() const; |
1119 | |
1120 | /// Determines whether this variable's context is, or is nested within, |
1121 | /// a C++ extern "C++" linkage spec. |
1122 | bool isInExternCXXContext() const; |
1123 | |
1124 | /// Returns true for local variable declarations other than parameters. |
1125 | /// Note that this includes static variables inside of functions. It also |
1126 | /// includes variables inside blocks. |
1127 | /// |
1128 | /// void foo() { int x; static int y; extern int z; } |
1129 | bool isLocalVarDecl() const { |
1130 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1131 | return false; |
1132 | if (const DeclContext *DC = getLexicalDeclContext()) |
1133 | return DC->getRedeclContext()->isFunctionOrMethod(); |
1134 | return false; |
1135 | } |
1136 | |
1137 | /// Similar to isLocalVarDecl but also includes parameters. |
1138 | bool isLocalVarDeclOrParm() const { |
1139 | return isLocalVarDecl() || getKind() == Decl::ParmVar; |
1140 | } |
1141 | |
1142 | /// Similar to isLocalVarDecl, but excludes variables declared in blocks. |
1143 | bool isFunctionOrMethodVarDecl() const { |
1144 | if (getKind() != Decl::Var && getKind() != Decl::Decomposition) |
1145 | return false; |
1146 | const DeclContext *DC = getLexicalDeclContext()->getRedeclContext(); |
1147 | return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; |
1148 | } |
1149 | |
1150 | /// Determines whether this is a static data member. |
1151 | /// |
1152 | /// This will only be true in C++, and applies to, e.g., the |
1153 | /// variable 'x' in: |
1154 | /// \code |
1155 | /// struct S { |
1156 | /// static int x; |
1157 | /// }; |
1158 | /// \endcode |
1159 | bool isStaticDataMember() const { |
1160 | // If it wasn't static, it would be a FieldDecl. |
1161 | return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); |
1162 | } |
1163 | |
1164 | VarDecl *getCanonicalDecl() override; |
1165 | const VarDecl *getCanonicalDecl() const { |
1166 | return const_cast<VarDecl*>(this)->getCanonicalDecl(); |
1167 | } |
1168 | |
1169 | enum DefinitionKind { |
1170 | /// This declaration is only a declaration. |
1171 | DeclarationOnly, |
1172 | |
1173 | /// This declaration is a tentative definition. |
1174 | TentativeDefinition, |
1175 | |
1176 | /// This declaration is definitely a definition. |
1177 | Definition |
1178 | }; |
1179 | |
1180 | /// Check whether this declaration is a definition. If this could be |
1181 | /// a tentative definition (in C), don't check whether there's an overriding |
1182 | /// definition. |
1183 | DefinitionKind isThisDeclarationADefinition(ASTContext &) const; |
1184 | DefinitionKind isThisDeclarationADefinition() const { |
1185 | return isThisDeclarationADefinition(getASTContext()); |
1186 | } |
1187 | |
1188 | /// Check whether this variable is defined in this translation unit. |
1189 | DefinitionKind hasDefinition(ASTContext &) const; |
1190 | DefinitionKind hasDefinition() const { |
1191 | return hasDefinition(getASTContext()); |
1192 | } |
1193 | |
1194 | /// Get the tentative definition that acts as the real definition in a TU. |
1195 | /// Returns null if there is a proper definition available. |
1196 | VarDecl *getActingDefinition(); |
1197 | const VarDecl *getActingDefinition() const { |
1198 | return const_cast<VarDecl*>(this)->getActingDefinition(); |
1199 | } |
1200 | |
1201 | /// Get the real (not just tentative) definition for this declaration. |
1202 | VarDecl *getDefinition(ASTContext &); |
1203 | const VarDecl *getDefinition(ASTContext &C) const { |
1204 | return const_cast<VarDecl*>(this)->getDefinition(C); |
1205 | } |
1206 | VarDecl *getDefinition() { |
1207 | return getDefinition(getASTContext()); |
1208 | } |
1209 | const VarDecl *getDefinition() const { |
1210 | return const_cast<VarDecl*>(this)->getDefinition(); |
1211 | } |
1212 | |
1213 | /// Determine whether this is or was instantiated from an out-of-line |
1214 | /// definition of a static data member. |
1215 | bool isOutOfLine() const override; |
1216 | |
1217 | /// Returns true for file scoped variable declaration. |
1218 | bool isFileVarDecl() const { |
1219 | Kind K = getKind(); |
1220 | if (K == ParmVar || K == ImplicitParam) |
1221 | return false; |
1222 | |
1223 | if (getLexicalDeclContext()->getRedeclContext()->isFileContext()) |
1224 | return true; |
1225 | |
1226 | if (isStaticDataMember()) |
1227 | return true; |
1228 | |
1229 | return false; |
1230 | } |
1231 | |
1232 | /// Get the initializer for this variable, no matter which |
1233 | /// declaration it is attached to. |
1234 | const Expr *getAnyInitializer() const { |
1235 | const VarDecl *D; |
1236 | return getAnyInitializer(D); |
1237 | } |
1238 | |
1239 | /// Get the initializer for this variable, no matter which |
1240 | /// declaration it is attached to. Also get that declaration. |
1241 | const Expr *getAnyInitializer(const VarDecl *&D) const; |
1242 | |
1243 | bool hasInit() const; |
1244 | const Expr *getInit() const { |
1245 | return const_cast<VarDecl *>(this)->getInit(); |
1246 | } |
1247 | Expr *getInit(); |
1248 | |
1249 | /// Retrieve the address of the initializer expression. |
1250 | Stmt **getInitAddress(); |
1251 | |
1252 | void setInit(Expr *I); |
1253 | |
1254 | /// Get the initializing declaration of this variable, if any. This is |
1255 | /// usually the definition, except that for a static data member it can be |
1256 | /// the in-class declaration. |
1257 | VarDecl *getInitializingDeclaration(); |
1258 | const VarDecl *getInitializingDeclaration() const { |
1259 | return const_cast<VarDecl *>(this)->getInitializingDeclaration(); |
1260 | } |
1261 | |
1262 | /// Determine whether this variable's value might be usable in a |
1263 | /// constant expression, according to the relevant language standard. |
1264 | /// This only checks properties of the declaration, and does not check |
1265 | /// whether the initializer is in fact a constant expression. |
1266 | bool mightBeUsableInConstantExpressions(ASTContext &C) const; |
1267 | |
1268 | /// Determine whether this variable's value can be used in a |
1269 | /// constant expression, according to the relevant language standard, |
1270 | /// including checking whether it was initialized by a constant expression. |
1271 | bool isUsableInConstantExpressions(ASTContext &C) const; |
1272 | |
1273 | EvaluatedStmt *ensureEvaluatedStmt() const; |
1274 | |
1275 | /// Attempt to evaluate the value of the initializer attached to this |
1276 | /// declaration, and produce notes explaining why it cannot be evaluated or is |
1277 | /// not a constant expression. Returns a pointer to the value if evaluation |
1278 | /// succeeded, 0 otherwise. |
1279 | APValue *evaluateValue() const; |
1280 | APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
1281 | |
1282 | /// Return the already-evaluated value of this variable's |
1283 | /// initializer, or NULL if the value is not yet known. Returns pointer |
1284 | /// to untyped APValue if the value could not be evaluated. |
1285 | APValue *getEvaluatedValue() const; |
1286 | |
1287 | /// Evaluate the destruction of this variable to determine if it constitutes |
1288 | /// constant destruction. |
1289 | /// |
1290 | /// \pre isInitICE() |
1291 | /// \return \c true if this variable has constant destruction, \c false if |
1292 | /// not. |
1293 | bool evaluateDestruction(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; |
1294 | |
1295 | /// Determines whether it is already known whether the |
1296 | /// initializer is an integral constant expression or not. |
1297 | bool isInitKnownICE() const; |
1298 | |
1299 | /// Determines whether the initializer is an integral constant |
1300 | /// expression, or in C++11, whether the initializer is a constant |
1301 | /// expression. |
1302 | /// |
1303 | /// \pre isInitKnownICE() |
1304 | bool isInitICE() const; |
1305 | |
1306 | /// Determine whether the value of the initializer attached to this |
1307 | /// declaration is an integral constant expression. |
1308 | bool checkInitIsICE() const; |
1309 | |
1310 | void setInitStyle(InitializationStyle Style) { |
1311 | VarDeclBits.InitStyle = Style; |
1312 | } |
1313 | |
1314 | /// The style of initialization for this declaration. |
1315 | /// |
1316 | /// C-style initialization is "int x = 1;". Call-style initialization is |
1317 | /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be |
1318 | /// the expression inside the parens or a "ClassType(a,b,c)" class constructor |
1319 | /// expression for class types. List-style initialization is C++11 syntax, |
1320 | /// e.g. "int x{1};". Clients can distinguish between different forms of |
1321 | /// initialization by checking this value. In particular, "int x = {1};" is |
1322 | /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the |
1323 | /// Init expression in all three cases is an InitListExpr. |
1324 | InitializationStyle getInitStyle() const { |
1325 | return static_cast<InitializationStyle>(VarDeclBits.InitStyle); |
1326 | } |
1327 | |
1328 | /// Whether the initializer is a direct-initializer (list or call). |
1329 | bool isDirectInit() const { |
1330 | return getInitStyle() != CInit; |
1331 | } |
1332 | |
1333 | /// If this definition should pretend to be a declaration. |
1334 | bool isThisDeclarationADemotedDefinition() const { |
1335 | return isa<ParmVarDecl>(this) ? false : |
1336 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition; |
1337 | } |
1338 | |
1339 | /// This is a definition which should be demoted to a declaration. |
1340 | /// |
1341 | /// In some cases (mostly module merging) we can end up with two visible |
1342 | /// definitions one of which needs to be demoted to a declaration to keep |
1343 | /// the AST invariants. |
1344 | void demoteThisDefinitionToDeclaration() { |
1345 | assert(isThisDeclarationADefinition() && "Not a definition!")((isThisDeclarationADefinition() && "Not a definition!" ) ? static_cast<void> (0) : __assert_fail ("isThisDeclarationADefinition() && \"Not a definition!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1345, __PRETTY_FUNCTION__)); |
1346 | assert(!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!")((!isa<ParmVarDecl>(this) && "Cannot demote ParmVarDecls!" ) ? static_cast<void> (0) : __assert_fail ("!isa<ParmVarDecl>(this) && \"Cannot demote ParmVarDecls!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1346, __PRETTY_FUNCTION__)); |
1347 | NonParmVarDeclBits.IsThisDeclarationADemotedDefinition = 1; |
1348 | } |
1349 | |
1350 | /// Determine whether this variable is the exception variable in a |
1351 | /// C++ catch statememt or an Objective-C \@catch statement. |
1352 | bool isExceptionVariable() const { |
1353 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.ExceptionVar; |
1354 | } |
1355 | void setExceptionVariable(bool EV) { |
1356 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1356, __PRETTY_FUNCTION__)); |
1357 | NonParmVarDeclBits.ExceptionVar = EV; |
1358 | } |
1359 | |
1360 | /// Determine whether this local variable can be used with the named |
1361 | /// return value optimization (NRVO). |
1362 | /// |
1363 | /// The named return value optimization (NRVO) works by marking certain |
1364 | /// non-volatile local variables of class type as NRVO objects. These |
1365 | /// locals can be allocated within the return slot of their containing |
1366 | /// function, in which case there is no need to copy the object to the |
1367 | /// return slot when returning from the function. Within the function body, |
1368 | /// each return that returns the NRVO object will have this variable as its |
1369 | /// NRVO candidate. |
1370 | bool isNRVOVariable() const { |
1371 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.NRVOVariable; |
1372 | } |
1373 | void setNRVOVariable(bool NRVO) { |
1374 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1374, __PRETTY_FUNCTION__)); |
1375 | NonParmVarDeclBits.NRVOVariable = NRVO; |
1376 | } |
1377 | |
1378 | /// Determine whether this variable is the for-range-declaration in |
1379 | /// a C++0x for-range statement. |
1380 | bool isCXXForRangeDecl() const { |
1381 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.CXXForRangeDecl; |
1382 | } |
1383 | void setCXXForRangeDecl(bool FRD) { |
1384 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1384, __PRETTY_FUNCTION__)); |
1385 | NonParmVarDeclBits.CXXForRangeDecl = FRD; |
1386 | } |
1387 | |
1388 | /// Determine whether this variable is a for-loop declaration for a |
1389 | /// for-in statement in Objective-C. |
1390 | bool isObjCForDecl() const { |
1391 | return NonParmVarDeclBits.ObjCForDecl; |
1392 | } |
1393 | |
1394 | void setObjCForDecl(bool FRD) { |
1395 | NonParmVarDeclBits.ObjCForDecl = FRD; |
1396 | } |
1397 | |
1398 | /// Determine whether this variable is an ARC pseudo-__strong variable. A |
1399 | /// pseudo-__strong variable has a __strong-qualified type but does not |
1400 | /// actually retain the object written into it. Generally such variables are |
1401 | /// also 'const' for safety. There are 3 cases where this will be set, 1) if |
1402 | /// the variable is annotated with the objc_externally_retained attribute, 2) |
1403 | /// if its 'self' in a non-init method, or 3) if its the variable in an for-in |
1404 | /// loop. |
1405 | bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; } |
1406 | void setARCPseudoStrong(bool PS) { VarDeclBits.ARCPseudoStrong = PS; } |
1407 | |
1408 | /// Whether this variable is (C++1z) inline. |
1409 | bool isInline() const { |
1410 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInline; |
1411 | } |
1412 | bool isInlineSpecified() const { |
1413 | return isa<ParmVarDecl>(this) ? false |
1414 | : NonParmVarDeclBits.IsInlineSpecified; |
1415 | } |
1416 | void setInlineSpecified() { |
1417 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1417, __PRETTY_FUNCTION__)); |
1418 | NonParmVarDeclBits.IsInline = true; |
1419 | NonParmVarDeclBits.IsInlineSpecified = true; |
1420 | } |
1421 | void setImplicitlyInline() { |
1422 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1422, __PRETTY_FUNCTION__)); |
1423 | NonParmVarDeclBits.IsInline = true; |
1424 | } |
1425 | |
1426 | /// Whether this variable is (C++11) constexpr. |
1427 | bool isConstexpr() const { |
1428 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsConstexpr; |
1429 | } |
1430 | void setConstexpr(bool IC) { |
1431 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1431, __PRETTY_FUNCTION__)); |
1432 | NonParmVarDeclBits.IsConstexpr = IC; |
1433 | } |
1434 | |
1435 | /// Whether this variable is the implicit variable for a lambda init-capture. |
1436 | bool isInitCapture() const { |
1437 | return isa<ParmVarDecl>(this) ? false : NonParmVarDeclBits.IsInitCapture; |
1438 | } |
1439 | void setInitCapture(bool IC) { |
1440 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1440, __PRETTY_FUNCTION__)); |
1441 | NonParmVarDeclBits.IsInitCapture = IC; |
1442 | } |
1443 | |
1444 | /// Determine whether this variable is actually a function parameter pack or |
1445 | /// init-capture pack. |
1446 | bool isParameterPack() const; |
1447 | |
1448 | /// Whether this local extern variable declaration's previous declaration |
1449 | /// was declared in the same block scope. Only correct in C++. |
1450 | bool isPreviousDeclInSameBlockScope() const { |
1451 | return isa<ParmVarDecl>(this) |
1452 | ? false |
1453 | : NonParmVarDeclBits.PreviousDeclInSameBlockScope; |
1454 | } |
1455 | void setPreviousDeclInSameBlockScope(bool Same) { |
1456 | assert(!isa<ParmVarDecl>(this))((!isa<ParmVarDecl>(this)) ? static_cast<void> (0 ) : __assert_fail ("!isa<ParmVarDecl>(this)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1456, __PRETTY_FUNCTION__)); |
1457 | NonParmVarDeclBits.PreviousDeclInSameBlockScope = Same; |
1458 | } |
1459 | |
1460 | /// Indicates the capture is a __block variable that is captured by a block |
1461 | /// that can potentially escape (a block for which BlockDecl::doesNotEscape |
1462 | /// returns false). |
1463 | bool isEscapingByref() const; |
1464 | |
1465 | /// Indicates the capture is a __block variable that is never captured by an |
1466 | /// escaping block. |
1467 | bool isNonEscapingByref() const; |
1468 | |
1469 | void setEscapingByref() { |
1470 | NonParmVarDeclBits.EscapingByref = true; |
1471 | } |
1472 | |
1473 | /// Retrieve the variable declaration from which this variable could |
1474 | /// be instantiated, if it is an instantiation (rather than a non-template). |
1475 | VarDecl *getTemplateInstantiationPattern() const; |
1476 | |
1477 | /// If this variable is an instantiated static data member of a |
1478 | /// class template specialization, returns the templated static data member |
1479 | /// from which it was instantiated. |
1480 | VarDecl *getInstantiatedFromStaticDataMember() const; |
1481 | |
1482 | /// If this variable is an instantiation of a variable template or a |
1483 | /// static data member of a class template, determine what kind of |
1484 | /// template specialization or instantiation this is. |
1485 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
1486 | |
1487 | /// Get the template specialization kind of this variable for the purposes of |
1488 | /// template instantiation. This differs from getTemplateSpecializationKind() |
1489 | /// for an instantiation of a class-scope explicit specialization. |
1490 | TemplateSpecializationKind |
1491 | getTemplateSpecializationKindForInstantiation() const; |
1492 | |
1493 | /// If this variable is an instantiation of a variable template or a |
1494 | /// static data member of a class template, determine its point of |
1495 | /// instantiation. |
1496 | SourceLocation getPointOfInstantiation() const; |
1497 | |
1498 | /// If this variable is an instantiation of a static data member of a |
1499 | /// class template specialization, retrieves the member specialization |
1500 | /// information. |
1501 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
1502 | |
1503 | /// For a static data member that was instantiated from a static |
1504 | /// data member of a class template, set the template specialiation kind. |
1505 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
1506 | SourceLocation PointOfInstantiation = SourceLocation()); |
1507 | |
1508 | /// Specify that this variable is an instantiation of the |
1509 | /// static data member VD. |
1510 | void setInstantiationOfStaticDataMember(VarDecl *VD, |
1511 | TemplateSpecializationKind TSK); |
1512 | |
1513 | /// Retrieves the variable template that is described by this |
1514 | /// variable declaration. |
1515 | /// |
1516 | /// Every variable template is represented as a VarTemplateDecl and a |
1517 | /// VarDecl. The former contains template properties (such as |
1518 | /// the template parameter lists) while the latter contains the |
1519 | /// actual description of the template's |
1520 | /// contents. VarTemplateDecl::getTemplatedDecl() retrieves the |
1521 | /// VarDecl that from a VarTemplateDecl, while |
1522 | /// getDescribedVarTemplate() retrieves the VarTemplateDecl from |
1523 | /// a VarDecl. |
1524 | VarTemplateDecl *getDescribedVarTemplate() const; |
1525 | |
1526 | void setDescribedVarTemplate(VarTemplateDecl *Template); |
1527 | |
1528 | // Is this variable known to have a definition somewhere in the complete |
1529 | // program? This may be true even if the declaration has internal linkage and |
1530 | // has no definition within this source file. |
1531 | bool isKnownToBeDefined() const; |
1532 | |
1533 | /// Is destruction of this variable entirely suppressed? If so, the variable |
1534 | /// need not have a usable destructor at all. |
1535 | bool isNoDestroy(const ASTContext &) const; |
1536 | |
1537 | /// Would the destruction of this variable have any effect, and if so, what |
1538 | /// kind? |
1539 | QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const; |
1540 | |
1541 | // Implement isa/cast/dyncast/etc. |
1542 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1543 | static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } |
1544 | }; |
1545 | |
1546 | class ImplicitParamDecl : public VarDecl { |
1547 | void anchor() override; |
1548 | |
1549 | public: |
1550 | /// Defines the kind of the implicit parameter: is this an implicit parameter |
1551 | /// with pointer to 'this', 'self', '_cmd', virtual table pointers, captured |
1552 | /// context or something else. |
1553 | enum ImplicitParamKind : unsigned { |
1554 | /// Parameter for Objective-C 'self' argument |
1555 | ObjCSelf, |
1556 | |
1557 | /// Parameter for Objective-C '_cmd' argument |
1558 | ObjCCmd, |
1559 | |
1560 | /// Parameter for C++ 'this' argument |
1561 | CXXThis, |
1562 | |
1563 | /// Parameter for C++ virtual table pointers |
1564 | CXXVTT, |
1565 | |
1566 | /// Parameter for captured context |
1567 | CapturedContext, |
1568 | |
1569 | /// Other implicit parameter |
1570 | Other, |
1571 | }; |
1572 | |
1573 | /// Create implicit parameter. |
1574 | static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, |
1575 | SourceLocation IdLoc, IdentifierInfo *Id, |
1576 | QualType T, ImplicitParamKind ParamKind); |
1577 | static ImplicitParamDecl *Create(ASTContext &C, QualType T, |
1578 | ImplicitParamKind ParamKind); |
1579 | |
1580 | static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1581 | |
1582 | ImplicitParamDecl(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, |
1583 | IdentifierInfo *Id, QualType Type, |
1584 | ImplicitParamKind ParamKind) |
1585 | : VarDecl(ImplicitParam, C, DC, IdLoc, IdLoc, Id, Type, |
1586 | /*TInfo=*/nullptr, SC_None) { |
1587 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1588 | setImplicit(); |
1589 | } |
1590 | |
1591 | ImplicitParamDecl(ASTContext &C, QualType Type, ImplicitParamKind ParamKind) |
1592 | : VarDecl(ImplicitParam, C, /*DC=*/nullptr, SourceLocation(), |
1593 | SourceLocation(), /*Id=*/nullptr, Type, |
1594 | /*TInfo=*/nullptr, SC_None) { |
1595 | NonParmVarDeclBits.ImplicitParamKind = ParamKind; |
1596 | setImplicit(); |
1597 | } |
1598 | |
1599 | /// Returns the implicit parameter kind. |
1600 | ImplicitParamKind getParameterKind() const { |
1601 | return static_cast<ImplicitParamKind>(NonParmVarDeclBits.ImplicitParamKind); |
1602 | } |
1603 | |
1604 | // Implement isa/cast/dyncast/etc. |
1605 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1606 | static bool classofKind(Kind K) { return K == ImplicitParam; } |
1607 | }; |
1608 | |
1609 | /// Represents a parameter to a function. |
1610 | class ParmVarDecl : public VarDecl { |
1611 | public: |
1612 | enum { MaxFunctionScopeDepth = 255 }; |
1613 | enum { MaxFunctionScopeIndex = 255 }; |
1614 | |
1615 | protected: |
1616 | ParmVarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1617 | SourceLocation IdLoc, IdentifierInfo *Id, QualType T, |
1618 | TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg) |
1619 | : VarDecl(DK, C, DC, StartLoc, IdLoc, Id, T, TInfo, S) { |
1620 | assert(ParmVarDeclBits.HasInheritedDefaultArg == false)((ParmVarDeclBits.HasInheritedDefaultArg == false) ? static_cast <void> (0) : __assert_fail ("ParmVarDeclBits.HasInheritedDefaultArg == false" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1620, __PRETTY_FUNCTION__)); |
1621 | assert(ParmVarDeclBits.DefaultArgKind == DAK_None)((ParmVarDeclBits.DefaultArgKind == DAK_None) ? static_cast< void> (0) : __assert_fail ("ParmVarDeclBits.DefaultArgKind == DAK_None" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1621, __PRETTY_FUNCTION__)); |
1622 | assert(ParmVarDeclBits.IsKNRPromoted == false)((ParmVarDeclBits.IsKNRPromoted == false) ? static_cast<void > (0) : __assert_fail ("ParmVarDeclBits.IsKNRPromoted == false" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1622, __PRETTY_FUNCTION__)); |
1623 | assert(ParmVarDeclBits.IsObjCMethodParam == false)((ParmVarDeclBits.IsObjCMethodParam == false) ? static_cast< void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam == false" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1623, __PRETTY_FUNCTION__)); |
1624 | setDefaultArg(DefArg); |
1625 | } |
1626 | |
1627 | public: |
1628 | static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, |
1629 | SourceLocation StartLoc, |
1630 | SourceLocation IdLoc, IdentifierInfo *Id, |
1631 | QualType T, TypeSourceInfo *TInfo, |
1632 | StorageClass S, Expr *DefArg); |
1633 | |
1634 | static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1635 | |
1636 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
1637 | |
1638 | void setObjCMethodScopeInfo(unsigned parameterIndex) { |
1639 | ParmVarDeclBits.IsObjCMethodParam = true; |
1640 | setParameterIndex(parameterIndex); |
1641 | } |
1642 | |
1643 | void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) { |
1644 | assert(!ParmVarDeclBits.IsObjCMethodParam)((!ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void> (0) : __assert_fail ("!ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1644, __PRETTY_FUNCTION__)); |
1645 | |
1646 | ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth; |
1647 | assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? static_cast<void> (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1648, __PRETTY_FUNCTION__)) |
1648 | && "truncation!")((ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && "truncation!") ? static_cast<void> (0) : __assert_fail ("ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth && \"truncation!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1648, __PRETTY_FUNCTION__)); |
1649 | |
1650 | setParameterIndex(parameterIndex); |
1651 | } |
1652 | |
1653 | bool isObjCMethodParameter() const { |
1654 | return ParmVarDeclBits.IsObjCMethodParam; |
1655 | } |
1656 | |
1657 | unsigned getFunctionScopeDepth() const { |
1658 | if (ParmVarDeclBits.IsObjCMethodParam) return 0; |
1659 | return ParmVarDeclBits.ScopeDepthOrObjCQuals; |
1660 | } |
1661 | |
1662 | static constexpr unsigned getMaxFunctionScopeDepth() { |
1663 | return (1u << NumScopeDepthOrObjCQualsBits) - 1; |
1664 | } |
1665 | |
1666 | /// Returns the index of this parameter in its prototype or method scope. |
1667 | unsigned getFunctionScopeIndex() const { |
1668 | return getParameterIndex(); |
1669 | } |
1670 | |
1671 | ObjCDeclQualifier getObjCDeclQualifier() const { |
1672 | if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None; |
1673 | return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals); |
1674 | } |
1675 | void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { |
1676 | assert(ParmVarDeclBits.IsObjCMethodParam)((ParmVarDeclBits.IsObjCMethodParam) ? static_cast<void> (0) : __assert_fail ("ParmVarDeclBits.IsObjCMethodParam", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1676, __PRETTY_FUNCTION__)); |
1677 | ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal; |
1678 | } |
1679 | |
1680 | /// True if the value passed to this parameter must undergo |
1681 | /// K&R-style default argument promotion: |
1682 | /// |
1683 | /// C99 6.5.2.2. |
1684 | /// If the expression that denotes the called function has a type |
1685 | /// that does not include a prototype, the integer promotions are |
1686 | /// performed on each argument, and arguments that have type float |
1687 | /// are promoted to double. |
1688 | bool isKNRPromoted() const { |
1689 | return ParmVarDeclBits.IsKNRPromoted; |
1690 | } |
1691 | void setKNRPromoted(bool promoted) { |
1692 | ParmVarDeclBits.IsKNRPromoted = promoted; |
1693 | } |
1694 | |
1695 | Expr *getDefaultArg(); |
1696 | const Expr *getDefaultArg() const { |
1697 | return const_cast<ParmVarDecl *>(this)->getDefaultArg(); |
1698 | } |
1699 | |
1700 | void setDefaultArg(Expr *defarg); |
1701 | |
1702 | /// Retrieve the source range that covers the entire default |
1703 | /// argument. |
1704 | SourceRange getDefaultArgRange() const; |
1705 | void setUninstantiatedDefaultArg(Expr *arg); |
1706 | Expr *getUninstantiatedDefaultArg(); |
1707 | const Expr *getUninstantiatedDefaultArg() const { |
1708 | return const_cast<ParmVarDecl *>(this)->getUninstantiatedDefaultArg(); |
1709 | } |
1710 | |
1711 | /// Determines whether this parameter has a default argument, |
1712 | /// either parsed or not. |
1713 | bool hasDefaultArg() const; |
1714 | |
1715 | /// Determines whether this parameter has a default argument that has not |
1716 | /// yet been parsed. This will occur during the processing of a C++ class |
1717 | /// whose member functions have default arguments, e.g., |
1718 | /// @code |
1719 | /// class X { |
1720 | /// public: |
1721 | /// void f(int x = 17); // x has an unparsed default argument now |
1722 | /// }; // x has a regular default argument now |
1723 | /// @endcode |
1724 | bool hasUnparsedDefaultArg() const { |
1725 | return ParmVarDeclBits.DefaultArgKind == DAK_Unparsed; |
1726 | } |
1727 | |
1728 | bool hasUninstantiatedDefaultArg() const { |
1729 | return ParmVarDeclBits.DefaultArgKind == DAK_Uninstantiated; |
1730 | } |
1731 | |
1732 | /// Specify that this parameter has an unparsed default argument. |
1733 | /// The argument will be replaced with a real default argument via |
1734 | /// setDefaultArg when the class definition enclosing the function |
1735 | /// declaration that owns this default argument is completed. |
1736 | void setUnparsedDefaultArg() { |
1737 | ParmVarDeclBits.DefaultArgKind = DAK_Unparsed; |
1738 | } |
1739 | |
1740 | bool hasInheritedDefaultArg() const { |
1741 | return ParmVarDeclBits.HasInheritedDefaultArg; |
1742 | } |
1743 | |
1744 | void setHasInheritedDefaultArg(bool I = true) { |
1745 | ParmVarDeclBits.HasInheritedDefaultArg = I; |
1746 | } |
1747 | |
1748 | QualType getOriginalType() const; |
1749 | |
1750 | /// Sets the function declaration that owns this |
1751 | /// ParmVarDecl. Since ParmVarDecls are often created before the |
1752 | /// FunctionDecls that own them, this routine is required to update |
1753 | /// the DeclContext appropriately. |
1754 | void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } |
1755 | |
1756 | // Implement isa/cast/dyncast/etc. |
1757 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
1758 | static bool classofKind(Kind K) { return K == ParmVar; } |
1759 | |
1760 | private: |
1761 | enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 }; |
1762 | |
1763 | void setParameterIndex(unsigned parameterIndex) { |
1764 | if (parameterIndex >= ParameterIndexSentinel) { |
1765 | setParameterIndexLarge(parameterIndex); |
1766 | return; |
1767 | } |
1768 | |
1769 | ParmVarDeclBits.ParameterIndex = parameterIndex; |
1770 | assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!")((ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!") ? static_cast<void> (0) : __assert_fail ("ParmVarDeclBits.ParameterIndex == parameterIndex && \"truncation!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 1770, __PRETTY_FUNCTION__)); |
1771 | } |
1772 | unsigned getParameterIndex() const { |
1773 | unsigned d = ParmVarDeclBits.ParameterIndex; |
1774 | return d == ParameterIndexSentinel ? getParameterIndexLarge() : d; |
1775 | } |
1776 | |
1777 | void setParameterIndexLarge(unsigned parameterIndex); |
1778 | unsigned getParameterIndexLarge() const; |
1779 | }; |
1780 | |
1781 | enum class MultiVersionKind { |
1782 | None, |
1783 | Target, |
1784 | CPUSpecific, |
1785 | CPUDispatch |
1786 | }; |
1787 | |
1788 | /// Represents a function declaration or definition. |
1789 | /// |
1790 | /// Since a given function can be declared several times in a program, |
1791 | /// there may be several FunctionDecls that correspond to that |
1792 | /// function. Only one of those FunctionDecls will be found when |
1793 | /// traversing the list of declarations in the context of the |
1794 | /// FunctionDecl (e.g., the translation unit); this FunctionDecl |
1795 | /// contains all of the information known about the function. Other, |
1796 | /// previous declarations of the function are available via the |
1797 | /// getPreviousDecl() chain. |
1798 | class FunctionDecl : public DeclaratorDecl, |
1799 | public DeclContext, |
1800 | public Redeclarable<FunctionDecl> { |
1801 | // This class stores some data in DeclContext::FunctionDeclBits |
1802 | // to save some space. Use the provided accessors to access it. |
1803 | public: |
1804 | /// The kind of templated function a FunctionDecl can be. |
1805 | enum TemplatedKind { |
1806 | // Not templated. |
1807 | TK_NonTemplate, |
1808 | // The pattern in a function template declaration. |
1809 | TK_FunctionTemplate, |
1810 | // A non-template function that is an instantiation or explicit |
1811 | // specialization of a member of a templated class. |
1812 | TK_MemberSpecialization, |
1813 | // An instantiation or explicit specialization of a function template. |
1814 | // Note: this might have been instantiated from a templated class if it |
1815 | // is a class-scope explicit specialization. |
1816 | TK_FunctionTemplateSpecialization, |
1817 | // A function template specialization that hasn't yet been resolved to a |
1818 | // particular specialized function template. |
1819 | TK_DependentFunctionTemplateSpecialization |
1820 | }; |
1821 | |
1822 | /// Stashed information about a defaulted function definition whose body has |
1823 | /// not yet been lazily generated. |
1824 | class DefaultedFunctionInfo final |
1825 | : llvm::TrailingObjects<DefaultedFunctionInfo, DeclAccessPair> { |
1826 | friend TrailingObjects; |
1827 | unsigned NumLookups; |
1828 | |
1829 | public: |
1830 | static DefaultedFunctionInfo *Create(ASTContext &Context, |
1831 | ArrayRef<DeclAccessPair> Lookups); |
1832 | /// Get the unqualified lookup results that should be used in this |
1833 | /// defaulted function definition. |
1834 | ArrayRef<DeclAccessPair> getUnqualifiedLookups() const { |
1835 | return {getTrailingObjects<DeclAccessPair>(), NumLookups}; |
1836 | } |
1837 | }; |
1838 | |
1839 | private: |
1840 | /// A new[]'d array of pointers to VarDecls for the formal |
1841 | /// parameters of this function. This is null if a prototype or if there are |
1842 | /// no formals. |
1843 | ParmVarDecl **ParamInfo = nullptr; |
1844 | |
1845 | /// The active member of this union is determined by |
1846 | /// FunctionDeclBits.HasDefaultedFunctionInfo. |
1847 | union { |
1848 | /// The body of the function. |
1849 | LazyDeclStmtPtr Body; |
1850 | /// Information about a future defaulted function definition. |
1851 | DefaultedFunctionInfo *DefaultedInfo; |
1852 | }; |
1853 | |
1854 | unsigned ODRHash; |
1855 | |
1856 | /// End part of this FunctionDecl's source range. |
1857 | /// |
1858 | /// We could compute the full range in getSourceRange(). However, when we're |
1859 | /// dealing with a function definition deserialized from a PCH/AST file, |
1860 | /// we can only compute the full range once the function body has been |
1861 | /// de-serialized, so it's far better to have the (sometimes-redundant) |
1862 | /// EndRangeLoc. |
1863 | SourceLocation EndRangeLoc; |
1864 | |
1865 | /// The template or declaration that this declaration |
1866 | /// describes or was instantiated from, respectively. |
1867 | /// |
1868 | /// For non-templates, this value will be NULL. For function |
1869 | /// declarations that describe a function template, this will be a |
1870 | /// pointer to a FunctionTemplateDecl. For member functions |
1871 | /// of class template specializations, this will be a MemberSpecializationInfo |
1872 | /// pointer containing information about the specialization. |
1873 | /// For function template specializations, this will be a |
1874 | /// FunctionTemplateSpecializationInfo, which contains information about |
1875 | /// the template being specialized and the template arguments involved in |
1876 | /// that specialization. |
1877 | llvm::PointerUnion<FunctionTemplateDecl *, |
1878 | MemberSpecializationInfo *, |
1879 | FunctionTemplateSpecializationInfo *, |
1880 | DependentFunctionTemplateSpecializationInfo *> |
1881 | TemplateOrSpecialization; |
1882 | |
1883 | /// Provides source/type location info for the declaration name embedded in |
1884 | /// the DeclaratorDecl base class. |
1885 | DeclarationNameLoc DNLoc; |
1886 | |
1887 | /// Specify that this function declaration is actually a function |
1888 | /// template specialization. |
1889 | /// |
1890 | /// \param C the ASTContext. |
1891 | /// |
1892 | /// \param Template the function template that this function template |
1893 | /// specialization specializes. |
1894 | /// |
1895 | /// \param TemplateArgs the template arguments that produced this |
1896 | /// function template specialization from the template. |
1897 | /// |
1898 | /// \param InsertPos If non-NULL, the position in the function template |
1899 | /// specialization set where the function template specialization data will |
1900 | /// be inserted. |
1901 | /// |
1902 | /// \param TSK the kind of template specialization this is. |
1903 | /// |
1904 | /// \param TemplateArgsAsWritten location info of template arguments. |
1905 | /// |
1906 | /// \param PointOfInstantiation point at which the function template |
1907 | /// specialization was first instantiated. |
1908 | void setFunctionTemplateSpecialization(ASTContext &C, |
1909 | FunctionTemplateDecl *Template, |
1910 | const TemplateArgumentList *TemplateArgs, |
1911 | void *InsertPos, |
1912 | TemplateSpecializationKind TSK, |
1913 | const TemplateArgumentListInfo *TemplateArgsAsWritten, |
1914 | SourceLocation PointOfInstantiation); |
1915 | |
1916 | /// Specify that this record is an instantiation of the |
1917 | /// member function FD. |
1918 | void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, |
1919 | TemplateSpecializationKind TSK); |
1920 | |
1921 | void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo); |
1922 | |
1923 | // This is unfortunately needed because ASTDeclWriter::VisitFunctionDecl |
1924 | // need to access this bit but we want to avoid making ASTDeclWriter |
1925 | // a friend of FunctionDeclBitfields just for this. |
1926 | bool isDeletedBit() const { return FunctionDeclBits.IsDeleted; } |
1927 | |
1928 | /// Whether an ODRHash has been stored. |
1929 | bool hasODRHash() const { return FunctionDeclBits.HasODRHash; } |
1930 | |
1931 | /// State that an ODRHash has been stored. |
1932 | void setHasODRHash(bool B = true) { FunctionDeclBits.HasODRHash = B; } |
1933 | |
1934 | protected: |
1935 | FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1936 | const DeclarationNameInfo &NameInfo, QualType T, |
1937 | TypeSourceInfo *TInfo, StorageClass S, bool isInlineSpecified, |
1938 | ConstexprSpecKind ConstexprKind, |
1939 | Expr *TrailingRequiresClause = nullptr); |
1940 | |
1941 | using redeclarable_base = Redeclarable<FunctionDecl>; |
1942 | |
1943 | FunctionDecl *getNextRedeclarationImpl() override { |
1944 | return getNextRedeclaration(); |
1945 | } |
1946 | |
1947 | FunctionDecl *getPreviousDeclImpl() override { |
1948 | return getPreviousDecl(); |
1949 | } |
1950 | |
1951 | FunctionDecl *getMostRecentDeclImpl() override { |
1952 | return getMostRecentDecl(); |
1953 | } |
1954 | |
1955 | public: |
1956 | friend class ASTDeclReader; |
1957 | friend class ASTDeclWriter; |
1958 | |
1959 | using redecl_range = redeclarable_base::redecl_range; |
1960 | using redecl_iterator = redeclarable_base::redecl_iterator; |
1961 | |
1962 | using redeclarable_base::redecls_begin; |
1963 | using redeclarable_base::redecls_end; |
1964 | using redeclarable_base::redecls; |
1965 | using redeclarable_base::getPreviousDecl; |
1966 | using redeclarable_base::getMostRecentDecl; |
1967 | using redeclarable_base::isFirstDecl; |
1968 | |
1969 | static FunctionDecl * |
1970 | Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
1971 | SourceLocation NLoc, DeclarationName N, QualType T, |
1972 | TypeSourceInfo *TInfo, StorageClass SC, bool isInlineSpecified = false, |
1973 | bool hasWrittenPrototype = true, |
1974 | ConstexprSpecKind ConstexprKind = CSK_unspecified, |
1975 | Expr *TrailingRequiresClause = nullptr) { |
1976 | DeclarationNameInfo NameInfo(N, NLoc); |
1977 | return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, SC, |
1978 | isInlineSpecified, hasWrittenPrototype, |
1979 | ConstexprKind, TrailingRequiresClause); |
1980 | } |
1981 | |
1982 | static FunctionDecl *Create(ASTContext &C, DeclContext *DC, |
1983 | SourceLocation StartLoc, |
1984 | const DeclarationNameInfo &NameInfo, QualType T, |
1985 | TypeSourceInfo *TInfo, StorageClass SC, |
1986 | bool isInlineSpecified, bool hasWrittenPrototype, |
1987 | ConstexprSpecKind ConstexprKind, |
1988 | Expr *TrailingRequiresClause); |
1989 | |
1990 | static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
1991 | |
1992 | DeclarationNameInfo getNameInfo() const { |
1993 | return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); |
1994 | } |
1995 | |
1996 | void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, |
1997 | bool Qualified) const override; |
1998 | |
1999 | void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } |
2000 | |
2001 | /// Returns the location of the ellipsis of a variadic function. |
2002 | SourceLocation getEllipsisLoc() const { |
2003 | const auto *FPT = getType()->getAs<FunctionProtoType>(); |
2004 | if (FPT && FPT->isVariadic()) |
2005 | return FPT->getEllipsisLoc(); |
2006 | return SourceLocation(); |
2007 | } |
2008 | |
2009 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2010 | |
2011 | // Function definitions. |
2012 | // |
2013 | // A function declaration may be: |
2014 | // - a non defining declaration, |
2015 | // - a definition. A function may be defined because: |
2016 | // - it has a body, or will have it in the case of late parsing. |
2017 | // - it has an uninstantiated body. The body does not exist because the |
2018 | // function is not used yet, but the declaration is considered a |
2019 | // definition and does not allow other definition of this function. |
2020 | // - it does not have a user specified body, but it does not allow |
2021 | // redefinition, because it is deleted/defaulted or is defined through |
2022 | // some other mechanism (alias, ifunc). |
2023 | |
2024 | /// Returns true if the function has a body. |
2025 | /// |
2026 | /// The function body might be in any of the (re-)declarations of this |
2027 | /// function. The variant that accepts a FunctionDecl pointer will set that |
2028 | /// function declaration to the actual declaration containing the body (if |
2029 | /// there is one). |
2030 | bool hasBody(const FunctionDecl *&Definition) const; |
2031 | |
2032 | bool hasBody() const override { |
2033 | const FunctionDecl* Definition; |
2034 | return hasBody(Definition); |
2035 | } |
2036 | |
2037 | /// Returns whether the function has a trivial body that does not require any |
2038 | /// specific codegen. |
2039 | bool hasTrivialBody() const; |
2040 | |
2041 | /// Returns true if the function has a definition that does not need to be |
2042 | /// instantiated. |
2043 | /// |
2044 | /// The variant that accepts a FunctionDecl pointer will set that function |
2045 | /// declaration to the declaration that is a definition (if there is one). |
2046 | bool isDefined(const FunctionDecl *&Definition) const; |
2047 | |
2048 | bool isDefined() const { |
2049 | const FunctionDecl* Definition; |
2050 | return isDefined(Definition); |
2051 | } |
2052 | |
2053 | /// Get the definition for this declaration. |
2054 | FunctionDecl *getDefinition() { |
2055 | const FunctionDecl *Definition; |
2056 | if (isDefined(Definition)) |
2057 | return const_cast<FunctionDecl *>(Definition); |
2058 | return nullptr; |
2059 | } |
2060 | const FunctionDecl *getDefinition() const { |
2061 | return const_cast<FunctionDecl *>(this)->getDefinition(); |
2062 | } |
2063 | |
2064 | /// Retrieve the body (definition) of the function. The function body might be |
2065 | /// in any of the (re-)declarations of this function. The variant that accepts |
2066 | /// a FunctionDecl pointer will set that function declaration to the actual |
2067 | /// declaration containing the body (if there is one). |
2068 | /// NOTE: For checking if there is a body, use hasBody() instead, to avoid |
2069 | /// unnecessary AST de-serialization of the body. |
2070 | Stmt *getBody(const FunctionDecl *&Definition) const; |
2071 | |
2072 | Stmt *getBody() const override { |
2073 | const FunctionDecl* Definition; |
2074 | return getBody(Definition); |
2075 | } |
2076 | |
2077 | /// Returns whether this specific declaration of the function is also a |
2078 | /// definition that does not contain uninstantiated body. |
2079 | /// |
2080 | /// This does not determine whether the function has been defined (e.g., in a |
2081 | /// previous definition); for that information, use isDefined. |
2082 | /// |
2083 | /// Note: the function declaration does not become a definition until the |
2084 | /// parser reaches the definition, if called before, this function will return |
2085 | /// `false`. |
2086 | bool isThisDeclarationADefinition() const { |
2087 | return isDeletedAsWritten() || isDefaulted() || |
2088 | doesThisDeclarationHaveABody() || hasSkippedBody() || |
2089 | willHaveBody() || hasDefiningAttr(); |
2090 | } |
2091 | |
2092 | /// Returns whether this specific declaration of the function has a body. |
2093 | bool doesThisDeclarationHaveABody() const { |
2094 | return (!FunctionDeclBits.HasDefaultedFunctionInfo && Body) || |
2095 | isLateTemplateParsed(); |
2096 | } |
2097 | |
2098 | void setBody(Stmt *B); |
2099 | void setLazyBody(uint64_t Offset) { |
2100 | FunctionDeclBits.HasDefaultedFunctionInfo = false; |
2101 | Body = LazyDeclStmtPtr(Offset); |
2102 | } |
2103 | |
2104 | void setDefaultedFunctionInfo(DefaultedFunctionInfo *Info); |
2105 | DefaultedFunctionInfo *getDefaultedFunctionInfo() const; |
2106 | |
2107 | /// Whether this function is variadic. |
2108 | bool isVariadic() const; |
2109 | |
2110 | /// Whether this function is marked as virtual explicitly. |
2111 | bool isVirtualAsWritten() const { |
2112 | return FunctionDeclBits.IsVirtualAsWritten; |
2113 | } |
2114 | |
2115 | /// State that this function is marked as virtual explicitly. |
2116 | void setVirtualAsWritten(bool V) { FunctionDeclBits.IsVirtualAsWritten = V; } |
2117 | |
2118 | /// Whether this virtual function is pure, i.e. makes the containing class |
2119 | /// abstract. |
2120 | bool isPure() const { return FunctionDeclBits.IsPure; } |
2121 | void setPure(bool P = true); |
2122 | |
2123 | /// Whether this templated function will be late parsed. |
2124 | bool isLateTemplateParsed() const { |
2125 | return FunctionDeclBits.IsLateTemplateParsed; |
2126 | } |
2127 | |
2128 | /// State that this templated function will be late parsed. |
2129 | void setLateTemplateParsed(bool ILT = true) { |
2130 | FunctionDeclBits.IsLateTemplateParsed = ILT; |
2131 | } |
2132 | |
2133 | /// Whether this function is "trivial" in some specialized C++ senses. |
2134 | /// Can only be true for default constructors, copy constructors, |
2135 | /// copy assignment operators, and destructors. Not meaningful until |
2136 | /// the class has been fully built by Sema. |
2137 | bool isTrivial() const { return FunctionDeclBits.IsTrivial; } |
2138 | void setTrivial(bool IT) { FunctionDeclBits.IsTrivial = IT; } |
2139 | |
2140 | bool isTrivialForCall() const { return FunctionDeclBits.IsTrivialForCall; } |
2141 | void setTrivialForCall(bool IT) { FunctionDeclBits.IsTrivialForCall = IT; } |
2142 | |
2143 | /// Whether this function is defaulted. Valid for e.g. |
2144 | /// special member functions, defaulted comparisions (not methods!). |
2145 | bool isDefaulted() const { return FunctionDeclBits.IsDefaulted; } |
2146 | void setDefaulted(bool D = true) { FunctionDeclBits.IsDefaulted = D; } |
2147 | |
2148 | /// Whether this function is explicitly defaulted. |
2149 | bool isExplicitlyDefaulted() const { |
2150 | return FunctionDeclBits.IsExplicitlyDefaulted; |
2151 | } |
2152 | |
2153 | /// State that this function is explicitly defaulted. |
2154 | void setExplicitlyDefaulted(bool ED = true) { |
2155 | FunctionDeclBits.IsExplicitlyDefaulted = ED; |
2156 | } |
2157 | |
2158 | /// True if this method is user-declared and was not |
2159 | /// deleted or defaulted on its first declaration. |
2160 | bool isUserProvided() const { |
2161 | auto *DeclAsWritten = this; |
2162 | if (FunctionDecl *Pattern = getTemplateInstantiationPattern()) |
2163 | DeclAsWritten = Pattern; |
2164 | return !(DeclAsWritten->isDeleted() || |
2165 | DeclAsWritten->getCanonicalDecl()->isDefaulted()); |
2166 | } |
2167 | |
2168 | /// Whether falling off this function implicitly returns null/zero. |
2169 | /// If a more specific implicit return value is required, front-ends |
2170 | /// should synthesize the appropriate return statements. |
2171 | bool hasImplicitReturnZero() const { |
2172 | return FunctionDeclBits.HasImplicitReturnZero; |
2173 | } |
2174 | |
2175 | /// State that falling off this function implicitly returns null/zero. |
2176 | /// If a more specific implicit return value is required, front-ends |
2177 | /// should synthesize the appropriate return statements. |
2178 | void setHasImplicitReturnZero(bool IRZ) { |
2179 | FunctionDeclBits.HasImplicitReturnZero = IRZ; |
2180 | } |
2181 | |
2182 | /// Whether this function has a prototype, either because one |
2183 | /// was explicitly written or because it was "inherited" by merging |
2184 | /// a declaration without a prototype with a declaration that has a |
2185 | /// prototype. |
2186 | bool hasPrototype() const { |
2187 | return hasWrittenPrototype() || hasInheritedPrototype(); |
2188 | } |
2189 | |
2190 | /// Whether this function has a written prototype. |
2191 | bool hasWrittenPrototype() const { |
2192 | return FunctionDeclBits.HasWrittenPrototype; |
2193 | } |
2194 | |
2195 | /// State that this function has a written prototype. |
2196 | void setHasWrittenPrototype(bool P = true) { |
2197 | FunctionDeclBits.HasWrittenPrototype = P; |
2198 | } |
2199 | |
2200 | /// Whether this function inherited its prototype from a |
2201 | /// previous declaration. |
2202 | bool hasInheritedPrototype() const { |
2203 | return FunctionDeclBits.HasInheritedPrototype; |
2204 | } |
2205 | |
2206 | /// State that this function inherited its prototype from a |
2207 | /// previous declaration. |
2208 | void setHasInheritedPrototype(bool P = true) { |
2209 | FunctionDeclBits.HasInheritedPrototype = P; |
2210 | } |
2211 | |
2212 | /// Whether this is a (C++11) constexpr function or constexpr constructor. |
2213 | bool isConstexpr() const { |
2214 | return FunctionDeclBits.ConstexprKind != CSK_unspecified; |
2215 | } |
2216 | void setConstexprKind(ConstexprSpecKind CSK) { |
2217 | FunctionDeclBits.ConstexprKind = CSK; |
2218 | } |
2219 | ConstexprSpecKind getConstexprKind() const { |
2220 | return static_cast<ConstexprSpecKind>(FunctionDeclBits.ConstexprKind); |
2221 | } |
2222 | bool isConstexprSpecified() const { |
2223 | return FunctionDeclBits.ConstexprKind == CSK_constexpr; |
2224 | } |
2225 | bool isConsteval() const { |
2226 | return FunctionDeclBits.ConstexprKind == CSK_consteval; |
2227 | } |
2228 | |
2229 | /// Whether the instantiation of this function is pending. |
2230 | /// This bit is set when the decision to instantiate this function is made |
2231 | /// and unset if and when the function body is created. That leaves out |
2232 | /// cases where instantiation did not happen because the template definition |
2233 | /// was not seen in this TU. This bit remains set in those cases, under the |
2234 | /// assumption that the instantiation will happen in some other TU. |
2235 | bool instantiationIsPending() const { |
2236 | return FunctionDeclBits.InstantiationIsPending; |
2237 | } |
2238 | |
2239 | /// State that the instantiation of this function is pending. |
2240 | /// (see instantiationIsPending) |
2241 | void setInstantiationIsPending(bool IC) { |
2242 | FunctionDeclBits.InstantiationIsPending = IC; |
2243 | } |
2244 | |
2245 | /// Indicates the function uses __try. |
2246 | bool usesSEHTry() const { return FunctionDeclBits.UsesSEHTry; } |
2247 | void setUsesSEHTry(bool UST) { FunctionDeclBits.UsesSEHTry = UST; } |
2248 | |
2249 | /// Indicates the function uses Floating Point constrained intrinsics |
2250 | bool usesFPIntrin() const { return FunctionDeclBits.UsesFPIntrin; } |
2251 | void setUsesFPIntrin(bool Val) { FunctionDeclBits.UsesFPIntrin = Val; } |
2252 | |
2253 | /// Whether this function has been deleted. |
2254 | /// |
2255 | /// A function that is "deleted" (via the C++0x "= delete" syntax) |
2256 | /// acts like a normal function, except that it cannot actually be |
2257 | /// called or have its address taken. Deleted functions are |
2258 | /// typically used in C++ overload resolution to attract arguments |
2259 | /// whose type or lvalue/rvalue-ness would permit the use of a |
2260 | /// different overload that would behave incorrectly. For example, |
2261 | /// one might use deleted functions to ban implicit conversion from |
2262 | /// a floating-point number to an Integer type: |
2263 | /// |
2264 | /// @code |
2265 | /// struct Integer { |
2266 | /// Integer(long); // construct from a long |
2267 | /// Integer(double) = delete; // no construction from float or double |
2268 | /// Integer(long double) = delete; // no construction from long double |
2269 | /// }; |
2270 | /// @endcode |
2271 | // If a function is deleted, its first declaration must be. |
2272 | bool isDeleted() const { |
2273 | return getCanonicalDecl()->FunctionDeclBits.IsDeleted; |
2274 | } |
2275 | |
2276 | bool isDeletedAsWritten() const { |
2277 | return FunctionDeclBits.IsDeleted && !isDefaulted(); |
2278 | } |
2279 | |
2280 | void setDeletedAsWritten(bool D = true) { FunctionDeclBits.IsDeleted = D; } |
2281 | |
2282 | /// Determines whether this function is "main", which is the |
2283 | /// entry point into an executable program. |
2284 | bool isMain() const; |
2285 | |
2286 | /// Determines whether this function is a MSVCRT user defined entry |
2287 | /// point. |
2288 | bool isMSVCRTEntryPoint() const; |
2289 | |
2290 | /// Determines whether this operator new or delete is one |
2291 | /// of the reserved global placement operators: |
2292 | /// void *operator new(size_t, void *); |
2293 | /// void *operator new[](size_t, void *); |
2294 | /// void operator delete(void *, void *); |
2295 | /// void operator delete[](void *, void *); |
2296 | /// These functions have special behavior under [new.delete.placement]: |
2297 | /// These functions are reserved, a C++ program may not define |
2298 | /// functions that displace the versions in the Standard C++ library. |
2299 | /// The provisions of [basic.stc.dynamic] do not apply to these |
2300 | /// reserved placement forms of operator new and operator delete. |
2301 | /// |
2302 | /// This function must be an allocation or deallocation function. |
2303 | bool isReservedGlobalPlacementOperator() const; |
2304 | |
2305 | /// Determines whether this function is one of the replaceable |
2306 | /// global allocation functions: |
2307 | /// void *operator new(size_t); |
2308 | /// void *operator new(size_t, const std::nothrow_t &) noexcept; |
2309 | /// void *operator new[](size_t); |
2310 | /// void *operator new[](size_t, const std::nothrow_t &) noexcept; |
2311 | /// void operator delete(void *) noexcept; |
2312 | /// void operator delete(void *, std::size_t) noexcept; [C++1y] |
2313 | /// void operator delete(void *, const std::nothrow_t &) noexcept; |
2314 | /// void operator delete[](void *) noexcept; |
2315 | /// void operator delete[](void *, std::size_t) noexcept; [C++1y] |
2316 | /// void operator delete[](void *, const std::nothrow_t &) noexcept; |
2317 | /// These functions have special behavior under C++1y [expr.new]: |
2318 | /// An implementation is allowed to omit a call to a replaceable global |
2319 | /// allocation function. [...] |
2320 | /// |
2321 | /// If this function is an aligned allocation/deallocation function, return |
2322 | /// the parameter number of the requested alignment through AlignmentParam. |
2323 | /// |
2324 | /// If this function is an allocation/deallocation function that takes |
2325 | /// the `std::nothrow_t` tag, return true through IsNothrow, |
2326 | bool isReplaceableGlobalAllocationFunction( |
2327 | Optional<unsigned> *AlignmentParam = nullptr, |
2328 | bool *IsNothrow = nullptr) const; |
2329 | |
2330 | /// Determine if this function provides an inline implementation of a builtin. |
2331 | bool isInlineBuiltinDeclaration() const; |
2332 | |
2333 | /// Determine whether this is a destroying operator delete. |
2334 | bool isDestroyingOperatorDelete() const; |
2335 | |
2336 | /// Compute the language linkage. |
2337 | LanguageLinkage getLanguageLinkage() const; |
2338 | |
2339 | /// Determines whether this function is a function with |
2340 | /// external, C linkage. |
2341 | bool isExternC() const; |
2342 | |
2343 | /// Determines whether this function's context is, or is nested within, |
2344 | /// a C++ extern "C" linkage spec. |
2345 | bool isInExternCContext() const; |
2346 | |
2347 | /// Determines whether this function's context is, or is nested within, |
2348 | /// a C++ extern "C++" linkage spec. |
2349 | bool isInExternCXXContext() const; |
2350 | |
2351 | /// Determines whether this is a global function. |
2352 | bool isGlobal() const; |
2353 | |
2354 | /// Determines whether this function is known to be 'noreturn', through |
2355 | /// an attribute on its declaration or its type. |
2356 | bool isNoReturn() const; |
2357 | |
2358 | /// True if the function was a definition but its body was skipped. |
2359 | bool hasSkippedBody() const { return FunctionDeclBits.HasSkippedBody; } |
2360 | void setHasSkippedBody(bool Skipped = true) { |
2361 | FunctionDeclBits.HasSkippedBody = Skipped; |
2362 | } |
2363 | |
2364 | /// True if this function will eventually have a body, once it's fully parsed. |
2365 | bool willHaveBody() const { return FunctionDeclBits.WillHaveBody; } |
2366 | void setWillHaveBody(bool V = true) { FunctionDeclBits.WillHaveBody = V; } |
2367 | |
2368 | /// True if this function is considered a multiversioned function. |
2369 | bool isMultiVersion() const { |
2370 | return getCanonicalDecl()->FunctionDeclBits.IsMultiVersion; |
2371 | } |
2372 | |
2373 | /// Sets the multiversion state for this declaration and all of its |
2374 | /// redeclarations. |
2375 | void setIsMultiVersion(bool V = true) { |
2376 | getCanonicalDecl()->FunctionDeclBits.IsMultiVersion = V; |
2377 | } |
2378 | |
2379 | /// Gets the kind of multiversioning attribute this declaration has. Note that |
2380 | /// this can return a value even if the function is not multiversion, such as |
2381 | /// the case of 'target'. |
2382 | MultiVersionKind getMultiVersionKind() const; |
2383 | |
2384 | |
2385 | /// True if this function is a multiversioned dispatch function as a part of |
2386 | /// the cpu_specific/cpu_dispatch functionality. |
2387 | bool isCPUDispatchMultiVersion() const; |
2388 | /// True if this function is a multiversioned processor specific function as a |
2389 | /// part of the cpu_specific/cpu_dispatch functionality. |
2390 | bool isCPUSpecificMultiVersion() const; |
2391 | |
2392 | /// True if this function is a multiversioned dispatch function as a part of |
2393 | /// the target functionality. |
2394 | bool isTargetMultiVersion() const; |
2395 | |
2396 | /// \brief Get the associated-constraints of this function declaration. |
2397 | /// Currently, this will either be a vector of size 1 containing the |
2398 | /// trailing-requires-clause or an empty vector. |
2399 | /// |
2400 | /// Use this instead of getTrailingRequiresClause for concepts APIs that |
2401 | /// accept an ArrayRef of constraint expressions. |
2402 | void getAssociatedConstraints(SmallVectorImpl<const Expr *> &AC) const { |
2403 | if (auto *TRC = getTrailingRequiresClause()) |
2404 | AC.push_back(TRC); |
2405 | } |
2406 | |
2407 | void setPreviousDeclaration(FunctionDecl * PrevDecl); |
2408 | |
2409 | FunctionDecl *getCanonicalDecl() override; |
2410 | const FunctionDecl *getCanonicalDecl() const { |
2411 | return const_cast<FunctionDecl*>(this)->getCanonicalDecl(); |
2412 | } |
2413 | |
2414 | unsigned getBuiltinID(bool ConsiderWrapperFunctions = false) const; |
2415 | |
2416 | // ArrayRef interface to parameters. |
2417 | ArrayRef<ParmVarDecl *> parameters() const { |
2418 | return {ParamInfo, getNumParams()}; |
2419 | } |
2420 | MutableArrayRef<ParmVarDecl *> parameters() { |
2421 | return {ParamInfo, getNumParams()}; |
2422 | } |
2423 | |
2424 | // Iterator access to formal parameters. |
2425 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
2426 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
2427 | |
2428 | bool param_empty() const { return parameters().empty(); } |
2429 | param_iterator param_begin() { return parameters().begin(); } |
2430 | param_iterator param_end() { return parameters().end(); } |
2431 | param_const_iterator param_begin() const { return parameters().begin(); } |
2432 | param_const_iterator param_end() const { return parameters().end(); } |
2433 | size_t param_size() const { return parameters().size(); } |
2434 | |
2435 | /// Return the number of parameters this function must have based on its |
2436 | /// FunctionType. This is the length of the ParamInfo array after it has been |
2437 | /// created. |
2438 | unsigned getNumParams() const; |
2439 | |
2440 | const ParmVarDecl *getParamDecl(unsigned i) const { |
2441 | assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast <void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 2441, __PRETTY_FUNCTION__)); |
2442 | return ParamInfo[i]; |
2443 | } |
2444 | ParmVarDecl *getParamDecl(unsigned i) { |
2445 | assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast <void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 2445, __PRETTY_FUNCTION__)); |
2446 | return ParamInfo[i]; |
2447 | } |
2448 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { |
2449 | setParams(getASTContext(), NewParamInfo); |
2450 | } |
2451 | |
2452 | /// Returns the minimum number of arguments needed to call this function. This |
2453 | /// may be fewer than the number of function parameters, if some of the |
2454 | /// parameters have default arguments (in C++). |
2455 | unsigned getMinRequiredArguments() const; |
2456 | |
2457 | /// Determine whether this function has a single parameter, or multiple |
2458 | /// parameters where all but the first have default arguments. |
2459 | /// |
2460 | /// This notion is used in the definition of copy/move constructors and |
2461 | /// initializer list constructors. Note that, unlike getMinRequiredArguments, |
2462 | /// parameter packs are not treated specially here. |
2463 | bool hasOneParamOrDefaultArgs() const; |
2464 | |
2465 | /// Find the source location information for how the type of this function |
2466 | /// was written. May be absent (for example if the function was declared via |
2467 | /// a typedef) and may contain a different type from that of the function |
2468 | /// (for example if the function type was adjusted by an attribute). |
2469 | FunctionTypeLoc getFunctionTypeLoc() const; |
2470 | |
2471 | QualType getReturnType() const { |
2472 | return getType()->castAs<FunctionType>()->getReturnType(); |
2473 | } |
2474 | |
2475 | /// Attempt to compute an informative source range covering the |
2476 | /// function return type. This may omit qualifiers and other information with |
2477 | /// limited representation in the AST. |
2478 | SourceRange getReturnTypeSourceRange() const; |
2479 | |
2480 | /// Attempt to compute an informative source range covering the |
2481 | /// function parameters, including the ellipsis of a variadic function. |
2482 | /// The source range excludes the parentheses, and is invalid if there are |
2483 | /// no parameters and no ellipsis. |
2484 | SourceRange getParametersSourceRange() const; |
2485 | |
2486 | /// Get the declared return type, which may differ from the actual return |
2487 | /// type if the return type is deduced. |
2488 | QualType getDeclaredReturnType() const { |
2489 | auto *TSI = getTypeSourceInfo(); |
2490 | QualType T = TSI ? TSI->getType() : getType(); |
2491 | return T->castAs<FunctionType>()->getReturnType(); |
2492 | } |
2493 | |
2494 | /// Gets the ExceptionSpecificationType as declared. |
2495 | ExceptionSpecificationType getExceptionSpecType() const { |
2496 | auto *TSI = getTypeSourceInfo(); |
2497 | QualType T = TSI ? TSI->getType() : getType(); |
2498 | const auto *FPT = T->getAs<FunctionProtoType>(); |
2499 | return FPT ? FPT->getExceptionSpecType() : EST_None; |
2500 | } |
2501 | |
2502 | /// Attempt to compute an informative source range covering the |
2503 | /// function exception specification, if any. |
2504 | SourceRange getExceptionSpecSourceRange() const; |
2505 | |
2506 | /// Determine the type of an expression that calls this function. |
2507 | QualType getCallResultType() const { |
2508 | return getType()->castAs<FunctionType>()->getCallResultType( |
2509 | getASTContext()); |
2510 | } |
2511 | |
2512 | /// Returns the storage class as written in the source. For the |
2513 | /// computed linkage of symbol, see getLinkage. |
2514 | StorageClass getStorageClass() const { |
2515 | return static_cast<StorageClass>(FunctionDeclBits.SClass); |
2516 | } |
2517 | |
2518 | /// Sets the storage class as written in the source. |
2519 | void setStorageClass(StorageClass SClass) { |
2520 | FunctionDeclBits.SClass = SClass; |
2521 | } |
2522 | |
2523 | /// Determine whether the "inline" keyword was specified for this |
2524 | /// function. |
2525 | bool isInlineSpecified() const { return FunctionDeclBits.IsInlineSpecified; } |
2526 | |
2527 | /// Set whether the "inline" keyword was specified for this function. |
2528 | void setInlineSpecified(bool I) { |
2529 | FunctionDeclBits.IsInlineSpecified = I; |
2530 | FunctionDeclBits.IsInline = I; |
2531 | } |
2532 | |
2533 | /// Flag that this function is implicitly inline. |
2534 | void setImplicitlyInline(bool I = true) { FunctionDeclBits.IsInline = I; } |
2535 | |
2536 | /// Determine whether this function should be inlined, because it is |
2537 | /// either marked "inline" or "constexpr" or is a member function of a class |
2538 | /// that was defined in the class body. |
2539 | bool isInlined() const { return FunctionDeclBits.IsInline; } |
2540 | |
2541 | bool isInlineDefinitionExternallyVisible() const; |
2542 | |
2543 | bool isMSExternInline() const; |
2544 | |
2545 | bool doesDeclarationForceExternallyVisibleDefinition() const; |
2546 | |
2547 | bool isStatic() const { return getStorageClass() == SC_Static; } |
2548 | |
2549 | /// Whether this function declaration represents an C++ overloaded |
2550 | /// operator, e.g., "operator+". |
2551 | bool isOverloadedOperator() const { |
2552 | return getOverloadedOperator() != OO_None; |
2553 | } |
2554 | |
2555 | OverloadedOperatorKind getOverloadedOperator() const; |
2556 | |
2557 | const IdentifierInfo *getLiteralIdentifier() const; |
2558 | |
2559 | /// If this function is an instantiation of a member function |
2560 | /// of a class template specialization, retrieves the function from |
2561 | /// which it was instantiated. |
2562 | /// |
2563 | /// This routine will return non-NULL for (non-templated) member |
2564 | /// functions of class templates and for instantiations of function |
2565 | /// templates. For example, given: |
2566 | /// |
2567 | /// \code |
2568 | /// template<typename T> |
2569 | /// struct X { |
2570 | /// void f(T); |
2571 | /// }; |
2572 | /// \endcode |
2573 | /// |
2574 | /// The declaration for X<int>::f is a (non-templated) FunctionDecl |
2575 | /// whose parent is the class template specialization X<int>. For |
2576 | /// this declaration, getInstantiatedFromFunction() will return |
2577 | /// the FunctionDecl X<T>::A. When a complete definition of |
2578 | /// X<int>::A is required, it will be instantiated from the |
2579 | /// declaration returned by getInstantiatedFromMemberFunction(). |
2580 | FunctionDecl *getInstantiatedFromMemberFunction() const; |
2581 | |
2582 | /// What kind of templated function this is. |
2583 | TemplatedKind getTemplatedKind() const; |
2584 | |
2585 | /// If this function is an instantiation of a member function of a |
2586 | /// class template specialization, retrieves the member specialization |
2587 | /// information. |
2588 | MemberSpecializationInfo *getMemberSpecializationInfo() const; |
2589 | |
2590 | /// Specify that this record is an instantiation of the |
2591 | /// member function FD. |
2592 | void setInstantiationOfMemberFunction(FunctionDecl *FD, |
2593 | TemplateSpecializationKind TSK) { |
2594 | setInstantiationOfMemberFunction(getASTContext(), FD, TSK); |
2595 | } |
2596 | |
2597 | /// Retrieves the function template that is described by this |
2598 | /// function declaration. |
2599 | /// |
2600 | /// Every function template is represented as a FunctionTemplateDecl |
2601 | /// and a FunctionDecl (or something derived from FunctionDecl). The |
2602 | /// former contains template properties (such as the template |
2603 | /// parameter lists) while the latter contains the actual |
2604 | /// description of the template's |
2605 | /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the |
2606 | /// FunctionDecl that describes the function template, |
2607 | /// getDescribedFunctionTemplate() retrieves the |
2608 | /// FunctionTemplateDecl from a FunctionDecl. |
2609 | FunctionTemplateDecl *getDescribedFunctionTemplate() const; |
2610 | |
2611 | void setDescribedFunctionTemplate(FunctionTemplateDecl *Template); |
2612 | |
2613 | /// Determine whether this function is a function template |
2614 | /// specialization. |
2615 | bool isFunctionTemplateSpecialization() const { |
2616 | return getPrimaryTemplate() != nullptr; |
2617 | } |
2618 | |
2619 | /// If this function is actually a function template specialization, |
2620 | /// retrieve information about this function template specialization. |
2621 | /// Otherwise, returns NULL. |
2622 | FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const; |
2623 | |
2624 | /// Determines whether this function is a function template |
2625 | /// specialization or a member of a class template specialization that can |
2626 | /// be implicitly instantiated. |
2627 | bool isImplicitlyInstantiable() const; |
2628 | |
2629 | /// Determines if the given function was instantiated from a |
2630 | /// function template. |
2631 | bool isTemplateInstantiation() const; |
2632 | |
2633 | /// Retrieve the function declaration from which this function could |
2634 | /// be instantiated, if it is an instantiation (rather than a non-template |
2635 | /// or a specialization, for example). |
2636 | /// |
2637 | /// If \p ForDefinition is \c false, explicit specializations will be treated |
2638 | /// as if they were implicit instantiations. This will then find the pattern |
2639 | /// corresponding to non-definition portions of the declaration, such as |
2640 | /// default arguments and the exception specification. |
2641 | FunctionDecl * |
2642 | getTemplateInstantiationPattern(bool ForDefinition = true) const; |
2643 | |
2644 | /// Retrieve the primary template that this function template |
2645 | /// specialization either specializes or was instantiated from. |
2646 | /// |
2647 | /// If this function declaration is not a function template specialization, |
2648 | /// returns NULL. |
2649 | FunctionTemplateDecl *getPrimaryTemplate() const; |
2650 | |
2651 | /// Retrieve the template arguments used to produce this function |
2652 | /// template specialization from the primary template. |
2653 | /// |
2654 | /// If this function declaration is not a function template specialization, |
2655 | /// returns NULL. |
2656 | const TemplateArgumentList *getTemplateSpecializationArgs() const; |
2657 | |
2658 | /// Retrieve the template argument list as written in the sources, |
2659 | /// if any. |
2660 | /// |
2661 | /// If this function declaration is not a function template specialization |
2662 | /// or if it had no explicit template argument list, returns NULL. |
2663 | /// Note that it an explicit template argument list may be written empty, |
2664 | /// e.g., template<> void foo<>(char* s); |
2665 | const ASTTemplateArgumentListInfo* |
2666 | getTemplateSpecializationArgsAsWritten() const; |
2667 | |
2668 | /// Specify that this function declaration is actually a function |
2669 | /// template specialization. |
2670 | /// |
2671 | /// \param Template the function template that this function template |
2672 | /// specialization specializes. |
2673 | /// |
2674 | /// \param TemplateArgs the template arguments that produced this |
2675 | /// function template specialization from the template. |
2676 | /// |
2677 | /// \param InsertPos If non-NULL, the position in the function template |
2678 | /// specialization set where the function template specialization data will |
2679 | /// be inserted. |
2680 | /// |
2681 | /// \param TSK the kind of template specialization this is. |
2682 | /// |
2683 | /// \param TemplateArgsAsWritten location info of template arguments. |
2684 | /// |
2685 | /// \param PointOfInstantiation point at which the function template |
2686 | /// specialization was first instantiated. |
2687 | void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, |
2688 | const TemplateArgumentList *TemplateArgs, |
2689 | void *InsertPos, |
2690 | TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, |
2691 | const TemplateArgumentListInfo *TemplateArgsAsWritten = nullptr, |
2692 | SourceLocation PointOfInstantiation = SourceLocation()) { |
2693 | setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, |
2694 | InsertPos, TSK, TemplateArgsAsWritten, |
2695 | PointOfInstantiation); |
2696 | } |
2697 | |
2698 | /// Specifies that this function declaration is actually a |
2699 | /// dependent function template specialization. |
2700 | void setDependentTemplateSpecialization(ASTContext &Context, |
2701 | const UnresolvedSetImpl &Templates, |
2702 | const TemplateArgumentListInfo &TemplateArgs); |
2703 | |
2704 | DependentFunctionTemplateSpecializationInfo * |
2705 | getDependentSpecializationInfo() const; |
2706 | |
2707 | /// Determine what kind of template instantiation this function |
2708 | /// represents. |
2709 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
2710 | |
2711 | /// Determine the kind of template specialization this function represents |
2712 | /// for the purpose of template instantiation. |
2713 | TemplateSpecializationKind |
2714 | getTemplateSpecializationKindForInstantiation() const; |
2715 | |
2716 | /// Determine what kind of template instantiation this function |
2717 | /// represents. |
2718 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
2719 | SourceLocation PointOfInstantiation = SourceLocation()); |
2720 | |
2721 | /// Retrieve the (first) point of instantiation of a function template |
2722 | /// specialization or a member of a class template specialization. |
2723 | /// |
2724 | /// \returns the first point of instantiation, if this function was |
2725 | /// instantiated from a template; otherwise, returns an invalid source |
2726 | /// location. |
2727 | SourceLocation getPointOfInstantiation() const; |
2728 | |
2729 | /// Determine whether this is or was instantiated from an out-of-line |
2730 | /// definition of a member function. |
2731 | bool isOutOfLine() const override; |
2732 | |
2733 | /// Identify a memory copying or setting function. |
2734 | /// If the given function is a memory copy or setting function, returns |
2735 | /// the corresponding Builtin ID. If the function is not a memory function, |
2736 | /// returns 0. |
2737 | unsigned getMemoryFunctionKind() const; |
2738 | |
2739 | /// Returns ODRHash of the function. This value is calculated and |
2740 | /// stored on first call, then the stored value returned on the other calls. |
2741 | unsigned getODRHash(); |
2742 | |
2743 | /// Returns cached ODRHash of the function. This must have been previously |
2744 | /// computed and stored. |
2745 | unsigned getODRHash() const; |
2746 | |
2747 | // Implement isa/cast/dyncast/etc. |
2748 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2749 | static bool classofKind(Kind K) { |
2750 | return K >= firstFunction && K <= lastFunction; |
2751 | } |
2752 | static DeclContext *castToDeclContext(const FunctionDecl *D) { |
2753 | return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D)); |
2754 | } |
2755 | static FunctionDecl *castFromDeclContext(const DeclContext *DC) { |
2756 | return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC)); |
2757 | } |
2758 | }; |
2759 | |
2760 | /// Represents a member of a struct/union/class. |
2761 | class FieldDecl : public DeclaratorDecl, public Mergeable<FieldDecl> { |
2762 | unsigned BitField : 1; |
2763 | unsigned Mutable : 1; |
2764 | mutable unsigned CachedFieldIndex : 30; |
2765 | |
2766 | /// The kinds of value we can store in InitializerOrBitWidth. |
2767 | /// |
2768 | /// Note that this is compatible with InClassInitStyle except for |
2769 | /// ISK_CapturedVLAType. |
2770 | enum InitStorageKind { |
2771 | /// If the pointer is null, there's nothing special. Otherwise, |
2772 | /// this is a bitfield and the pointer is the Expr* storing the |
2773 | /// bit-width. |
2774 | ISK_NoInit = (unsigned) ICIS_NoInit, |
2775 | |
2776 | /// The pointer is an (optional due to delayed parsing) Expr* |
2777 | /// holding the copy-initializer. |
2778 | ISK_InClassCopyInit = (unsigned) ICIS_CopyInit, |
2779 | |
2780 | /// The pointer is an (optional due to delayed parsing) Expr* |
2781 | /// holding the list-initializer. |
2782 | ISK_InClassListInit = (unsigned) ICIS_ListInit, |
2783 | |
2784 | /// The pointer is a VariableArrayType* that's been captured; |
2785 | /// the enclosing context is a lambda or captured statement. |
2786 | ISK_CapturedVLAType, |
2787 | }; |
2788 | |
2789 | /// If this is a bitfield with a default member initializer, this |
2790 | /// structure is used to represent the two expressions. |
2791 | struct InitAndBitWidth { |
2792 | Expr *Init; |
2793 | Expr *BitWidth; |
2794 | }; |
2795 | |
2796 | /// Storage for either the bit-width, the in-class initializer, or |
2797 | /// both (via InitAndBitWidth), or the captured variable length array bound. |
2798 | /// |
2799 | /// If the storage kind is ISK_InClassCopyInit or |
2800 | /// ISK_InClassListInit, but the initializer is null, then this |
2801 | /// field has an in-class initializer that has not yet been parsed |
2802 | /// and attached. |
2803 | // FIXME: Tail-allocate this to reduce the size of FieldDecl in the |
2804 | // overwhelmingly common case that we have none of these things. |
2805 | llvm::PointerIntPair<void *, 2, InitStorageKind> InitStorage; |
2806 | |
2807 | protected: |
2808 | FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, |
2809 | SourceLocation IdLoc, IdentifierInfo *Id, |
2810 | QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2811 | InClassInitStyle InitStyle) |
2812 | : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), |
2813 | BitField(false), Mutable(Mutable), CachedFieldIndex(0), |
2814 | InitStorage(nullptr, (InitStorageKind) InitStyle) { |
2815 | if (BW) |
2816 | setBitWidth(BW); |
2817 | } |
2818 | |
2819 | public: |
2820 | friend class ASTDeclReader; |
2821 | friend class ASTDeclWriter; |
2822 | |
2823 | static FieldDecl *Create(const ASTContext &C, DeclContext *DC, |
2824 | SourceLocation StartLoc, SourceLocation IdLoc, |
2825 | IdentifierInfo *Id, QualType T, |
2826 | TypeSourceInfo *TInfo, Expr *BW, bool Mutable, |
2827 | InClassInitStyle InitStyle); |
2828 | |
2829 | static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2830 | |
2831 | /// Returns the index of this field within its record, |
2832 | /// as appropriate for passing to ASTRecordLayout::getFieldOffset. |
2833 | unsigned getFieldIndex() const; |
2834 | |
2835 | /// Determines whether this field is mutable (C++ only). |
2836 | bool isMutable() const { return Mutable; } |
2837 | |
2838 | /// Determines whether this field is a bitfield. |
2839 | bool isBitField() const { return BitField; } |
2840 | |
2841 | /// Determines whether this is an unnamed bitfield. |
2842 | bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); } |
2843 | |
2844 | /// Determines whether this field is a |
2845 | /// representative for an anonymous struct or union. Such fields are |
2846 | /// unnamed and are implicitly generated by the implementation to |
2847 | /// store the data for the anonymous union or struct. |
2848 | bool isAnonymousStructOrUnion() const; |
2849 | |
2850 | Expr *getBitWidth() const { |
2851 | if (!BitField) |
2852 | return nullptr; |
2853 | void *Ptr = InitStorage.getPointer(); |
2854 | if (getInClassInitStyle()) |
2855 | return static_cast<InitAndBitWidth*>(Ptr)->BitWidth; |
2856 | return static_cast<Expr*>(Ptr); |
2857 | } |
2858 | |
2859 | unsigned getBitWidthValue(const ASTContext &Ctx) const; |
2860 | |
2861 | /// Set the bit-field width for this member. |
2862 | // Note: used by some clients (i.e., do not remove it). |
2863 | void setBitWidth(Expr *Width) { |
2864 | assert(!hasCapturedVLAType() && !BitField &&((!hasCapturedVLAType() && !BitField && "bit width or captured type already set" ) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 2865, __PRETTY_FUNCTION__)) |
2865 | "bit width or captured type already set")((!hasCapturedVLAType() && !BitField && "bit width or captured type already set" ) ? static_cast<void> (0) : __assert_fail ("!hasCapturedVLAType() && !BitField && \"bit width or captured type already set\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 2865, __PRETTY_FUNCTION__)); |
2866 | assert(Width && "no bit width specified")((Width && "no bit width specified") ? static_cast< void> (0) : __assert_fail ("Width && \"no bit width specified\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 2866, __PRETTY_FUNCTION__)); |
2867 | InitStorage.setPointer( |
2868 | InitStorage.getInt() |
2869 | ? new (getASTContext()) |
2870 | InitAndBitWidth{getInClassInitializer(), Width} |
2871 | : static_cast<void*>(Width)); |
2872 | BitField = true; |
2873 | } |
2874 | |
2875 | /// Remove the bit-field width from this member. |
2876 | // Note: used by some clients (i.e., do not remove it). |
2877 | void removeBitWidth() { |
2878 | assert(isBitField() && "no bitfield width to remove")((isBitField() && "no bitfield width to remove") ? static_cast <void> (0) : __assert_fail ("isBitField() && \"no bitfield width to remove\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 2878, __PRETTY_FUNCTION__)); |
2879 | InitStorage.setPointer(getInClassInitializer()); |
2880 | BitField = false; |
2881 | } |
2882 | |
2883 | /// Is this a zero-length bit-field? Such bit-fields aren't really bit-fields |
2884 | /// at all and instead act as a separator between contiguous runs of other |
2885 | /// bit-fields. |
2886 | bool isZeroLengthBitField(const ASTContext &Ctx) const; |
2887 | |
2888 | /// Determine if this field is a subobject of zero size, that is, either a |
2889 | /// zero-length bit-field or a field of empty class type with the |
2890 | /// [[no_unique_address]] attribute. |
2891 | bool isZeroSize(const ASTContext &Ctx) const; |
2892 | |
2893 | /// Get the kind of (C++11) default member initializer that this field has. |
2894 | InClassInitStyle getInClassInitStyle() const { |
2895 | InitStorageKind storageKind = InitStorage.getInt(); |
2896 | return (storageKind == ISK_CapturedVLAType |
2897 | ? ICIS_NoInit : (InClassInitStyle) storageKind); |
2898 | } |
2899 | |
2900 | /// Determine whether this member has a C++11 default member initializer. |
2901 | bool hasInClassInitializer() const { |
2902 | return getInClassInitStyle() != ICIS_NoInit; |
2903 | } |
2904 | |
2905 | /// Get the C++11 default member initializer for this member, or null if one |
2906 | /// has not been set. If a valid declaration has a default member initializer, |
2907 | /// but this returns null, then we have not parsed and attached it yet. |
2908 | Expr *getInClassInitializer() const { |
2909 | if (!hasInClassInitializer()) |
2910 | return nullptr; |
2911 | void *Ptr = InitStorage.getPointer(); |
2912 | if (BitField) |
2913 | return static_cast<InitAndBitWidth*>(Ptr)->Init; |
2914 | return static_cast<Expr*>(Ptr); |
2915 | } |
2916 | |
2917 | /// Set the C++11 in-class initializer for this member. |
2918 | void setInClassInitializer(Expr *Init) { |
2919 | assert(hasInClassInitializer() && !getInClassInitializer())((hasInClassInitializer() && !getInClassInitializer() ) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && !getInClassInitializer()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 2919, __PRETTY_FUNCTION__)); |
2920 | if (BitField) |
2921 | static_cast<InitAndBitWidth*>(InitStorage.getPointer())->Init = Init; |
2922 | else |
2923 | InitStorage.setPointer(Init); |
2924 | } |
2925 | |
2926 | /// Remove the C++11 in-class initializer from this member. |
2927 | void removeInClassInitializer() { |
2928 | assert(hasInClassInitializer() && "no initializer to remove")((hasInClassInitializer() && "no initializer to remove" ) ? static_cast<void> (0) : __assert_fail ("hasInClassInitializer() && \"no initializer to remove\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 2928, __PRETTY_FUNCTION__)); |
2929 | InitStorage.setPointerAndInt(getBitWidth(), ISK_NoInit); |
2930 | } |
2931 | |
2932 | /// Determine whether this member captures the variable length array |
2933 | /// type. |
2934 | bool hasCapturedVLAType() const { |
2935 | return InitStorage.getInt() == ISK_CapturedVLAType; |
2936 | } |
2937 | |
2938 | /// Get the captured variable length array type. |
2939 | const VariableArrayType *getCapturedVLAType() const { |
2940 | return hasCapturedVLAType() ? static_cast<const VariableArrayType *>( |
2941 | InitStorage.getPointer()) |
2942 | : nullptr; |
2943 | } |
2944 | |
2945 | /// Set the captured variable length array type for this field. |
2946 | void setCapturedVLAType(const VariableArrayType *VLAType); |
2947 | |
2948 | /// Returns the parent of this field declaration, which |
2949 | /// is the struct in which this field is defined. |
2950 | /// |
2951 | /// Returns null if this is not a normal class/struct field declaration, e.g. |
2952 | /// ObjCAtDefsFieldDecl, ObjCIvarDecl. |
2953 | const RecordDecl *getParent() const { |
2954 | return dyn_cast<RecordDecl>(getDeclContext()); |
2955 | } |
2956 | |
2957 | RecordDecl *getParent() { |
2958 | return dyn_cast<RecordDecl>(getDeclContext()); |
2959 | } |
2960 | |
2961 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
2962 | |
2963 | /// Retrieves the canonical declaration of this field. |
2964 | FieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
2965 | const FieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
2966 | |
2967 | // Implement isa/cast/dyncast/etc. |
2968 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
2969 | static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } |
2970 | }; |
2971 | |
2972 | /// An instance of this object exists for each enum constant |
2973 | /// that is defined. For example, in "enum X {a,b}", each of a/b are |
2974 | /// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a |
2975 | /// TagType for the X EnumDecl. |
2976 | class EnumConstantDecl : public ValueDecl, public Mergeable<EnumConstantDecl> { |
2977 | Stmt *Init; // an integer constant expression |
2978 | llvm::APSInt Val; // The value. |
2979 | |
2980 | protected: |
2981 | EnumConstantDecl(DeclContext *DC, SourceLocation L, |
2982 | IdentifierInfo *Id, QualType T, Expr *E, |
2983 | const llvm::APSInt &V) |
2984 | : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} |
2985 | |
2986 | public: |
2987 | friend class StmtIteratorBase; |
2988 | |
2989 | static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, |
2990 | SourceLocation L, IdentifierInfo *Id, |
2991 | QualType T, Expr *E, |
2992 | const llvm::APSInt &V); |
2993 | static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
2994 | |
2995 | const Expr *getInitExpr() const { return (const Expr*) Init; } |
2996 | Expr *getInitExpr() { return (Expr*) Init; } |
2997 | const llvm::APSInt &getInitVal() const { return Val; } |
2998 | |
2999 | void setInitExpr(Expr *E) { Init = (Stmt*) E; } |
3000 | void setInitVal(const llvm::APSInt &V) { Val = V; } |
3001 | |
3002 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3003 | |
3004 | /// Retrieves the canonical declaration of this enumerator. |
3005 | EnumConstantDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3006 | const EnumConstantDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3007 | |
3008 | // Implement isa/cast/dyncast/etc. |
3009 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3010 | static bool classofKind(Kind K) { return K == EnumConstant; } |
3011 | }; |
3012 | |
3013 | /// Represents a field injected from an anonymous union/struct into the parent |
3014 | /// scope. These are always implicit. |
3015 | class IndirectFieldDecl : public ValueDecl, |
3016 | public Mergeable<IndirectFieldDecl> { |
3017 | NamedDecl **Chaining; |
3018 | unsigned ChainingSize; |
3019 | |
3020 | IndirectFieldDecl(ASTContext &C, DeclContext *DC, SourceLocation L, |
3021 | DeclarationName N, QualType T, |
3022 | MutableArrayRef<NamedDecl *> CH); |
3023 | |
3024 | void anchor() override; |
3025 | |
3026 | public: |
3027 | friend class ASTDeclReader; |
3028 | |
3029 | static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, |
3030 | SourceLocation L, IdentifierInfo *Id, |
3031 | QualType T, llvm::MutableArrayRef<NamedDecl *> CH); |
3032 | |
3033 | static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3034 | |
3035 | using chain_iterator = ArrayRef<NamedDecl *>::const_iterator; |
3036 | |
3037 | ArrayRef<NamedDecl *> chain() const { |
3038 | return llvm::makeArrayRef(Chaining, ChainingSize); |
3039 | } |
3040 | chain_iterator chain_begin() const { return chain().begin(); } |
3041 | chain_iterator chain_end() const { return chain().end(); } |
3042 | |
3043 | unsigned getChainingSize() const { return ChainingSize; } |
3044 | |
3045 | FieldDecl *getAnonField() const { |
3046 | assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 3046, __PRETTY_FUNCTION__)); |
3047 | return cast<FieldDecl>(chain().back()); |
3048 | } |
3049 | |
3050 | VarDecl *getVarDecl() const { |
3051 | assert(chain().size() >= 2)((chain().size() >= 2) ? static_cast<void> (0) : __assert_fail ("chain().size() >= 2", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 3051, __PRETTY_FUNCTION__)); |
3052 | return dyn_cast<VarDecl>(chain().front()); |
3053 | } |
3054 | |
3055 | IndirectFieldDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3056 | const IndirectFieldDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3057 | |
3058 | // Implement isa/cast/dyncast/etc. |
3059 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3060 | static bool classofKind(Kind K) { return K == IndirectField; } |
3061 | }; |
3062 | |
3063 | /// Represents a declaration of a type. |
3064 | class TypeDecl : public NamedDecl { |
3065 | friend class ASTContext; |
3066 | |
3067 | /// This indicates the Type object that represents |
3068 | /// this TypeDecl. It is a cache maintained by |
3069 | /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and |
3070 | /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. |
3071 | mutable const Type *TypeForDecl = nullptr; |
3072 | |
3073 | /// The start of the source range for this declaration. |
3074 | SourceLocation LocStart; |
3075 | |
3076 | void anchor() override; |
3077 | |
3078 | protected: |
3079 | TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, |
3080 | SourceLocation StartL = SourceLocation()) |
3081 | : NamedDecl(DK, DC, L, Id), LocStart(StartL) {} |
3082 | |
3083 | public: |
3084 | // Low-level accessor. If you just want the type defined by this node, |
3085 | // check out ASTContext::getTypeDeclType or one of |
3086 | // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you |
3087 | // already know the specific kind of node this is. |
3088 | const Type *getTypeForDecl() const { return TypeForDecl; } |
3089 | void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } |
3090 | |
3091 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; } |
3092 | void setLocStart(SourceLocation L) { LocStart = L; } |
3093 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
3094 | if (LocStart.isValid()) |
3095 | return SourceRange(LocStart, getLocation()); |
3096 | else |
3097 | return SourceRange(getLocation()); |
3098 | } |
3099 | |
3100 | // Implement isa/cast/dyncast/etc. |
3101 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3102 | static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } |
3103 | }; |
3104 | |
3105 | /// Base class for declarations which introduce a typedef-name. |
3106 | class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> { |
3107 | struct alignas(8) ModedTInfo { |
3108 | TypeSourceInfo *first; |
3109 | QualType second; |
3110 | }; |
3111 | |
3112 | /// If int part is 0, we have not computed IsTransparentTag. |
3113 | /// Otherwise, IsTransparentTag is (getInt() >> 1). |
3114 | mutable llvm::PointerIntPair< |
3115 | llvm::PointerUnion<TypeSourceInfo *, ModedTInfo *>, 2> |
3116 | MaybeModedTInfo; |
3117 | |
3118 | void anchor() override; |
3119 | |
3120 | protected: |
3121 | TypedefNameDecl(Kind DK, ASTContext &C, DeclContext *DC, |
3122 | SourceLocation StartLoc, SourceLocation IdLoc, |
3123 | IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3124 | : TypeDecl(DK, DC, IdLoc, Id, StartLoc), redeclarable_base(C), |
3125 | MaybeModedTInfo(TInfo, 0) {} |
3126 | |
3127 | using redeclarable_base = Redeclarable<TypedefNameDecl>; |
3128 | |
3129 | TypedefNameDecl *getNextRedeclarationImpl() override { |
3130 | return getNextRedeclaration(); |
3131 | } |
3132 | |
3133 | TypedefNameDecl *getPreviousDeclImpl() override { |
3134 | return getPreviousDecl(); |
3135 | } |
3136 | |
3137 | TypedefNameDecl *getMostRecentDeclImpl() override { |
3138 | return getMostRecentDecl(); |
3139 | } |
3140 | |
3141 | public: |
3142 | using redecl_range = redeclarable_base::redecl_range; |
3143 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3144 | |
3145 | using redeclarable_base::redecls_begin; |
3146 | using redeclarable_base::redecls_end; |
3147 | using redeclarable_base::redecls; |
3148 | using redeclarable_base::getPreviousDecl; |
3149 | using redeclarable_base::getMostRecentDecl; |
3150 | using redeclarable_base::isFirstDecl; |
3151 | |
3152 | bool isModed() const { |
3153 | return MaybeModedTInfo.getPointer().is<ModedTInfo *>(); |
3154 | } |
3155 | |
3156 | TypeSourceInfo *getTypeSourceInfo() const { |
3157 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->first |
3158 | : MaybeModedTInfo.getPointer().get<TypeSourceInfo *>(); |
3159 | } |
3160 | |
3161 | QualType getUnderlyingType() const { |
3162 | return isModed() ? MaybeModedTInfo.getPointer().get<ModedTInfo *>()->second |
3163 | : MaybeModedTInfo.getPointer() |
3164 | .get<TypeSourceInfo *>() |
3165 | ->getType(); |
3166 | } |
3167 | |
3168 | void setTypeSourceInfo(TypeSourceInfo *newType) { |
3169 | MaybeModedTInfo.setPointer(newType); |
3170 | } |
3171 | |
3172 | void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy) { |
3173 | MaybeModedTInfo.setPointer(new (getASTContext(), 8) |
3174 | ModedTInfo({unmodedTSI, modedTy})); |
3175 | } |
3176 | |
3177 | /// Retrieves the canonical declaration of this typedef-name. |
3178 | TypedefNameDecl *getCanonicalDecl() override { return getFirstDecl(); } |
3179 | const TypedefNameDecl *getCanonicalDecl() const { return getFirstDecl(); } |
3180 | |
3181 | /// Retrieves the tag declaration for which this is the typedef name for |
3182 | /// linkage purposes, if any. |
3183 | /// |
3184 | /// \param AnyRedecl Look for the tag declaration in any redeclaration of |
3185 | /// this typedef declaration. |
3186 | TagDecl *getAnonDeclWithTypedefName(bool AnyRedecl = false) const; |
3187 | |
3188 | /// Determines if this typedef shares a name and spelling location with its |
3189 | /// underlying tag type, as is the case with the NS_ENUM macro. |
3190 | bool isTransparentTag() const { |
3191 | if (MaybeModedTInfo.getInt()) |
3192 | return MaybeModedTInfo.getInt() & 0x2; |
3193 | return isTransparentTagSlow(); |
3194 | } |
3195 | |
3196 | // Implement isa/cast/dyncast/etc. |
3197 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3198 | static bool classofKind(Kind K) { |
3199 | return K >= firstTypedefName && K <= lastTypedefName; |
3200 | } |
3201 | |
3202 | private: |
3203 | bool isTransparentTagSlow() const; |
3204 | }; |
3205 | |
3206 | /// Represents the declaration of a typedef-name via the 'typedef' |
3207 | /// type specifier. |
3208 | class TypedefDecl : public TypedefNameDecl { |
3209 | TypedefDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3210 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3211 | : TypedefNameDecl(Typedef, C, DC, StartLoc, IdLoc, Id, TInfo) {} |
3212 | |
3213 | public: |
3214 | static TypedefDecl *Create(ASTContext &C, DeclContext *DC, |
3215 | SourceLocation StartLoc, SourceLocation IdLoc, |
3216 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
3217 | static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3218 | |
3219 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3220 | |
3221 | // Implement isa/cast/dyncast/etc. |
3222 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3223 | static bool classofKind(Kind K) { return K == Typedef; } |
3224 | }; |
3225 | |
3226 | /// Represents the declaration of a typedef-name via a C++11 |
3227 | /// alias-declaration. |
3228 | class TypeAliasDecl : public TypedefNameDecl { |
3229 | /// The template for which this is the pattern, if any. |
3230 | TypeAliasTemplateDecl *Template; |
3231 | |
3232 | TypeAliasDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3233 | SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo) |
3234 | : TypedefNameDecl(TypeAlias, C, DC, StartLoc, IdLoc, Id, TInfo), |
3235 | Template(nullptr) {} |
3236 | |
3237 | public: |
3238 | static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC, |
3239 | SourceLocation StartLoc, SourceLocation IdLoc, |
3240 | IdentifierInfo *Id, TypeSourceInfo *TInfo); |
3241 | static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3242 | |
3243 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3244 | |
3245 | TypeAliasTemplateDecl *getDescribedAliasTemplate() const { return Template; } |
3246 | void setDescribedAliasTemplate(TypeAliasTemplateDecl *TAT) { Template = TAT; } |
3247 | |
3248 | // Implement isa/cast/dyncast/etc. |
3249 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3250 | static bool classofKind(Kind K) { return K == TypeAlias; } |
3251 | }; |
3252 | |
3253 | /// Represents the declaration of a struct/union/class/enum. |
3254 | class TagDecl : public TypeDecl, |
3255 | public DeclContext, |
3256 | public Redeclarable<TagDecl> { |
3257 | // This class stores some data in DeclContext::TagDeclBits |
3258 | // to save some space. Use the provided accessors to access it. |
3259 | public: |
3260 | // This is really ugly. |
3261 | using TagKind = TagTypeKind; |
3262 | |
3263 | private: |
3264 | SourceRange BraceRange; |
3265 | |
3266 | // A struct representing syntactic qualifier info, |
3267 | // to be used for the (uncommon) case of out-of-line declarations. |
3268 | using ExtInfo = QualifierInfo; |
3269 | |
3270 | /// If the (out-of-line) tag declaration name |
3271 | /// is qualified, it points to the qualifier info (nns and range); |
3272 | /// otherwise, if the tag declaration is anonymous and it is part of |
3273 | /// a typedef or alias, it points to the TypedefNameDecl (used for mangling); |
3274 | /// otherwise, if the tag declaration is anonymous and it is used as a |
3275 | /// declaration specifier for variables, it points to the first VarDecl (used |
3276 | /// for mangling); |
3277 | /// otherwise, it is a null (TypedefNameDecl) pointer. |
3278 | llvm::PointerUnion<TypedefNameDecl *, ExtInfo *> TypedefNameDeclOrQualifier; |
3279 | |
3280 | bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo *>(); } |
3281 | ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo *>(); } |
3282 | const ExtInfo *getExtInfo() const { |
3283 | return TypedefNameDeclOrQualifier.get<ExtInfo *>(); |
3284 | } |
3285 | |
3286 | protected: |
3287 | TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3288 | SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl, |
3289 | SourceLocation StartL); |
3290 | |
3291 | using redeclarable_base = Redeclarable<TagDecl>; |
3292 | |
3293 | TagDecl *getNextRedeclarationImpl() override { |
3294 | return getNextRedeclaration(); |
3295 | } |
3296 | |
3297 | TagDecl *getPreviousDeclImpl() override { |
3298 | return getPreviousDecl(); |
3299 | } |
3300 | |
3301 | TagDecl *getMostRecentDeclImpl() override { |
3302 | return getMostRecentDecl(); |
3303 | } |
3304 | |
3305 | /// Completes the definition of this tag declaration. |
3306 | /// |
3307 | /// This is a helper function for derived classes. |
3308 | void completeDefinition(); |
3309 | |
3310 | /// True if this decl is currently being defined. |
3311 | void setBeingDefined(bool V = true) { TagDeclBits.IsBeingDefined = V; } |
3312 | |
3313 | /// Indicates whether it is possible for declarations of this kind |
3314 | /// to have an out-of-date definition. |
3315 | /// |
3316 | /// This option is only enabled when modules are enabled. |
3317 | void setMayHaveOutOfDateDef(bool V = true) { |
3318 | TagDeclBits.MayHaveOutOfDateDef = V; |
3319 | } |
3320 | |
3321 | public: |
3322 | friend class ASTDeclReader; |
3323 | friend class ASTDeclWriter; |
3324 | |
3325 | using redecl_range = redeclarable_base::redecl_range; |
3326 | using redecl_iterator = redeclarable_base::redecl_iterator; |
3327 | |
3328 | using redeclarable_base::redecls_begin; |
3329 | using redeclarable_base::redecls_end; |
3330 | using redeclarable_base::redecls; |
3331 | using redeclarable_base::getPreviousDecl; |
3332 | using redeclarable_base::getMostRecentDecl; |
3333 | using redeclarable_base::isFirstDecl; |
3334 | |
3335 | SourceRange getBraceRange() const { return BraceRange; } |
3336 | void setBraceRange(SourceRange R) { BraceRange = R; } |
3337 | |
3338 | /// Return SourceLocation representing start of source |
3339 | /// range ignoring outer template declarations. |
3340 | SourceLocation getInnerLocStart() const { return getBeginLoc(); } |
3341 | |
3342 | /// Return SourceLocation representing start of source |
3343 | /// range taking into account any outer template declarations. |
3344 | SourceLocation getOuterLocStart() const; |
3345 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
3346 | |
3347 | TagDecl *getCanonicalDecl() override; |
3348 | const TagDecl *getCanonicalDecl() const { |
3349 | return const_cast<TagDecl*>(this)->getCanonicalDecl(); |
3350 | } |
3351 | |
3352 | /// Return true if this declaration is a completion definition of the type. |
3353 | /// Provided for consistency. |
3354 | bool isThisDeclarationADefinition() const { |
3355 | return isCompleteDefinition(); |
3356 | } |
3357 | |
3358 | /// Return true if this decl has its body fully specified. |
3359 | bool isCompleteDefinition() const { return TagDeclBits.IsCompleteDefinition; } |
3360 | |
3361 | /// True if this decl has its body fully specified. |
3362 | void setCompleteDefinition(bool V = true) { |
3363 | TagDeclBits.IsCompleteDefinition = V; |
3364 | } |
3365 | |
3366 | /// Return true if this complete decl is |
3367 | /// required to be complete for some existing use. |
3368 | bool isCompleteDefinitionRequired() const { |
3369 | return TagDeclBits.IsCompleteDefinitionRequired; |
3370 | } |
3371 | |
3372 | /// True if this complete decl is |
3373 | /// required to be complete for some existing use. |
3374 | void setCompleteDefinitionRequired(bool V = true) { |
3375 | TagDeclBits.IsCompleteDefinitionRequired = V; |
3376 | } |
3377 | |
3378 | /// Return true if this decl is currently being defined. |
3379 | bool isBeingDefined() const { return TagDeclBits.IsBeingDefined; } |
3380 | |
3381 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
3382 | /// for the very first time) in the syntax of a declarator. |
3383 | bool isEmbeddedInDeclarator() const { |
3384 | return TagDeclBits.IsEmbeddedInDeclarator; |
3385 | } |
3386 | |
3387 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
3388 | /// for the very first time) in the syntax of a declarator. |
3389 | void setEmbeddedInDeclarator(bool isInDeclarator) { |
3390 | TagDeclBits.IsEmbeddedInDeclarator = isInDeclarator; |
3391 | } |
3392 | |
3393 | /// True if this tag is free standing, e.g. "struct foo;". |
3394 | bool isFreeStanding() const { return TagDeclBits.IsFreeStanding; } |
3395 | |
3396 | /// True if this tag is free standing, e.g. "struct foo;". |
3397 | void setFreeStanding(bool isFreeStanding = true) { |
3398 | TagDeclBits.IsFreeStanding = isFreeStanding; |
3399 | } |
3400 | |
3401 | /// Indicates whether it is possible for declarations of this kind |
3402 | /// to have an out-of-date definition. |
3403 | /// |
3404 | /// This option is only enabled when modules are enabled. |
3405 | bool mayHaveOutOfDateDef() const { return TagDeclBits.MayHaveOutOfDateDef; } |
3406 | |
3407 | /// Whether this declaration declares a type that is |
3408 | /// dependent, i.e., a type that somehow depends on template |
3409 | /// parameters. |
3410 | bool isDependentType() const { return isDependentContext(); } |
3411 | |
3412 | /// Starts the definition of this tag declaration. |
3413 | /// |
3414 | /// This method should be invoked at the beginning of the definition |
3415 | /// of this tag declaration. It will set the tag type into a state |
3416 | /// where it is in the process of being defined. |
3417 | void startDefinition(); |
3418 | |
3419 | /// Returns the TagDecl that actually defines this |
3420 | /// struct/union/class/enum. When determining whether or not a |
3421 | /// struct/union/class/enum has a definition, one should use this |
3422 | /// method as opposed to 'isDefinition'. 'isDefinition' indicates |
3423 | /// whether or not a specific TagDecl is defining declaration, not |
3424 | /// whether or not the struct/union/class/enum type is defined. |
3425 | /// This method returns NULL if there is no TagDecl that defines |
3426 | /// the struct/union/class/enum. |
3427 | TagDecl *getDefinition() const; |
3428 | |
3429 | StringRef getKindName() const { |
3430 | return TypeWithKeyword::getTagTypeKindName(getTagKind()); |
3431 | } |
3432 | |
3433 | TagKind getTagKind() const { |
3434 | return static_cast<TagKind>(TagDeclBits.TagDeclKind); |
3435 | } |
3436 | |
3437 | void setTagKind(TagKind TK) { TagDeclBits.TagDeclKind = TK; } |
3438 | |
3439 | bool isStruct() const { return getTagKind() == TTK_Struct; } |
3440 | bool isInterface() const { return getTagKind() == TTK_Interface; } |
3441 | bool isClass() const { return getTagKind() == TTK_Class; } |
3442 | bool isUnion() const { return getTagKind() == TTK_Union; } |
3443 | bool isEnum() const { return getTagKind() == TTK_Enum; } |
3444 | |
3445 | /// Is this tag type named, either directly or via being defined in |
3446 | /// a typedef of this type? |
3447 | /// |
3448 | /// C++11 [basic.link]p8: |
3449 | /// A type is said to have linkage if and only if: |
3450 | /// - it is a class or enumeration type that is named (or has a |
3451 | /// name for linkage purposes) and the name has linkage; ... |
3452 | /// C++11 [dcl.typedef]p9: |
3453 | /// If the typedef declaration defines an unnamed class (or enum), |
3454 | /// the first typedef-name declared by the declaration to be that |
3455 | /// class type (or enum type) is used to denote the class type (or |
3456 | /// enum type) for linkage purposes only. |
3457 | /// |
3458 | /// C does not have an analogous rule, but the same concept is |
3459 | /// nonetheless useful in some places. |
3460 | bool hasNameForLinkage() const { |
3461 | return (getDeclName() || getTypedefNameForAnonDecl()); |
3462 | } |
3463 | |
3464 | TypedefNameDecl *getTypedefNameForAnonDecl() const { |
3465 | return hasExtInfo() ? nullptr |
3466 | : TypedefNameDeclOrQualifier.get<TypedefNameDecl *>(); |
3467 | } |
3468 | |
3469 | void setTypedefNameForAnonDecl(TypedefNameDecl *TDD); |
3470 | |
3471 | /// Retrieve the nested-name-specifier that qualifies the name of this |
3472 | /// declaration, if it was present in the source. |
3473 | NestedNameSpecifier *getQualifier() const { |
3474 | return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() |
3475 | : nullptr; |
3476 | } |
3477 | |
3478 | /// Retrieve the nested-name-specifier (with source-location |
3479 | /// information) that qualifies the name of this declaration, if it was |
3480 | /// present in the source. |
3481 | NestedNameSpecifierLoc getQualifierLoc() const { |
3482 | return hasExtInfo() ? getExtInfo()->QualifierLoc |
3483 | : NestedNameSpecifierLoc(); |
3484 | } |
3485 | |
3486 | void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); |
3487 | |
3488 | unsigned getNumTemplateParameterLists() const { |
3489 | return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; |
3490 | } |
3491 | |
3492 | TemplateParameterList *getTemplateParameterList(unsigned i) const { |
3493 | assert(i < getNumTemplateParameterLists())((i < getNumTemplateParameterLists()) ? static_cast<void > (0) : __assert_fail ("i < getNumTemplateParameterLists()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 3493, __PRETTY_FUNCTION__)); |
3494 | return getExtInfo()->TemplParamLists[i]; |
3495 | } |
3496 | |
3497 | void setTemplateParameterListsInfo(ASTContext &Context, |
3498 | ArrayRef<TemplateParameterList *> TPLists); |
3499 | |
3500 | // Implement isa/cast/dyncast/etc. |
3501 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3502 | static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } |
3503 | |
3504 | static DeclContext *castToDeclContext(const TagDecl *D) { |
3505 | return static_cast<DeclContext *>(const_cast<TagDecl*>(D)); |
3506 | } |
3507 | |
3508 | static TagDecl *castFromDeclContext(const DeclContext *DC) { |
3509 | return static_cast<TagDecl *>(const_cast<DeclContext*>(DC)); |
3510 | } |
3511 | }; |
3512 | |
3513 | /// Represents an enum. In C++11, enums can be forward-declared |
3514 | /// with a fixed underlying type, and in C we allow them to be forward-declared |
3515 | /// with no underlying type as an extension. |
3516 | class EnumDecl : public TagDecl { |
3517 | // This class stores some data in DeclContext::EnumDeclBits |
3518 | // to save some space. Use the provided accessors to access it. |
3519 | |
3520 | /// This represent the integer type that the enum corresponds |
3521 | /// to for code generation purposes. Note that the enumerator constants may |
3522 | /// have a different type than this does. |
3523 | /// |
3524 | /// If the underlying integer type was explicitly stated in the source |
3525 | /// code, this is a TypeSourceInfo* for that type. Otherwise this type |
3526 | /// was automatically deduced somehow, and this is a Type*. |
3527 | /// |
3528 | /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in |
3529 | /// some cases it won't. |
3530 | /// |
3531 | /// The underlying type of an enumeration never has any qualifiers, so |
3532 | /// we can get away with just storing a raw Type*, and thus save an |
3533 | /// extra pointer when TypeSourceInfo is needed. |
3534 | llvm::PointerUnion<const Type *, TypeSourceInfo *> IntegerType; |
3535 | |
3536 | /// The integer type that values of this type should |
3537 | /// promote to. In C, enumerators are generally of an integer type |
3538 | /// directly, but gcc-style large enumerators (and all enumerators |
3539 | /// in C++) are of the enum type instead. |
3540 | QualType PromotionType; |
3541 | |
3542 | /// If this enumeration is an instantiation of a member enumeration |
3543 | /// of a class template specialization, this is the member specialization |
3544 | /// information. |
3545 | MemberSpecializationInfo *SpecializationInfo = nullptr; |
3546 | |
3547 | /// Store the ODRHash after first calculation. |
3548 | /// The corresponding flag HasODRHash is in EnumDeclBits |
3549 | /// and can be accessed with the provided accessors. |
3550 | unsigned ODRHash; |
3551 | |
3552 | EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, |
3553 | SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, |
3554 | bool Scoped, bool ScopedUsingClassTag, bool Fixed); |
3555 | |
3556 | void anchor() override; |
3557 | |
3558 | void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, |
3559 | TemplateSpecializationKind TSK); |
3560 | |
3561 | /// Sets the width in bits required to store all the |
3562 | /// non-negative enumerators of this enum. |
3563 | void setNumPositiveBits(unsigned Num) { |
3564 | EnumDeclBits.NumPositiveBits = Num; |
3565 | assert(EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount")((EnumDeclBits.NumPositiveBits == Num && "can't store this bitcount" ) ? static_cast<void> (0) : __assert_fail ("EnumDeclBits.NumPositiveBits == Num && \"can't store this bitcount\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 3565, __PRETTY_FUNCTION__)); |
3566 | } |
3567 | |
3568 | /// Returns the width in bits required to store all the |
3569 | /// negative enumerators of this enum. (see getNumNegativeBits) |
3570 | void setNumNegativeBits(unsigned Num) { EnumDeclBits.NumNegativeBits = Num; } |
3571 | |
3572 | public: |
3573 | /// True if this tag declaration is a scoped enumeration. Only |
3574 | /// possible in C++11 mode. |
3575 | void setScoped(bool Scoped = true) { EnumDeclBits.IsScoped = Scoped; } |
3576 | |
3577 | /// If this tag declaration is a scoped enum, |
3578 | /// then this is true if the scoped enum was declared using the class |
3579 | /// tag, false if it was declared with the struct tag. No meaning is |
3580 | /// associated if this tag declaration is not a scoped enum. |
3581 | void setScopedUsingClassTag(bool ScopedUCT = true) { |
3582 | EnumDeclBits.IsScopedUsingClassTag = ScopedUCT; |
3583 | } |
3584 | |
3585 | /// True if this is an Objective-C, C++11, or |
3586 | /// Microsoft-style enumeration with a fixed underlying type. |
3587 | void setFixed(bool Fixed = true) { EnumDeclBits.IsFixed = Fixed; } |
3588 | |
3589 | private: |
3590 | /// True if a valid hash is stored in ODRHash. |
3591 | bool hasODRHash() const { return EnumDeclBits.HasODRHash; } |
3592 | void setHasODRHash(bool Hash = true) { EnumDeclBits.HasODRHash = Hash; } |
3593 | |
3594 | public: |
3595 | friend class ASTDeclReader; |
3596 | |
3597 | EnumDecl *getCanonicalDecl() override { |
3598 | return cast<EnumDecl>(TagDecl::getCanonicalDecl()); |
3599 | } |
3600 | const EnumDecl *getCanonicalDecl() const { |
3601 | return const_cast<EnumDecl*>(this)->getCanonicalDecl(); |
3602 | } |
3603 | |
3604 | EnumDecl *getPreviousDecl() { |
3605 | return cast_or_null<EnumDecl>( |
3606 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3607 | } |
3608 | const EnumDecl *getPreviousDecl() const { |
3609 | return const_cast<EnumDecl*>(this)->getPreviousDecl(); |
3610 | } |
3611 | |
3612 | EnumDecl *getMostRecentDecl() { |
3613 | return cast<EnumDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3614 | } |
3615 | const EnumDecl *getMostRecentDecl() const { |
3616 | return const_cast<EnumDecl*>(this)->getMostRecentDecl(); |
3617 | } |
3618 | |
3619 | EnumDecl *getDefinition() const { |
3620 | return cast_or_null<EnumDecl>(TagDecl::getDefinition()); |
3621 | } |
3622 | |
3623 | static EnumDecl *Create(ASTContext &C, DeclContext *DC, |
3624 | SourceLocation StartLoc, SourceLocation IdLoc, |
3625 | IdentifierInfo *Id, EnumDecl *PrevDecl, |
3626 | bool IsScoped, bool IsScopedUsingClassTag, |
3627 | bool IsFixed); |
3628 | static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
3629 | |
3630 | /// When created, the EnumDecl corresponds to a |
3631 | /// forward-declared enum. This method is used to mark the |
3632 | /// declaration as being defined; its enumerators have already been |
3633 | /// added (via DeclContext::addDecl). NewType is the new underlying |
3634 | /// type of the enumeration type. |
3635 | void completeDefinition(QualType NewType, |
3636 | QualType PromotionType, |
3637 | unsigned NumPositiveBits, |
3638 | unsigned NumNegativeBits); |
3639 | |
3640 | // Iterates through the enumerators of this enumeration. |
3641 | using enumerator_iterator = specific_decl_iterator<EnumConstantDecl>; |
3642 | using enumerator_range = |
3643 | llvm::iterator_range<specific_decl_iterator<EnumConstantDecl>>; |
3644 | |
3645 | enumerator_range enumerators() const { |
3646 | return enumerator_range(enumerator_begin(), enumerator_end()); |
3647 | } |
3648 | |
3649 | enumerator_iterator enumerator_begin() const { |
3650 | const EnumDecl *E = getDefinition(); |
3651 | if (!E) |
3652 | E = this; |
3653 | return enumerator_iterator(E->decls_begin()); |
3654 | } |
3655 | |
3656 | enumerator_iterator enumerator_end() const { |
3657 | const EnumDecl *E = getDefinition(); |
3658 | if (!E) |
3659 | E = this; |
3660 | return enumerator_iterator(E->decls_end()); |
3661 | } |
3662 | |
3663 | /// Return the integer type that enumerators should promote to. |
3664 | QualType getPromotionType() const { return PromotionType; } |
3665 | |
3666 | /// Set the promotion type. |
3667 | void setPromotionType(QualType T) { PromotionType = T; } |
3668 | |
3669 | /// Return the integer type this enum decl corresponds to. |
3670 | /// This returns a null QualType for an enum forward definition with no fixed |
3671 | /// underlying type. |
3672 | QualType getIntegerType() const { |
3673 | if (!IntegerType) |
3674 | return QualType(); |
3675 | if (const Type *T = IntegerType.dyn_cast<const Type*>()) |
3676 | return QualType(T, 0); |
3677 | return IntegerType.get<TypeSourceInfo*>()->getType().getUnqualifiedType(); |
3678 | } |
3679 | |
3680 | /// Set the underlying integer type. |
3681 | void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } |
3682 | |
3683 | /// Set the underlying integer type source info. |
3684 | void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo) { IntegerType = TInfo; } |
3685 | |
3686 | /// Return the type source info for the underlying integer type, |
3687 | /// if no type source info exists, return 0. |
3688 | TypeSourceInfo *getIntegerTypeSourceInfo() const { |
3689 | return IntegerType.dyn_cast<TypeSourceInfo*>(); |
3690 | } |
3691 | |
3692 | /// Retrieve the source range that covers the underlying type if |
3693 | /// specified. |
3694 | SourceRange getIntegerTypeRange() const LLVM_READONLY__attribute__((__pure__)); |
3695 | |
3696 | /// Returns the width in bits required to store all the |
3697 | /// non-negative enumerators of this enum. |
3698 | unsigned getNumPositiveBits() const { return EnumDeclBits.NumPositiveBits; } |
3699 | |
3700 | /// Returns the width in bits required to store all the |
3701 | /// negative enumerators of this enum. These widths include |
3702 | /// the rightmost leading 1; that is: |
3703 | /// |
3704 | /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS |
3705 | /// ------------------------ ------- ----------------- |
3706 | /// -1 1111111 1 |
3707 | /// -10 1110110 5 |
3708 | /// -101 1001011 8 |
3709 | unsigned getNumNegativeBits() const { return EnumDeclBits.NumNegativeBits; } |
3710 | |
3711 | /// Returns true if this is a C++11 scoped enumeration. |
3712 | bool isScoped() const { return EnumDeclBits.IsScoped; } |
3713 | |
3714 | /// Returns true if this is a C++11 scoped enumeration. |
3715 | bool isScopedUsingClassTag() const { |
3716 | return EnumDeclBits.IsScopedUsingClassTag; |
3717 | } |
3718 | |
3719 | /// Returns true if this is an Objective-C, C++11, or |
3720 | /// Microsoft-style enumeration with a fixed underlying type. |
3721 | bool isFixed() const { return EnumDeclBits.IsFixed; } |
3722 | |
3723 | unsigned getODRHash(); |
3724 | |
3725 | /// Returns true if this can be considered a complete type. |
3726 | bool isComplete() const { |
3727 | // IntegerType is set for fixed type enums and non-fixed but implicitly |
3728 | // int-sized Microsoft enums. |
3729 | return isCompleteDefinition() || IntegerType; |
3730 | } |
3731 | |
3732 | /// Returns true if this enum is either annotated with |
3733 | /// enum_extensibility(closed) or isn't annotated with enum_extensibility. |
3734 | bool isClosed() const; |
3735 | |
3736 | /// Returns true if this enum is annotated with flag_enum and isn't annotated |
3737 | /// with enum_extensibility(open). |
3738 | bool isClosedFlag() const; |
3739 | |
3740 | /// Returns true if this enum is annotated with neither flag_enum nor |
3741 | /// enum_extensibility(open). |
3742 | bool isClosedNonFlag() const; |
3743 | |
3744 | /// Retrieve the enum definition from which this enumeration could |
3745 | /// be instantiated, if it is an instantiation (rather than a non-template). |
3746 | EnumDecl *getTemplateInstantiationPattern() const; |
3747 | |
3748 | /// Returns the enumeration (declared within the template) |
3749 | /// from which this enumeration type was instantiated, or NULL if |
3750 | /// this enumeration was not instantiated from any template. |
3751 | EnumDecl *getInstantiatedFromMemberEnum() const; |
3752 | |
3753 | /// If this enumeration is a member of a specialization of a |
3754 | /// templated class, determine what kind of template specialization |
3755 | /// or instantiation this is. |
3756 | TemplateSpecializationKind getTemplateSpecializationKind() const; |
3757 | |
3758 | /// For an enumeration member that was instantiated from a member |
3759 | /// enumeration of a templated class, set the template specialiation kind. |
3760 | void setTemplateSpecializationKind(TemplateSpecializationKind TSK, |
3761 | SourceLocation PointOfInstantiation = SourceLocation()); |
3762 | |
3763 | /// If this enumeration is an instantiation of a member enumeration of |
3764 | /// a class template specialization, retrieves the member specialization |
3765 | /// information. |
3766 | MemberSpecializationInfo *getMemberSpecializationInfo() const { |
3767 | return SpecializationInfo; |
3768 | } |
3769 | |
3770 | /// Specify that this enumeration is an instantiation of the |
3771 | /// member enumeration ED. |
3772 | void setInstantiationOfMemberEnum(EnumDecl *ED, |
3773 | TemplateSpecializationKind TSK) { |
3774 | setInstantiationOfMemberEnum(getASTContext(), ED, TSK); |
3775 | } |
3776 | |
3777 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
3778 | static bool classofKind(Kind K) { return K == Enum; } |
3779 | }; |
3780 | |
3781 | /// Represents a struct/union/class. For example: |
3782 | /// struct X; // Forward declaration, no "body". |
3783 | /// union Y { int A, B; }; // Has body with members A and B (FieldDecls). |
3784 | /// This decl will be marked invalid if *any* members are invalid. |
3785 | class RecordDecl : public TagDecl { |
3786 | // This class stores some data in DeclContext::RecordDeclBits |
3787 | // to save some space. Use the provided accessors to access it. |
3788 | public: |
3789 | friend class DeclContext; |
3790 | /// Enum that represents the different ways arguments are passed to and |
3791 | /// returned from function calls. This takes into account the target-specific |
3792 | /// and version-specific rules along with the rules determined by the |
3793 | /// language. |
3794 | enum ArgPassingKind : unsigned { |
3795 | /// The argument of this type can be passed directly in registers. |
3796 | APK_CanPassInRegs, |
3797 | |
3798 | /// The argument of this type cannot be passed directly in registers. |
3799 | /// Records containing this type as a subobject are not forced to be passed |
3800 | /// indirectly. This value is used only in C++. This value is required by |
3801 | /// C++ because, in uncommon situations, it is possible for a class to have |
3802 | /// only trivial copy/move constructors even when one of its subobjects has |
3803 | /// a non-trivial copy/move constructor (if e.g. the corresponding copy/move |
3804 | /// constructor in the derived class is deleted). |
3805 | APK_CannotPassInRegs, |
3806 | |
3807 | /// The argument of this type cannot be passed directly in registers. |
3808 | /// Records containing this type as a subobject are forced to be passed |
3809 | /// indirectly. |
3810 | APK_CanNeverPassInRegs |
3811 | }; |
3812 | |
3813 | protected: |
3814 | RecordDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC, |
3815 | SourceLocation StartLoc, SourceLocation IdLoc, |
3816 | IdentifierInfo *Id, RecordDecl *PrevDecl); |
3817 | |
3818 | public: |
3819 | static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, |
3820 | SourceLocation StartLoc, SourceLocation IdLoc, |
3821 | IdentifierInfo *Id, RecordDecl* PrevDecl = nullptr); |
3822 | static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); |
3823 | |
3824 | RecordDecl *getPreviousDecl() { |
3825 | return cast_or_null<RecordDecl>( |
3826 | static_cast<TagDecl *>(this)->getPreviousDecl()); |
3827 | } |
3828 | const RecordDecl *getPreviousDecl() const { |
3829 | return const_cast<RecordDecl*>(this)->getPreviousDecl(); |
3830 | } |
3831 | |
3832 | RecordDecl *getMostRecentDecl() { |
3833 | return cast<RecordDecl>(static_cast<TagDecl *>(this)->getMostRecentDecl()); |
3834 | } |
3835 | const RecordDecl *getMostRecentDecl() const { |
3836 | return const_cast<RecordDecl*>(this)->getMostRecentDecl(); |
3837 | } |
3838 | |
3839 | bool hasFlexibleArrayMember() const { |
3840 | return RecordDeclBits.HasFlexibleArrayMember; |
3841 | } |
3842 | |
3843 | void setHasFlexibleArrayMember(bool V) { |
3844 | RecordDeclBits.HasFlexibleArrayMember = V; |
3845 | } |
3846 | |
3847 | /// Whether this is an anonymous struct or union. To be an anonymous |
3848 | /// struct or union, it must have been declared without a name and |
3849 | /// there must be no objects of this type declared, e.g., |
3850 | /// @code |
3851 | /// union { int i; float f; }; |
3852 | /// @endcode |
3853 | /// is an anonymous union but neither of the following are: |
3854 | /// @code |
3855 | /// union X { int i; float f; }; |
3856 | /// union { int i; float f; } obj; |
3857 | /// @endcode |
3858 | bool isAnonymousStructOrUnion() const { |
3859 | return RecordDeclBits.AnonymousStructOrUnion; |
3860 | } |
3861 | |
3862 | void setAnonymousStructOrUnion(bool Anon) { |
3863 | RecordDeclBits.AnonymousStructOrUnion = Anon; |
3864 | } |
3865 | |
3866 | bool hasObjectMember() const { return RecordDeclBits.HasObjectMember; } |
3867 | void setHasObjectMember(bool val) { RecordDeclBits.HasObjectMember = val; } |
3868 | |
3869 | bool hasVolatileMember() const { return RecordDeclBits.HasVolatileMember; } |
3870 | |
3871 | void setHasVolatileMember(bool val) { |
3872 | RecordDeclBits.HasVolatileMember = val; |
3873 | } |
3874 | |
3875 | bool hasLoadedFieldsFromExternalStorage() const { |
3876 | return RecordDeclBits.LoadedFieldsFromExternalStorage; |
3877 | } |
3878 | |
3879 | void setHasLoadedFieldsFromExternalStorage(bool val) const { |
3880 | RecordDeclBits.LoadedFieldsFromExternalStorage = val; |
3881 | } |
3882 | |
3883 | /// Functions to query basic properties of non-trivial C structs. |
3884 | bool isNonTrivialToPrimitiveDefaultInitialize() const { |
3885 | return RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize; |
3886 | } |
3887 | |
3888 | void setNonTrivialToPrimitiveDefaultInitialize(bool V) { |
3889 | RecordDeclBits.NonTrivialToPrimitiveDefaultInitialize = V; |
3890 | } |
3891 | |
3892 | bool isNonTrivialToPrimitiveCopy() const { |
3893 | return RecordDeclBits.NonTrivialToPrimitiveCopy; |
3894 | } |
3895 | |
3896 | void setNonTrivialToPrimitiveCopy(bool V) { |
3897 | RecordDeclBits.NonTrivialToPrimitiveCopy = V; |
3898 | } |
3899 | |
3900 | bool isNonTrivialToPrimitiveDestroy() const { |
3901 | return RecordDeclBits.NonTrivialToPrimitiveDestroy; |
3902 | } |
3903 | |
3904 | void setNonTrivialToPrimitiveDestroy(bool V) { |
3905 | RecordDeclBits.NonTrivialToPrimitiveDestroy = V; |
3906 | } |
3907 | |
3908 | bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const { |
3909 | return RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion; |
3910 | } |
3911 | |
3912 | void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V) { |
3913 | RecordDeclBits.HasNonTrivialToPrimitiveDefaultInitializeCUnion = V; |
3914 | } |
3915 | |
3916 | bool hasNonTrivialToPrimitiveDestructCUnion() const { |
3917 | return RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion; |
3918 | } |
3919 | |
3920 | void setHasNonTrivialToPrimitiveDestructCUnion(bool V) { |
3921 | RecordDeclBits.HasNonTrivialToPrimitiveDestructCUnion = V; |
3922 | } |
3923 | |
3924 | bool hasNonTrivialToPrimitiveCopyCUnion() const { |
3925 | return RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion; |
3926 | } |
3927 | |
3928 | void setHasNonTrivialToPrimitiveCopyCUnion(bool V) { |
3929 | RecordDeclBits.HasNonTrivialToPrimitiveCopyCUnion = V; |
3930 | } |
3931 | |
3932 | /// Determine whether this class can be passed in registers. In C++ mode, |
3933 | /// it must have at least one trivial, non-deleted copy or move constructor. |
3934 | /// FIXME: This should be set as part of completeDefinition. |
3935 | bool canPassInRegisters() const { |
3936 | return getArgPassingRestrictions() == APK_CanPassInRegs; |
3937 | } |
3938 | |
3939 | ArgPassingKind getArgPassingRestrictions() const { |
3940 | return static_cast<ArgPassingKind>(RecordDeclBits.ArgPassingRestrictions); |
3941 | } |
3942 | |
3943 | void setArgPassingRestrictions(ArgPassingKind Kind) { |
3944 | RecordDeclBits.ArgPassingRestrictions = Kind; |
3945 | } |
3946 | |
3947 | bool isParamDestroyedInCallee() const { |
3948 | return RecordDeclBits.ParamDestroyedInCallee; |
3949 | } |
3950 | |
3951 | void setParamDestroyedInCallee(bool V) { |
3952 | RecordDeclBits.ParamDestroyedInCallee = V; |
3953 | } |
3954 | |
3955 | /// Determines whether this declaration represents the |
3956 | /// injected class name. |
3957 | /// |
3958 | /// The injected class name in C++ is the name of the class that |
3959 | /// appears inside the class itself. For example: |
3960 | /// |
3961 | /// \code |
3962 | /// struct C { |
3963 | /// // C is implicitly declared here as a synonym for the class name. |
3964 | /// }; |
3965 | /// |
3966 | /// C::C c; // same as "C c;" |
3967 | /// \endcode |
3968 | bool isInjectedClassName() const; |
3969 | |
3970 | /// Determine whether this record is a class describing a lambda |
3971 | /// function object. |
3972 | bool isLambda() const; |
3973 | |
3974 | /// Determine whether this record is a record for captured variables in |
3975 | /// CapturedStmt construct. |
3976 | bool isCapturedRecord() const; |
3977 | |
3978 | /// Mark the record as a record for captured variables in CapturedStmt |
3979 | /// construct. |
3980 | void setCapturedRecord(); |
3981 | |
3982 | /// Returns the RecordDecl that actually defines |
3983 | /// this struct/union/class. When determining whether or not a |
3984 | /// struct/union/class is completely defined, one should use this |
3985 | /// method as opposed to 'isCompleteDefinition'. |
3986 | /// 'isCompleteDefinition' indicates whether or not a specific |
3987 | /// RecordDecl is a completed definition, not whether or not the |
3988 | /// record type is defined. This method returns NULL if there is |
3989 | /// no RecordDecl that defines the struct/union/tag. |
3990 | RecordDecl *getDefinition() const { |
3991 | return cast_or_null<RecordDecl>(TagDecl::getDefinition()); |
3992 | } |
3993 | |
3994 | /// Returns whether this record is a union, or contains (at any nesting level) |
3995 | /// a union member. This is used by CMSE to warn about possible information |
3996 | /// leaks. |
3997 | bool isOrContainsUnion() const; |
3998 | |
3999 | // Iterator access to field members. The field iterator only visits |
4000 | // the non-static data members of this class, ignoring any static |
4001 | // data members, functions, constructors, destructors, etc. |
4002 | using field_iterator = specific_decl_iterator<FieldDecl>; |
4003 | using field_range = llvm::iterator_range<specific_decl_iterator<FieldDecl>>; |
4004 | |
4005 | field_range fields() const { return field_range(field_begin(), field_end()); } |
4006 | field_iterator field_begin() const; |
4007 | |
4008 | field_iterator field_end() const { |
4009 | return field_iterator(decl_iterator()); |
4010 | } |
4011 | |
4012 | // Whether there are any fields (non-static data members) in this record. |
4013 | bool field_empty() const { |
4014 | return field_begin() == field_end(); |
4015 | } |
4016 | |
4017 | /// Note that the definition of this type is now complete. |
4018 | virtual void completeDefinition(); |
4019 | |
4020 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4021 | static bool classofKind(Kind K) { |
4022 | return K >= firstRecord && K <= lastRecord; |
4023 | } |
4024 | |
4025 | /// Get whether or not this is an ms_struct which can |
4026 | /// be turned on with an attribute, pragma, or -mms-bitfields |
4027 | /// commandline option. |
4028 | bool isMsStruct(const ASTContext &C) const; |
4029 | |
4030 | /// Whether we are allowed to insert extra padding between fields. |
4031 | /// These padding are added to help AddressSanitizer detect |
4032 | /// intra-object-overflow bugs. |
4033 | bool mayInsertExtraPadding(bool EmitRemark = false) const; |
4034 | |
4035 | /// Finds the first data member which has a name. |
4036 | /// nullptr is returned if no named data member exists. |
4037 | const FieldDecl *findFirstNamedDataMember() const; |
4038 | |
4039 | private: |
4040 | /// Deserialize just the fields. |
4041 | void LoadFieldsFromExternalStorage() const; |
4042 | }; |
4043 | |
4044 | class FileScopeAsmDecl : public Decl { |
4045 | StringLiteral *AsmString; |
4046 | SourceLocation RParenLoc; |
4047 | |
4048 | FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, |
4049 | SourceLocation StartL, SourceLocation EndL) |
4050 | : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} |
4051 | |
4052 | virtual void anchor(); |
4053 | |
4054 | public: |
4055 | static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, |
4056 | StringLiteral *Str, SourceLocation AsmLoc, |
4057 | SourceLocation RParenLoc); |
4058 | |
4059 | static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4060 | |
4061 | SourceLocation getAsmLoc() const { return getLocation(); } |
4062 | SourceLocation getRParenLoc() const { return RParenLoc; } |
4063 | void setRParenLoc(SourceLocation L) { RParenLoc = L; } |
4064 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
4065 | return SourceRange(getAsmLoc(), getRParenLoc()); |
4066 | } |
4067 | |
4068 | const StringLiteral *getAsmString() const { return AsmString; } |
4069 | StringLiteral *getAsmString() { return AsmString; } |
4070 | void setAsmString(StringLiteral *Asm) { AsmString = Asm; } |
4071 | |
4072 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4073 | static bool classofKind(Kind K) { return K == FileScopeAsm; } |
4074 | }; |
4075 | |
4076 | /// Represents a block literal declaration, which is like an |
4077 | /// unnamed FunctionDecl. For example: |
4078 | /// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } |
4079 | class BlockDecl : public Decl, public DeclContext { |
4080 | // This class stores some data in DeclContext::BlockDeclBits |
4081 | // to save some space. Use the provided accessors to access it. |
4082 | public: |
4083 | /// A class which contains all the information about a particular |
4084 | /// captured value. |
4085 | class Capture { |
4086 | enum { |
4087 | flag_isByRef = 0x1, |
4088 | flag_isNested = 0x2 |
4089 | }; |
4090 | |
4091 | /// The variable being captured. |
4092 | llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags; |
4093 | |
4094 | /// The copy expression, expressed in terms of a DeclRef (or |
4095 | /// BlockDeclRef) to the captured variable. Only required if the |
4096 | /// variable has a C++ class type. |
4097 | Expr *CopyExpr; |
4098 | |
4099 | public: |
4100 | Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) |
4101 | : VariableAndFlags(variable, |
4102 | (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), |
4103 | CopyExpr(copy) {} |
4104 | |
4105 | /// The variable being captured. |
4106 | VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } |
4107 | |
4108 | /// Whether this is a "by ref" capture, i.e. a capture of a __block |
4109 | /// variable. |
4110 | bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } |
4111 | |
4112 | bool isEscapingByref() const { |
4113 | return getVariable()->isEscapingByref(); |
4114 | } |
4115 | |
4116 | bool isNonEscapingByref() const { |
4117 | return getVariable()->isNonEscapingByref(); |
4118 | } |
4119 | |
4120 | /// Whether this is a nested capture, i.e. the variable captured |
4121 | /// is not from outside the immediately enclosing function/block. |
4122 | bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } |
4123 | |
4124 | bool hasCopyExpr() const { return CopyExpr != nullptr; } |
4125 | Expr *getCopyExpr() const { return CopyExpr; } |
4126 | void setCopyExpr(Expr *e) { CopyExpr = e; } |
4127 | }; |
4128 | |
4129 | private: |
4130 | /// A new[]'d array of pointers to ParmVarDecls for the formal |
4131 | /// parameters of this function. This is null if a prototype or if there are |
4132 | /// no formals. |
4133 | ParmVarDecl **ParamInfo = nullptr; |
4134 | unsigned NumParams = 0; |
4135 | |
4136 | Stmt *Body = nullptr; |
4137 | TypeSourceInfo *SignatureAsWritten = nullptr; |
4138 | |
4139 | const Capture *Captures = nullptr; |
4140 | unsigned NumCaptures = 0; |
4141 | |
4142 | unsigned ManglingNumber = 0; |
4143 | Decl *ManglingContextDecl = nullptr; |
4144 | |
4145 | protected: |
4146 | BlockDecl(DeclContext *DC, SourceLocation CaretLoc); |
4147 | |
4148 | public: |
4149 | static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); |
4150 | static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4151 | |
4152 | SourceLocation getCaretLocation() const { return getLocation(); } |
4153 | |
4154 | bool isVariadic() const { return BlockDeclBits.IsVariadic; } |
4155 | void setIsVariadic(bool value) { BlockDeclBits.IsVariadic = value; } |
4156 | |
4157 | CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } |
4158 | Stmt *getBody() const override { return (Stmt*) Body; } |
4159 | void setBody(CompoundStmt *B) { Body = (Stmt*) B; } |
4160 | |
4161 | void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } |
4162 | TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } |
4163 | |
4164 | // ArrayRef access to formal parameters. |
4165 | ArrayRef<ParmVarDecl *> parameters() const { |
4166 | return {ParamInfo, getNumParams()}; |
4167 | } |
4168 | MutableArrayRef<ParmVarDecl *> parameters() { |
4169 | return {ParamInfo, getNumParams()}; |
4170 | } |
4171 | |
4172 | // Iterator access to formal parameters. |
4173 | using param_iterator = MutableArrayRef<ParmVarDecl *>::iterator; |
4174 | using param_const_iterator = ArrayRef<ParmVarDecl *>::const_iterator; |
4175 | |
4176 | bool param_empty() const { return parameters().empty(); } |
4177 | param_iterator param_begin() { return parameters().begin(); } |
4178 | param_iterator param_end() { return parameters().end(); } |
4179 | param_const_iterator param_begin() const { return parameters().begin(); } |
4180 | param_const_iterator param_end() const { return parameters().end(); } |
4181 | size_t param_size() const { return parameters().size(); } |
4182 | |
4183 | unsigned getNumParams() const { return NumParams; } |
4184 | |
4185 | const ParmVarDecl *getParamDecl(unsigned i) const { |
4186 | assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast <void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4186, __PRETTY_FUNCTION__)); |
4187 | return ParamInfo[i]; |
4188 | } |
4189 | ParmVarDecl *getParamDecl(unsigned i) { |
4190 | assert(i < getNumParams() && "Illegal param #")((i < getNumParams() && "Illegal param #") ? static_cast <void> (0) : __assert_fail ("i < getNumParams() && \"Illegal param #\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4190, __PRETTY_FUNCTION__)); |
4191 | return ParamInfo[i]; |
4192 | } |
4193 | |
4194 | void setParams(ArrayRef<ParmVarDecl *> NewParamInfo); |
4195 | |
4196 | /// True if this block (or its nested blocks) captures |
4197 | /// anything of local storage from its enclosing scopes. |
4198 | bool hasCaptures() const { return NumCaptures || capturesCXXThis(); } |
4199 | |
4200 | /// Returns the number of captured variables. |
4201 | /// Does not include an entry for 'this'. |
4202 | unsigned getNumCaptures() const { return NumCaptures; } |
4203 | |
4204 | using capture_const_iterator = ArrayRef<Capture>::const_iterator; |
4205 | |
4206 | ArrayRef<Capture> captures() const { return {Captures, NumCaptures}; } |
4207 | |
4208 | capture_const_iterator capture_begin() const { return captures().begin(); } |
4209 | capture_const_iterator capture_end() const { return captures().end(); } |
4210 | |
4211 | bool capturesCXXThis() const { return BlockDeclBits.CapturesCXXThis; } |
4212 | void setCapturesCXXThis(bool B = true) { BlockDeclBits.CapturesCXXThis = B; } |
4213 | |
4214 | bool blockMissingReturnType() const { |
4215 | return BlockDeclBits.BlockMissingReturnType; |
4216 | } |
4217 | |
4218 | void setBlockMissingReturnType(bool val = true) { |
4219 | BlockDeclBits.BlockMissingReturnType = val; |
4220 | } |
4221 | |
4222 | bool isConversionFromLambda() const { |
4223 | return BlockDeclBits.IsConversionFromLambda; |
4224 | } |
4225 | |
4226 | void setIsConversionFromLambda(bool val = true) { |
4227 | BlockDeclBits.IsConversionFromLambda = val; |
4228 | } |
4229 | |
4230 | bool doesNotEscape() const { return BlockDeclBits.DoesNotEscape; } |
4231 | void setDoesNotEscape(bool B = true) { BlockDeclBits.DoesNotEscape = B; } |
4232 | |
4233 | bool canAvoidCopyToHeap() const { |
4234 | return BlockDeclBits.CanAvoidCopyToHeap; |
4235 | } |
4236 | void setCanAvoidCopyToHeap(bool B = true) { |
4237 | BlockDeclBits.CanAvoidCopyToHeap = B; |
4238 | } |
4239 | |
4240 | bool capturesVariable(const VarDecl *var) const; |
4241 | |
4242 | void setCaptures(ASTContext &Context, ArrayRef<Capture> Captures, |
4243 | bool CapturesCXXThis); |
4244 | |
4245 | unsigned getBlockManglingNumber() const { return ManglingNumber; } |
4246 | |
4247 | Decl *getBlockManglingContextDecl() const { return ManglingContextDecl; } |
4248 | |
4249 | void setBlockMangling(unsigned Number, Decl *Ctx) { |
4250 | ManglingNumber = Number; |
4251 | ManglingContextDecl = Ctx; |
4252 | } |
4253 | |
4254 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
4255 | |
4256 | // Implement isa/cast/dyncast/etc. |
4257 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4258 | static bool classofKind(Kind K) { return K == Block; } |
4259 | static DeclContext *castToDeclContext(const BlockDecl *D) { |
4260 | return static_cast<DeclContext *>(const_cast<BlockDecl*>(D)); |
4261 | } |
4262 | static BlockDecl *castFromDeclContext(const DeclContext *DC) { |
4263 | return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC)); |
4264 | } |
4265 | }; |
4266 | |
4267 | /// Represents the body of a CapturedStmt, and serves as its DeclContext. |
4268 | class CapturedDecl final |
4269 | : public Decl, |
4270 | public DeclContext, |
4271 | private llvm::TrailingObjects<CapturedDecl, ImplicitParamDecl *> { |
4272 | protected: |
4273 | size_t numTrailingObjects(OverloadToken<ImplicitParamDecl>) { |
4274 | return NumParams; |
4275 | } |
4276 | |
4277 | private: |
4278 | /// The number of parameters to the outlined function. |
4279 | unsigned NumParams; |
4280 | |
4281 | /// The position of context parameter in list of parameters. |
4282 | unsigned ContextParam; |
4283 | |
4284 | /// The body of the outlined function. |
4285 | llvm::PointerIntPair<Stmt *, 1, bool> BodyAndNothrow; |
4286 | |
4287 | explicit CapturedDecl(DeclContext *DC, unsigned NumParams); |
4288 | |
4289 | ImplicitParamDecl *const *getParams() const { |
4290 | return getTrailingObjects<ImplicitParamDecl *>(); |
4291 | } |
4292 | |
4293 | ImplicitParamDecl **getParams() { |
4294 | return getTrailingObjects<ImplicitParamDecl *>(); |
4295 | } |
4296 | |
4297 | public: |
4298 | friend class ASTDeclReader; |
4299 | friend class ASTDeclWriter; |
4300 | friend TrailingObjects; |
4301 | |
4302 | static CapturedDecl *Create(ASTContext &C, DeclContext *DC, |
4303 | unsigned NumParams); |
4304 | static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
4305 | unsigned NumParams); |
4306 | |
4307 | Stmt *getBody() const override; |
4308 | void setBody(Stmt *B); |
4309 | |
4310 | bool isNothrow() const; |
4311 | void setNothrow(bool Nothrow = true); |
4312 | |
4313 | unsigned getNumParams() const { return NumParams; } |
4314 | |
4315 | ImplicitParamDecl *getParam(unsigned i) const { |
4316 | assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4316, __PRETTY_FUNCTION__)); |
4317 | return getParams()[i]; |
4318 | } |
4319 | void setParam(unsigned i, ImplicitParamDecl *P) { |
4320 | assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4320, __PRETTY_FUNCTION__)); |
4321 | getParams()[i] = P; |
4322 | } |
4323 | |
4324 | // ArrayRef interface to parameters. |
4325 | ArrayRef<ImplicitParamDecl *> parameters() const { |
4326 | return {getParams(), getNumParams()}; |
4327 | } |
4328 | MutableArrayRef<ImplicitParamDecl *> parameters() { |
4329 | return {getParams(), getNumParams()}; |
4330 | } |
4331 | |
4332 | /// Retrieve the parameter containing captured variables. |
4333 | ImplicitParamDecl *getContextParam() const { |
4334 | assert(ContextParam < NumParams)((ContextParam < NumParams) ? static_cast<void> (0) : __assert_fail ("ContextParam < NumParams", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4334, __PRETTY_FUNCTION__)); |
4335 | return getParam(ContextParam); |
4336 | } |
4337 | void setContextParam(unsigned i, ImplicitParamDecl *P) { |
4338 | assert(i < NumParams)((i < NumParams) ? static_cast<void> (0) : __assert_fail ("i < NumParams", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4338, __PRETTY_FUNCTION__)); |
4339 | ContextParam = i; |
4340 | setParam(i, P); |
4341 | } |
4342 | unsigned getContextParamPosition() const { return ContextParam; } |
4343 | |
4344 | using param_iterator = ImplicitParamDecl *const *; |
4345 | using param_range = llvm::iterator_range<param_iterator>; |
4346 | |
4347 | /// Retrieve an iterator pointing to the first parameter decl. |
4348 | param_iterator param_begin() const { return getParams(); } |
4349 | /// Retrieve an iterator one past the last parameter decl. |
4350 | param_iterator param_end() const { return getParams() + NumParams; } |
4351 | |
4352 | // Implement isa/cast/dyncast/etc. |
4353 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4354 | static bool classofKind(Kind K) { return K == Captured; } |
4355 | static DeclContext *castToDeclContext(const CapturedDecl *D) { |
4356 | return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D)); |
4357 | } |
4358 | static CapturedDecl *castFromDeclContext(const DeclContext *DC) { |
4359 | return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC)); |
4360 | } |
4361 | }; |
4362 | |
4363 | /// Describes a module import declaration, which makes the contents |
4364 | /// of the named module visible in the current translation unit. |
4365 | /// |
4366 | /// An import declaration imports the named module (or submodule). For example: |
4367 | /// \code |
4368 | /// @import std.vector; |
4369 | /// \endcode |
4370 | /// |
4371 | /// Import declarations can also be implicitly generated from |
4372 | /// \#include/\#import directives. |
4373 | class ImportDecl final : public Decl, |
4374 | llvm::TrailingObjects<ImportDecl, SourceLocation> { |
4375 | friend class ASTContext; |
4376 | friend class ASTDeclReader; |
4377 | friend class ASTReader; |
4378 | friend TrailingObjects; |
4379 | |
4380 | /// The imported module. |
4381 | Module *ImportedModule = nullptr; |
4382 | |
4383 | /// The next import in the list of imports local to the translation |
4384 | /// unit being parsed (not loaded from an AST file). |
4385 | /// |
4386 | /// Includes a bit that indicates whether we have source-location information |
4387 | /// for each identifier in the module name. |
4388 | /// |
4389 | /// When the bit is false, we only have a single source location for the |
4390 | /// end of the import declaration. |
4391 | llvm::PointerIntPair<ImportDecl *, 1, bool> NextLocalImportAndComplete; |
4392 | |
4393 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
4394 | ArrayRef<SourceLocation> IdentifierLocs); |
4395 | |
4396 | ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, |
4397 | SourceLocation EndLoc); |
4398 | |
4399 | ImportDecl(EmptyShell Empty) : Decl(Import, Empty) {} |
4400 | |
4401 | bool isImportComplete() const { return NextLocalImportAndComplete.getInt(); } |
4402 | |
4403 | void setImportComplete(bool C) { NextLocalImportAndComplete.setInt(C); } |
4404 | |
4405 | /// The next import in the list of imports local to the translation |
4406 | /// unit being parsed (not loaded from an AST file). |
4407 | ImportDecl *getNextLocalImport() const { |
4408 | return NextLocalImportAndComplete.getPointer(); |
4409 | } |
4410 | |
4411 | void setNextLocalImport(ImportDecl *Import) { |
4412 | NextLocalImportAndComplete.setPointer(Import); |
4413 | } |
4414 | |
4415 | public: |
4416 | /// Create a new module import declaration. |
4417 | static ImportDecl *Create(ASTContext &C, DeclContext *DC, |
4418 | SourceLocation StartLoc, Module *Imported, |
4419 | ArrayRef<SourceLocation> IdentifierLocs); |
4420 | |
4421 | /// Create a new module import declaration for an implicitly-generated |
4422 | /// import. |
4423 | static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, |
4424 | SourceLocation StartLoc, Module *Imported, |
4425 | SourceLocation EndLoc); |
4426 | |
4427 | /// Create a new, deserialized module import declaration. |
4428 | static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, |
4429 | unsigned NumLocations); |
4430 | |
4431 | /// Retrieve the module that was imported by the import declaration. |
4432 | Module *getImportedModule() const { return ImportedModule; } |
4433 | |
4434 | /// Retrieves the locations of each of the identifiers that make up |
4435 | /// the complete module name in the import declaration. |
4436 | /// |
4437 | /// This will return an empty array if the locations of the individual |
4438 | /// identifiers aren't available. |
4439 | ArrayRef<SourceLocation> getIdentifierLocs() const; |
4440 | |
4441 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)); |
4442 | |
4443 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4444 | static bool classofKind(Kind K) { return K == Import; } |
4445 | }; |
4446 | |
4447 | /// Represents a C++ Modules TS module export declaration. |
4448 | /// |
4449 | /// For example: |
4450 | /// \code |
4451 | /// export void foo(); |
4452 | /// \endcode |
4453 | class ExportDecl final : public Decl, public DeclContext { |
4454 | virtual void anchor(); |
4455 | |
4456 | private: |
4457 | friend class ASTDeclReader; |
4458 | |
4459 | /// The source location for the right brace (if valid). |
4460 | SourceLocation RBraceLoc; |
4461 | |
4462 | ExportDecl(DeclContext *DC, SourceLocation ExportLoc) |
4463 | : Decl(Export, DC, ExportLoc), DeclContext(Export), |
4464 | RBraceLoc(SourceLocation()) {} |
4465 | |
4466 | public: |
4467 | static ExportDecl *Create(ASTContext &C, DeclContext *DC, |
4468 | SourceLocation ExportLoc); |
4469 | static ExportDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4470 | |
4471 | SourceLocation getExportLoc() const { return getLocation(); } |
4472 | SourceLocation getRBraceLoc() const { return RBraceLoc; } |
4473 | void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } |
4474 | |
4475 | bool hasBraces() const { return RBraceLoc.isValid(); } |
4476 | |
4477 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
4478 | if (hasBraces()) |
4479 | return RBraceLoc; |
4480 | // No braces: get the end location of the (only) declaration in context |
4481 | // (if present). |
4482 | return decls_empty() ? getLocation() : decls_begin()->getEndLoc(); |
4483 | } |
4484 | |
4485 | SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) { |
4486 | return SourceRange(getLocation(), getEndLoc()); |
4487 | } |
4488 | |
4489 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4490 | static bool classofKind(Kind K) { return K == Export; } |
4491 | static DeclContext *castToDeclContext(const ExportDecl *D) { |
4492 | return static_cast<DeclContext *>(const_cast<ExportDecl*>(D)); |
4493 | } |
4494 | static ExportDecl *castFromDeclContext(const DeclContext *DC) { |
4495 | return static_cast<ExportDecl *>(const_cast<DeclContext*>(DC)); |
4496 | } |
4497 | }; |
4498 | |
4499 | /// Represents an empty-declaration. |
4500 | class EmptyDecl : public Decl { |
4501 | EmptyDecl(DeclContext *DC, SourceLocation L) : Decl(Empty, DC, L) {} |
4502 | |
4503 | virtual void anchor(); |
4504 | |
4505 | public: |
4506 | static EmptyDecl *Create(ASTContext &C, DeclContext *DC, |
4507 | SourceLocation L); |
4508 | static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID); |
4509 | |
4510 | static bool classof(const Decl *D) { return classofKind(D->getKind()); } |
4511 | static bool classofKind(Kind K) { return K == Empty; } |
4512 | }; |
4513 | |
4514 | /// Insertion operator for diagnostics. This allows sending NamedDecl's |
4515 | /// into a diagnostic with <<. |
4516 | inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, |
4517 | const NamedDecl* ND) { |
4518 | DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4519 | DiagnosticsEngine::ak_nameddecl); |
4520 | return DB; |
4521 | } |
4522 | inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, |
4523 | const NamedDecl* ND) { |
4524 | PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND), |
4525 | DiagnosticsEngine::ak_nameddecl); |
4526 | return PD; |
4527 | } |
4528 | |
4529 | template<typename decl_type> |
4530 | void Redeclarable<decl_type>::setPreviousDecl(decl_type *PrevDecl) { |
4531 | // Note: This routine is implemented here because we need both NamedDecl |
4532 | // and Redeclarable to be defined. |
4533 | assert(RedeclLink.isFirst() &&((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4534, __PRETTY_FUNCTION__)) |
4534 | "setPreviousDecl on a decl already in a redeclaration chain")((RedeclLink.isFirst() && "setPreviousDecl on a decl already in a redeclaration chain" ) ? static_cast<void> (0) : __assert_fail ("RedeclLink.isFirst() && \"setPreviousDecl on a decl already in a redeclaration chain\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4534, __PRETTY_FUNCTION__)); |
4535 | |
4536 | if (PrevDecl) { |
4537 | // Point to previous. Make sure that this is actually the most recent |
4538 | // redeclaration, or we can build invalid chains. If the most recent |
4539 | // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. |
4540 | First = PrevDecl->getFirstDecl(); |
4541 | assert(First->RedeclLink.isFirst() && "Expected first")((First->RedeclLink.isFirst() && "Expected first") ? static_cast<void> (0) : __assert_fail ("First->RedeclLink.isFirst() && \"Expected first\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4541, __PRETTY_FUNCTION__)); |
4542 | decl_type *MostRecent = First->getNextRedeclaration(); |
4543 | RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent)); |
4544 | |
4545 | // If the declaration was previously visible, a redeclaration of it remains |
4546 | // visible even if it wouldn't be visible by itself. |
4547 | static_cast<decl_type*>(this)->IdentifierNamespace |= |
4548 | MostRecent->getIdentifierNamespace() & |
4549 | (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type); |
4550 | } else { |
4551 | // Make this first. |
4552 | First = static_cast<decl_type*>(this); |
4553 | } |
4554 | |
4555 | // First one will point to this one as latest. |
4556 | First->RedeclLink.setLatest(static_cast<decl_type*>(this)); |
4557 | |
4558 | assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) ||((!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))-> isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4559, __PRETTY_FUNCTION__)) |
4559 | cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid())((!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))-> isLinkageValid()) ? static_cast<void> (0) : __assert_fail ("!isa<NamedDecl>(static_cast<decl_type*>(this)) || cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Decl.h" , 4559, __PRETTY_FUNCTION__)); |
4560 | } |
4561 | |
4562 | // Inline function definitions. |
4563 | |
4564 | /// Check if the given decl is complete. |
4565 | /// |
4566 | /// We use this function to break a cycle between the inline definitions in |
4567 | /// Type.h and Decl.h. |
4568 | inline bool IsEnumDeclComplete(EnumDecl *ED) { |
4569 | return ED->isComplete(); |
4570 | } |
4571 | |
4572 | /// Check if the given decl is scoped. |
4573 | /// |
4574 | /// We use this function to break a cycle between the inline definitions in |
4575 | /// Type.h and Decl.h. |
4576 | inline bool IsEnumDeclScoped(EnumDecl *ED) { |
4577 | return ED->isScoped(); |
4578 | } |
4579 | |
4580 | /// OpenMP variants are mangled early based on their OpenMP context selector. |
4581 | /// The new name looks likes this: |
4582 | /// <name> + OpenMPVariantManglingSeparatorStr + <mangled OpenMP context> |
4583 | static constexpr StringRef getOpenMPVariantManglingSeparatorStr() { |
4584 | return "$ompvariant"; |
4585 | } |
4586 | |
4587 | } // namespace clang |
4588 | |
4589 | #endif // LLVM_CLANG_AST_DECL_H |
1 | //===- DeclBase.h - Base Classes for representing 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 | // This file defines the Decl and DeclContext interfaces. |
10 | // |
11 | //===----------------------------------------------------------------------===// |
12 | |
13 | #ifndef LLVM_CLANG_AST_DECLBASE_H |
14 | #define LLVM_CLANG_AST_DECLBASE_H |
15 | |
16 | #include "clang/AST/ASTDumperUtils.h" |
17 | #include "clang/AST/AttrIterator.h" |
18 | #include "clang/AST/DeclarationName.h" |
19 | #include "clang/Basic/IdentifierTable.h" |
20 | #include "clang/Basic/LLVM.h" |
21 | #include "clang/Basic/SourceLocation.h" |
22 | #include "clang/Basic/Specifiers.h" |
23 | #include "llvm/ADT/ArrayRef.h" |
24 | #include "llvm/ADT/PointerIntPair.h" |
25 | #include "llvm/ADT/PointerUnion.h" |
26 | #include "llvm/ADT/iterator.h" |
27 | #include "llvm/ADT/iterator_range.h" |
28 | #include "llvm/Support/Casting.h" |
29 | #include "llvm/Support/Compiler.h" |
30 | #include "llvm/Support/PrettyStackTrace.h" |
31 | #include "llvm/Support/VersionTuple.h" |
32 | #include <algorithm> |
33 | #include <cassert> |
34 | #include <cstddef> |
35 | #include <iterator> |
36 | #include <string> |
37 | #include <type_traits> |
38 | #include <utility> |
39 | |
40 | namespace clang { |
41 | |
42 | class ASTContext; |
43 | class ASTMutationListener; |
44 | class Attr; |
45 | class BlockDecl; |
46 | class DeclContext; |
47 | class ExternalSourceSymbolAttr; |
48 | class FunctionDecl; |
49 | class FunctionType; |
50 | class IdentifierInfo; |
51 | enum Linkage : unsigned char; |
52 | class LinkageSpecDecl; |
53 | class Module; |
54 | class NamedDecl; |
55 | class ObjCCategoryDecl; |
56 | class ObjCCategoryImplDecl; |
57 | class ObjCContainerDecl; |
58 | class ObjCImplDecl; |
59 | class ObjCImplementationDecl; |
60 | class ObjCInterfaceDecl; |
61 | class ObjCMethodDecl; |
62 | class ObjCProtocolDecl; |
63 | struct PrintingPolicy; |
64 | class RecordDecl; |
65 | class SourceManager; |
66 | class Stmt; |
67 | class StoredDeclsMap; |
68 | class TemplateDecl; |
69 | class TemplateParameterList; |
70 | class TranslationUnitDecl; |
71 | class UsingDirectiveDecl; |
72 | |
73 | /// Captures the result of checking the availability of a |
74 | /// declaration. |
75 | enum AvailabilityResult { |
76 | AR_Available = 0, |
77 | AR_NotYetIntroduced, |
78 | AR_Deprecated, |
79 | AR_Unavailable |
80 | }; |
81 | |
82 | /// Decl - This represents one declaration (or definition), e.g. a variable, |
83 | /// typedef, function, struct, etc. |
84 | /// |
85 | /// Note: There are objects tacked on before the *beginning* of Decl |
86 | /// (and its subclasses) in its Decl::operator new(). Proper alignment |
87 | /// of all subclasses (not requiring more than the alignment of Decl) is |
88 | /// asserted in DeclBase.cpp. |
89 | class alignas(8) Decl { |
90 | public: |
91 | /// Lists the kind of concrete classes of Decl. |
92 | enum Kind { |
93 | #define DECL(DERIVED, BASE) DERIVED, |
94 | #define ABSTRACT_DECL(DECL) |
95 | #define DECL_RANGE(BASE, START, END) \ |
96 | first##BASE = START, last##BASE = END, |
97 | #define LAST_DECL_RANGE(BASE, START, END) \ |
98 | first##BASE = START, last##BASE = END |
99 | #include "clang/AST/DeclNodes.inc" |
100 | }; |
101 | |
102 | /// A placeholder type used to construct an empty shell of a |
103 | /// decl-derived type that will be filled in later (e.g., by some |
104 | /// deserialization method). |
105 | struct EmptyShell {}; |
106 | |
107 | /// IdentifierNamespace - The different namespaces in which |
108 | /// declarations may appear. According to C99 6.2.3, there are |
109 | /// four namespaces, labels, tags, members and ordinary |
110 | /// identifiers. C++ describes lookup completely differently: |
111 | /// certain lookups merely "ignore" certain kinds of declarations, |
112 | /// usually based on whether the declaration is of a type, etc. |
113 | /// |
114 | /// These are meant as bitmasks, so that searches in |
115 | /// C++ can look into the "tag" namespace during ordinary lookup. |
116 | /// |
117 | /// Decl currently provides 15 bits of IDNS bits. |
118 | enum IdentifierNamespace { |
119 | /// Labels, declared with 'x:' and referenced with 'goto x'. |
120 | IDNS_Label = 0x0001, |
121 | |
122 | /// Tags, declared with 'struct foo;' and referenced with |
123 | /// 'struct foo'. All tags are also types. This is what |
124 | /// elaborated-type-specifiers look for in C. |
125 | /// This also contains names that conflict with tags in the |
126 | /// same scope but that are otherwise ordinary names (non-type |
127 | /// template parameters and indirect field declarations). |
128 | IDNS_Tag = 0x0002, |
129 | |
130 | /// Types, declared with 'struct foo', typedefs, etc. |
131 | /// This is what elaborated-type-specifiers look for in C++, |
132 | /// but note that it's ill-formed to find a non-tag. |
133 | IDNS_Type = 0x0004, |
134 | |
135 | /// Members, declared with object declarations within tag |
136 | /// definitions. In C, these can only be found by "qualified" |
137 | /// lookup in member expressions. In C++, they're found by |
138 | /// normal lookup. |
139 | IDNS_Member = 0x0008, |
140 | |
141 | /// Namespaces, declared with 'namespace foo {}'. |
142 | /// Lookup for nested-name-specifiers find these. |
143 | IDNS_Namespace = 0x0010, |
144 | |
145 | /// Ordinary names. In C, everything that's not a label, tag, |
146 | /// member, or function-local extern ends up here. |
147 | IDNS_Ordinary = 0x0020, |
148 | |
149 | /// Objective C \@protocol. |
150 | IDNS_ObjCProtocol = 0x0040, |
151 | |
152 | /// This declaration is a friend function. A friend function |
153 | /// declaration is always in this namespace but may also be in |
154 | /// IDNS_Ordinary if it was previously declared. |
155 | IDNS_OrdinaryFriend = 0x0080, |
156 | |
157 | /// This declaration is a friend class. A friend class |
158 | /// declaration is always in this namespace but may also be in |
159 | /// IDNS_Tag|IDNS_Type if it was previously declared. |
160 | IDNS_TagFriend = 0x0100, |
161 | |
162 | /// This declaration is a using declaration. A using declaration |
163 | /// *introduces* a number of other declarations into the current |
164 | /// scope, and those declarations use the IDNS of their targets, |
165 | /// but the actual using declarations go in this namespace. |
166 | IDNS_Using = 0x0200, |
167 | |
168 | /// This declaration is a C++ operator declared in a non-class |
169 | /// context. All such operators are also in IDNS_Ordinary. |
170 | /// C++ lexical operator lookup looks for these. |
171 | IDNS_NonMemberOperator = 0x0400, |
172 | |
173 | /// This declaration is a function-local extern declaration of a |
174 | /// variable or function. This may also be IDNS_Ordinary if it |
175 | /// has been declared outside any function. These act mostly like |
176 | /// invisible friend declarations, but are also visible to unqualified |
177 | /// lookup within the scope of the declaring function. |
178 | IDNS_LocalExtern = 0x0800, |
179 | |
180 | /// This declaration is an OpenMP user defined reduction construction. |
181 | IDNS_OMPReduction = 0x1000, |
182 | |
183 | /// This declaration is an OpenMP user defined mapper. |
184 | IDNS_OMPMapper = 0x2000, |
185 | }; |
186 | |
187 | /// ObjCDeclQualifier - 'Qualifiers' written next to the return and |
188 | /// parameter types in method declarations. Other than remembering |
189 | /// them and mangling them into the method's signature string, these |
190 | /// are ignored by the compiler; they are consumed by certain |
191 | /// remote-messaging frameworks. |
192 | /// |
193 | /// in, inout, and out are mutually exclusive and apply only to |
194 | /// method parameters. bycopy and byref are mutually exclusive and |
195 | /// apply only to method parameters (?). oneway applies only to |
196 | /// results. All of these expect their corresponding parameter to |
197 | /// have a particular type. None of this is currently enforced by |
198 | /// clang. |
199 | /// |
200 | /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier. |
201 | enum ObjCDeclQualifier { |
202 | OBJC_TQ_None = 0x0, |
203 | OBJC_TQ_In = 0x1, |
204 | OBJC_TQ_Inout = 0x2, |
205 | OBJC_TQ_Out = 0x4, |
206 | OBJC_TQ_Bycopy = 0x8, |
207 | OBJC_TQ_Byref = 0x10, |
208 | OBJC_TQ_Oneway = 0x20, |
209 | |
210 | /// The nullability qualifier is set when the nullability of the |
211 | /// result or parameter was expressed via a context-sensitive |
212 | /// keyword. |
213 | OBJC_TQ_CSNullability = 0x40 |
214 | }; |
215 | |
216 | /// The kind of ownership a declaration has, for visibility purposes. |
217 | /// This enumeration is designed such that higher values represent higher |
218 | /// levels of name hiding. |
219 | enum class ModuleOwnershipKind : unsigned { |
220 | /// This declaration is not owned by a module. |
221 | Unowned, |
222 | |
223 | /// This declaration has an owning module, but is globally visible |
224 | /// (typically because its owning module is visible and we know that |
225 | /// modules cannot later become hidden in this compilation). |
226 | /// After serialization and deserialization, this will be converted |
227 | /// to VisibleWhenImported. |
228 | Visible, |
229 | |
230 | /// This declaration has an owning module, and is visible when that |
231 | /// module is imported. |
232 | VisibleWhenImported, |
233 | |
234 | /// This declaration has an owning module, but is only visible to |
235 | /// lookups that occur within that module. |
236 | ModulePrivate |
237 | }; |
238 | |
239 | protected: |
240 | /// The next declaration within the same lexical |
241 | /// DeclContext. These pointers form the linked list that is |
242 | /// traversed via DeclContext's decls_begin()/decls_end(). |
243 | /// |
244 | /// The extra two bits are used for the ModuleOwnershipKind. |
245 | llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits; |
246 | |
247 | private: |
248 | friend class DeclContext; |
249 | |
250 | struct MultipleDC { |
251 | DeclContext *SemanticDC; |
252 | DeclContext *LexicalDC; |
253 | }; |
254 | |
255 | /// DeclCtx - Holds either a DeclContext* or a MultipleDC*. |
256 | /// For declarations that don't contain C++ scope specifiers, it contains |
257 | /// the DeclContext where the Decl was declared. |
258 | /// For declarations with C++ scope specifiers, it contains a MultipleDC* |
259 | /// with the context where it semantically belongs (SemanticDC) and the |
260 | /// context where it was lexically declared (LexicalDC). |
261 | /// e.g.: |
262 | /// |
263 | /// namespace A { |
264 | /// void f(); // SemanticDC == LexicalDC == 'namespace A' |
265 | /// } |
266 | /// void A::f(); // SemanticDC == namespace 'A' |
267 | /// // LexicalDC == global namespace |
268 | llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx; |
269 | |
270 | bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); } |
271 | bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); } |
272 | |
273 | MultipleDC *getMultipleDC() const { |
274 | return DeclCtx.get<MultipleDC*>(); |
275 | } |
276 | |
277 | DeclContext *getSemanticDC() const { |
278 | return DeclCtx.get<DeclContext*>(); |
279 | } |
280 | |
281 | /// Loc - The location of this decl. |
282 | SourceLocation Loc; |
283 | |
284 | /// DeclKind - This indicates which class this is. |
285 | unsigned DeclKind : 7; |
286 | |
287 | /// InvalidDecl - This indicates a semantic error occurred. |
288 | unsigned InvalidDecl : 1; |
289 | |
290 | /// HasAttrs - This indicates whether the decl has attributes or not. |
291 | unsigned HasAttrs : 1; |
292 | |
293 | /// Implicit - Whether this declaration was implicitly generated by |
294 | /// the implementation rather than explicitly written by the user. |
295 | unsigned Implicit : 1; |
296 | |
297 | /// Whether this declaration was "used", meaning that a definition is |
298 | /// required. |
299 | unsigned Used : 1; |
300 | |
301 | /// Whether this declaration was "referenced". |
302 | /// The difference with 'Used' is whether the reference appears in a |
303 | /// evaluated context or not, e.g. functions used in uninstantiated templates |
304 | /// are regarded as "referenced" but not "used". |
305 | unsigned Referenced : 1; |
306 | |
307 | /// Whether this declaration is a top-level declaration (function, |
308 | /// global variable, etc.) that is lexically inside an objc container |
309 | /// definition. |
310 | unsigned TopLevelDeclInObjCContainer : 1; |
311 | |
312 | /// Whether statistic collection is enabled. |
313 | static bool StatisticsEnabled; |
314 | |
315 | protected: |
316 | friend class ASTDeclReader; |
317 | friend class ASTDeclWriter; |
318 | friend class ASTNodeImporter; |
319 | friend class ASTReader; |
320 | friend class CXXClassMemberWrapper; |
321 | friend class LinkageComputer; |
322 | template<typename decl_type> friend class Redeclarable; |
323 | |
324 | /// Access - Used by C++ decls for the access specifier. |
325 | // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum |
326 | unsigned Access : 2; |
327 | |
328 | /// Whether this declaration was loaded from an AST file. |
329 | unsigned FromASTFile : 1; |
330 | |
331 | /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in. |
332 | unsigned IdentifierNamespace : 14; |
333 | |
334 | /// If 0, we have not computed the linkage of this declaration. |
335 | /// Otherwise, it is the linkage + 1. |
336 | mutable unsigned CacheValidAndLinkage : 3; |
337 | |
338 | /// Allocate memory for a deserialized declaration. |
339 | /// |
340 | /// This routine must be used to allocate memory for any declaration that is |
341 | /// deserialized from a module file. |
342 | /// |
343 | /// \param Size The size of the allocated object. |
344 | /// \param Ctx The context in which we will allocate memory. |
345 | /// \param ID The global ID of the deserialized declaration. |
346 | /// \param Extra The amount of extra space to allocate after the object. |
347 | void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID, |
348 | std::size_t Extra = 0); |
349 | |
350 | /// Allocate memory for a non-deserialized declaration. |
351 | void *operator new(std::size_t Size, const ASTContext &Ctx, |
352 | DeclContext *Parent, std::size_t Extra = 0); |
353 | |
354 | private: |
355 | bool AccessDeclContextSanity() const; |
356 | |
357 | /// Get the module ownership kind to use for a local lexical child of \p DC, |
358 | /// which may be either a local or (rarely) an imported declaration. |
359 | static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) { |
360 | if (DC) { |
361 | auto *D = cast<Decl>(DC); |
362 | auto MOK = D->getModuleOwnershipKind(); |
363 | if (MOK != ModuleOwnershipKind::Unowned && |
364 | (!D->isFromASTFile() || D->hasLocalOwningModuleStorage())) |
365 | return MOK; |
366 | // If D is not local and we have no local module storage, then we don't |
367 | // need to track module ownership at all. |
368 | } |
369 | return ModuleOwnershipKind::Unowned; |
370 | } |
371 | |
372 | public: |
373 | Decl() = delete; |
374 | Decl(const Decl&) = delete; |
375 | Decl(Decl &&) = delete; |
376 | Decl &operator=(const Decl&) = delete; |
377 | Decl &operator=(Decl&&) = delete; |
378 | |
379 | protected: |
380 | Decl(Kind DK, DeclContext *DC, SourceLocation L) |
381 | : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)), |
382 | DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false), |
383 | Implicit(false), Used(false), Referenced(false), |
384 | TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0), |
385 | IdentifierNamespace(getIdentifierNamespaceForKind(DK)), |
386 | CacheValidAndLinkage(0) { |
387 | if (StatisticsEnabled) add(DK); |
388 | } |
389 | |
390 | Decl(Kind DK, EmptyShell Empty) |
391 | : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false), |
392 | Used(false), Referenced(false), TopLevelDeclInObjCContainer(false), |
393 | Access(AS_none), FromASTFile(0), |
394 | IdentifierNamespace(getIdentifierNamespaceForKind(DK)), |
395 | CacheValidAndLinkage(0) { |
396 | if (StatisticsEnabled) add(DK); |
397 | } |
398 | |
399 | virtual ~Decl(); |
400 | |
401 | /// Update a potentially out-of-date declaration. |
402 | void updateOutOfDate(IdentifierInfo &II) const; |
403 | |
404 | Linkage getCachedLinkage() const { |
405 | return Linkage(CacheValidAndLinkage - 1); |
406 | } |
407 | |
408 | void setCachedLinkage(Linkage L) const { |
409 | CacheValidAndLinkage = L + 1; |
410 | } |
411 | |
412 | bool hasCachedLinkage() const { |
413 | return CacheValidAndLinkage; |
414 | } |
415 | |
416 | public: |
417 | /// Source range that this declaration covers. |
418 | virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { |
419 | return SourceRange(getLocation(), getLocation()); |
420 | } |
421 | |
422 | SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { |
423 | return getSourceRange().getBegin(); |
424 | } |
425 | |
426 | SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { |
427 | return getSourceRange().getEnd(); |
428 | } |
429 | |
430 | SourceLocation getLocation() const { return Loc; } |
431 | void setLocation(SourceLocation L) { Loc = L; } |
432 | |
433 | Kind getKind() const { return static_cast<Kind>(DeclKind); } |
434 | const char *getDeclKindName() const; |
435 | |
436 | Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); } |
437 | const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();} |
438 | |
439 | DeclContext *getDeclContext() { |
440 | if (isInSemaDC()) |
441 | return getSemanticDC(); |
442 | return getMultipleDC()->SemanticDC; |
443 | } |
444 | const DeclContext *getDeclContext() const { |
445 | return const_cast<Decl*>(this)->getDeclContext(); |
446 | } |
447 | |
448 | /// Find the innermost non-closure ancestor of this declaration, |
449 | /// walking up through blocks, lambdas, etc. If that ancestor is |
450 | /// not a code context (!isFunctionOrMethod()), returns null. |
451 | /// |
452 | /// A declaration may be its own non-closure context. |
453 | Decl *getNonClosureContext(); |
454 | const Decl *getNonClosureContext() const { |
455 | return const_cast<Decl*>(this)->getNonClosureContext(); |
456 | } |
457 | |
458 | TranslationUnitDecl *getTranslationUnitDecl(); |
459 | const TranslationUnitDecl *getTranslationUnitDecl() const { |
460 | return const_cast<Decl*>(this)->getTranslationUnitDecl(); |
461 | } |
462 | |
463 | bool isInAnonymousNamespace() const; |
464 | |
465 | bool isInStdNamespace() const; |
466 | |
467 | ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__)); |
468 | |
469 | /// Helper to get the language options from the ASTContext. |
470 | /// Defined out of line to avoid depending on ASTContext.h. |
471 | const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__)); |
472 | |
473 | void setAccess(AccessSpecifier AS) { |
474 | Access = AS; |
475 | assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 475, __PRETTY_FUNCTION__)); |
476 | } |
477 | |
478 | AccessSpecifier getAccess() const { |
479 | assert(AccessDeclContextSanity())((AccessDeclContextSanity()) ? static_cast<void> (0) : __assert_fail ("AccessDeclContextSanity()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 479, __PRETTY_FUNCTION__)); |
480 | return AccessSpecifier(Access); |
481 | } |
482 | |
483 | /// Retrieve the access specifier for this declaration, even though |
484 | /// it may not yet have been properly set. |
485 | AccessSpecifier getAccessUnsafe() const { |
486 | return AccessSpecifier(Access); |
487 | } |
488 | |
489 | bool hasAttrs() const { return HasAttrs; } |
490 | |
491 | void setAttrs(const AttrVec& Attrs) { |
492 | return setAttrsImpl(Attrs, getASTContext()); |
493 | } |
494 | |
495 | AttrVec &getAttrs() { |
496 | return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs()); |
497 | } |
498 | |
499 | const AttrVec &getAttrs() const; |
500 | void dropAttrs(); |
501 | void addAttr(Attr *A); |
502 | |
503 | using attr_iterator = AttrVec::const_iterator; |
504 | using attr_range = llvm::iterator_range<attr_iterator>; |
505 | |
506 | attr_range attrs() const { |
507 | return attr_range(attr_begin(), attr_end()); |
508 | } |
509 | |
510 | attr_iterator attr_begin() const { |
511 | return hasAttrs() ? getAttrs().begin() : nullptr; |
512 | } |
513 | attr_iterator attr_end() const { |
514 | return hasAttrs() ? getAttrs().end() : nullptr; |
515 | } |
516 | |
517 | template <typename T> |
518 | void dropAttr() { |
519 | if (!HasAttrs) return; |
520 | |
521 | AttrVec &Vec = getAttrs(); |
522 | llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); }); |
523 | |
524 | if (Vec.empty()) |
525 | HasAttrs = false; |
526 | } |
527 | |
528 | template <typename T> |
529 | llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const { |
530 | return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>()); |
531 | } |
532 | |
533 | template <typename T> |
534 | specific_attr_iterator<T> specific_attr_begin() const { |
535 | return specific_attr_iterator<T>(attr_begin()); |
536 | } |
537 | |
538 | template <typename T> |
539 | specific_attr_iterator<T> specific_attr_end() const { |
540 | return specific_attr_iterator<T>(attr_end()); |
541 | } |
542 | |
543 | template<typename T> T *getAttr() const { |
544 | return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr; |
545 | } |
546 | |
547 | template<typename T> bool hasAttr() const { |
548 | return hasAttrs() && hasSpecificAttr<T>(getAttrs()); |
549 | } |
550 | |
551 | /// getMaxAlignment - return the maximum alignment specified by attributes |
552 | /// on this decl, 0 if there are none. |
553 | unsigned getMaxAlignment() const; |
554 | |
555 | /// setInvalidDecl - Indicates the Decl had a semantic error. This |
556 | /// allows for graceful error recovery. |
557 | void setInvalidDecl(bool Invalid = true); |
558 | bool isInvalidDecl() const { return (bool) InvalidDecl; } |
559 | |
560 | /// isImplicit - Indicates whether the declaration was implicitly |
561 | /// generated by the implementation. If false, this declaration |
562 | /// was written explicitly in the source code. |
563 | bool isImplicit() const { return Implicit; } |
564 | void setImplicit(bool I = true) { Implicit = I; } |
565 | |
566 | /// Whether *any* (re-)declaration of the entity was used, meaning that |
567 | /// a definition is required. |
568 | /// |
569 | /// \param CheckUsedAttr When true, also consider the "used" attribute |
570 | /// (in addition to the "used" bit set by \c setUsed()) when determining |
571 | /// whether the function is used. |
572 | bool isUsed(bool CheckUsedAttr = true) const; |
573 | |
574 | /// Set whether the declaration is used, in the sense of odr-use. |
575 | /// |
576 | /// This should only be used immediately after creating a declaration. |
577 | /// It intentionally doesn't notify any listeners. |
578 | void setIsUsed() { getCanonicalDecl()->Used = true; } |
579 | |
580 | /// Mark the declaration used, in the sense of odr-use. |
581 | /// |
582 | /// This notifies any mutation listeners in addition to setting a bit |
583 | /// indicating the declaration is used. |
584 | void markUsed(ASTContext &C); |
585 | |
586 | /// Whether any declaration of this entity was referenced. |
587 | bool isReferenced() const; |
588 | |
589 | /// Whether this declaration was referenced. This should not be relied |
590 | /// upon for anything other than debugging. |
591 | bool isThisDeclarationReferenced() const { return Referenced; } |
592 | |
593 | void setReferenced(bool R = true) { Referenced = R; } |
594 | |
595 | /// Whether this declaration is a top-level declaration (function, |
596 | /// global variable, etc.) that is lexically inside an objc container |
597 | /// definition. |
598 | bool isTopLevelDeclInObjCContainer() const { |
599 | return TopLevelDeclInObjCContainer; |
600 | } |
601 | |
602 | void setTopLevelDeclInObjCContainer(bool V = true) { |
603 | TopLevelDeclInObjCContainer = V; |
604 | } |
605 | |
606 | /// Looks on this and related declarations for an applicable |
607 | /// external source symbol attribute. |
608 | ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const; |
609 | |
610 | /// Whether this declaration was marked as being private to the |
611 | /// module in which it was defined. |
612 | bool isModulePrivate() const { |
613 | return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate; |
614 | } |
615 | |
616 | /// Return true if this declaration has an attribute which acts as |
617 | /// definition of the entity, such as 'alias' or 'ifunc'. |
618 | bool hasDefiningAttr() const; |
619 | |
620 | /// Return this declaration's defining attribute if it has one. |
621 | const Attr *getDefiningAttr() const; |
622 | |
623 | protected: |
624 | /// Specify that this declaration was marked as being private |
625 | /// to the module in which it was defined. |
626 | void setModulePrivate() { |
627 | // The module-private specifier has no effect on unowned declarations. |
628 | // FIXME: We should track this in some way for source fidelity. |
629 | if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned) |
630 | return; |
631 | setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate); |
632 | } |
633 | |
634 | public: |
635 | /// Set the FromASTFile flag. This indicates that this declaration |
636 | /// was deserialized and not parsed from source code and enables |
637 | /// features such as module ownership information. |
638 | void setFromASTFile() { |
639 | FromASTFile = true; |
640 | } |
641 | |
642 | /// Set the owning module ID. This may only be called for |
643 | /// deserialized Decls. |
644 | void setOwningModuleID(unsigned ID) { |
645 | assert(isFromASTFile() && "Only works on a deserialized declaration")((isFromASTFile() && "Only works on a deserialized declaration" ) ? static_cast<void> (0) : __assert_fail ("isFromASTFile() && \"Only works on a deserialized declaration\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 645, __PRETTY_FUNCTION__)); |
646 | *((unsigned*)this - 2) = ID; |
647 | } |
648 | |
649 | public: |
650 | /// Determine the availability of the given declaration. |
651 | /// |
652 | /// This routine will determine the most restrictive availability of |
653 | /// the given declaration (e.g., preferring 'unavailable' to |
654 | /// 'deprecated'). |
655 | /// |
656 | /// \param Message If non-NULL and the result is not \c |
657 | /// AR_Available, will be set to a (possibly empty) message |
658 | /// describing why the declaration has not been introduced, is |
659 | /// deprecated, or is unavailable. |
660 | /// |
661 | /// \param EnclosingVersion The version to compare with. If empty, assume the |
662 | /// deployment target version. |
663 | /// |
664 | /// \param RealizedPlatform If non-NULL and the availability result is found |
665 | /// in an available attribute it will set to the platform which is written in |
666 | /// the available attribute. |
667 | AvailabilityResult |
668 | getAvailability(std::string *Message = nullptr, |
669 | VersionTuple EnclosingVersion = VersionTuple(), |
670 | StringRef *RealizedPlatform = nullptr) const; |
671 | |
672 | /// Retrieve the version of the target platform in which this |
673 | /// declaration was introduced. |
674 | /// |
675 | /// \returns An empty version tuple if this declaration has no 'introduced' |
676 | /// availability attributes, or the version tuple that's specified in the |
677 | /// attribute otherwise. |
678 | VersionTuple getVersionIntroduced() const; |
679 | |
680 | /// Determine whether this declaration is marked 'deprecated'. |
681 | /// |
682 | /// \param Message If non-NULL and the declaration is deprecated, |
683 | /// this will be set to the message describing why the declaration |
684 | /// was deprecated (which may be empty). |
685 | bool isDeprecated(std::string *Message = nullptr) const { |
686 | return getAvailability(Message) == AR_Deprecated; |
687 | } |
688 | |
689 | /// Determine whether this declaration is marked 'unavailable'. |
690 | /// |
691 | /// \param Message If non-NULL and the declaration is unavailable, |
692 | /// this will be set to the message describing why the declaration |
693 | /// was made unavailable (which may be empty). |
694 | bool isUnavailable(std::string *Message = nullptr) const { |
695 | return getAvailability(Message) == AR_Unavailable; |
696 | } |
697 | |
698 | /// Determine whether this is a weak-imported symbol. |
699 | /// |
700 | /// Weak-imported symbols are typically marked with the |
701 | /// 'weak_import' attribute, but may also be marked with an |
702 | /// 'availability' attribute where we're targing a platform prior to |
703 | /// the introduction of this feature. |
704 | bool isWeakImported() const; |
705 | |
706 | /// Determines whether this symbol can be weak-imported, |
707 | /// e.g., whether it would be well-formed to add the weak_import |
708 | /// attribute. |
709 | /// |
710 | /// \param IsDefinition Set to \c true to indicate that this |
711 | /// declaration cannot be weak-imported because it has a definition. |
712 | bool canBeWeakImported(bool &IsDefinition) const; |
713 | |
714 | /// Determine whether this declaration came from an AST file (such as |
715 | /// a precompiled header or module) rather than having been parsed. |
716 | bool isFromASTFile() const { return FromASTFile; } |
717 | |
718 | /// Retrieve the global declaration ID associated with this |
719 | /// declaration, which specifies where this Decl was loaded from. |
720 | unsigned getGlobalID() const { |
721 | if (isFromASTFile()) |
722 | return *((const unsigned*)this - 1); |
723 | return 0; |
724 | } |
725 | |
726 | /// Retrieve the global ID of the module that owns this particular |
727 | /// declaration. |
728 | unsigned getOwningModuleID() const { |
729 | if (isFromASTFile()) |
730 | return *((const unsigned*)this - 2); |
731 | return 0; |
732 | } |
733 | |
734 | private: |
735 | Module *getOwningModuleSlow() const; |
736 | |
737 | protected: |
738 | bool hasLocalOwningModuleStorage() const; |
739 | |
740 | public: |
741 | /// Get the imported owning module, if this decl is from an imported |
742 | /// (non-local) module. |
743 | Module *getImportedOwningModule() const { |
744 | if (!isFromASTFile() || !hasOwningModule()) |
745 | return nullptr; |
746 | |
747 | return getOwningModuleSlow(); |
748 | } |
749 | |
750 | /// Get the local owning module, if known. Returns nullptr if owner is |
751 | /// not yet known or declaration is not from a module. |
752 | Module *getLocalOwningModule() const { |
753 | if (isFromASTFile() || !hasOwningModule()) |
754 | return nullptr; |
755 | |
756 | assert(hasLocalOwningModuleStorage() &&((hasLocalOwningModuleStorage() && "owned local decl but no local module storage" ) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 757, __PRETTY_FUNCTION__)) |
757 | "owned local decl but no local module storage")((hasLocalOwningModuleStorage() && "owned local decl but no local module storage" ) ? static_cast<void> (0) : __assert_fail ("hasLocalOwningModuleStorage() && \"owned local decl but no local module storage\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 757, __PRETTY_FUNCTION__)); |
758 | return reinterpret_cast<Module *const *>(this)[-1]; |
759 | } |
760 | void setLocalOwningModule(Module *M) { |
761 | assert(!isFromASTFile() && hasOwningModule() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage () && "should not have a cached owning module") ? static_cast <void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 763, __PRETTY_FUNCTION__)) |
762 | hasLocalOwningModuleStorage() &&((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage () && "should not have a cached owning module") ? static_cast <void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 763, __PRETTY_FUNCTION__)) |
763 | "should not have a cached owning module")((!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage () && "should not have a cached owning module") ? static_cast <void> (0) : __assert_fail ("!isFromASTFile() && hasOwningModule() && hasLocalOwningModuleStorage() && \"should not have a cached owning module\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 763, __PRETTY_FUNCTION__)); |
764 | reinterpret_cast<Module **>(this)[-1] = M; |
765 | } |
766 | |
767 | /// Is this declaration owned by some module? |
768 | bool hasOwningModule() const { |
769 | return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned; |
770 | } |
771 | |
772 | /// Get the module that owns this declaration (for visibility purposes). |
773 | Module *getOwningModule() const { |
774 | return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule(); |
775 | } |
776 | |
777 | /// Get the module that owns this declaration for linkage purposes. |
778 | /// There only ever is such a module under the C++ Modules TS. |
779 | /// |
780 | /// \param IgnoreLinkage Ignore the linkage of the entity; assume that |
781 | /// all declarations in a global module fragment are unowned. |
782 | Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const; |
783 | |
784 | /// Determine whether this declaration is definitely visible to name lookup, |
785 | /// independent of whether the owning module is visible. |
786 | /// Note: The declaration may be visible even if this returns \c false if the |
787 | /// owning module is visible within the query context. This is a low-level |
788 | /// helper function; most code should be calling Sema::isVisible() instead. |
789 | bool isUnconditionallyVisible() const { |
790 | return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible; |
791 | } |
792 | |
793 | /// Set that this declaration is globally visible, even if it came from a |
794 | /// module that is not visible. |
795 | void setVisibleDespiteOwningModule() { |
796 | if (!isUnconditionallyVisible()) |
797 | setModuleOwnershipKind(ModuleOwnershipKind::Visible); |
798 | } |
799 | |
800 | /// Get the kind of module ownership for this declaration. |
801 | ModuleOwnershipKind getModuleOwnershipKind() const { |
802 | return NextInContextAndBits.getInt(); |
803 | } |
804 | |
805 | /// Set whether this declaration is hidden from name lookup. |
806 | void setModuleOwnershipKind(ModuleOwnershipKind MOK) { |
807 | assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile () && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 810, __PRETTY_FUNCTION__)) |
808 | MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile () && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 810, __PRETTY_FUNCTION__)) |
809 | !hasLocalOwningModuleStorage()) &&((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile () && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 810, __PRETTY_FUNCTION__)) |
810 | "no storage available for owning module for this declaration")((!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile () && !hasLocalOwningModuleStorage()) && "no storage available for owning module for this declaration" ) ? static_cast<void> (0) : __assert_fail ("!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned && MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() && !hasLocalOwningModuleStorage()) && \"no storage available for owning module for this declaration\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 810, __PRETTY_FUNCTION__)); |
811 | NextInContextAndBits.setInt(MOK); |
812 | } |
813 | |
814 | unsigned getIdentifierNamespace() const { |
815 | return IdentifierNamespace; |
816 | } |
817 | |
818 | bool isInIdentifierNamespace(unsigned NS) const { |
819 | return getIdentifierNamespace() & NS; |
820 | } |
821 | |
822 | static unsigned getIdentifierNamespaceForKind(Kind DK); |
823 | |
824 | bool hasTagIdentifierNamespace() const { |
825 | return isTagIdentifierNamespace(getIdentifierNamespace()); |
826 | } |
827 | |
828 | static bool isTagIdentifierNamespace(unsigned NS) { |
829 | // TagDecls have Tag and Type set and may also have TagFriend. |
830 | return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type); |
831 | } |
832 | |
833 | /// getLexicalDeclContext - The declaration context where this Decl was |
834 | /// lexically declared (LexicalDC). May be different from |
835 | /// getDeclContext() (SemanticDC). |
836 | /// e.g.: |
837 | /// |
838 | /// namespace A { |
839 | /// void f(); // SemanticDC == LexicalDC == 'namespace A' |
840 | /// } |
841 | /// void A::f(); // SemanticDC == namespace 'A' |
842 | /// // LexicalDC == global namespace |
843 | DeclContext *getLexicalDeclContext() { |
844 | if (isInSemaDC()) |
845 | return getSemanticDC(); |
846 | return getMultipleDC()->LexicalDC; |
847 | } |
848 | const DeclContext *getLexicalDeclContext() const { |
849 | return const_cast<Decl*>(this)->getLexicalDeclContext(); |
850 | } |
851 | |
852 | /// Determine whether this declaration is declared out of line (outside its |
853 | /// semantic context). |
854 | virtual bool isOutOfLine() const; |
855 | |
856 | /// setDeclContext - Set both the semantic and lexical DeclContext |
857 | /// to DC. |
858 | void setDeclContext(DeclContext *DC); |
859 | |
860 | void setLexicalDeclContext(DeclContext *DC); |
861 | |
862 | /// Determine whether this declaration is a templated entity (whether it is |
863 | // within the scope of a template parameter). |
864 | bool isTemplated() const; |
865 | |
866 | /// Determine the number of levels of template parameter surrounding this |
867 | /// declaration. |
868 | unsigned getTemplateDepth() const; |
869 | |
870 | /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this |
871 | /// scoped decl is defined outside the current function or method. This is |
872 | /// roughly global variables and functions, but also handles enums (which |
873 | /// could be defined inside or outside a function etc). |
874 | bool isDefinedOutsideFunctionOrMethod() const { |
875 | return getParentFunctionOrMethod() == nullptr; |
876 | } |
877 | |
878 | /// Determine whether a substitution into this declaration would occur as |
879 | /// part of a substitution into a dependent local scope. Such a substitution |
880 | /// transitively substitutes into all constructs nested within this |
881 | /// declaration. |
882 | /// |
883 | /// This recognizes non-defining declarations as well as members of local |
884 | /// classes and lambdas: |
885 | /// \code |
886 | /// template<typename T> void foo() { void bar(); } |
887 | /// template<typename T> void foo2() { class ABC { void bar(); }; } |
888 | /// template<typename T> inline int x = [](){ return 0; }(); |
889 | /// \endcode |
890 | bool isInLocalScopeForInstantiation() const; |
891 | |
892 | /// If this decl is defined inside a function/method/block it returns |
893 | /// the corresponding DeclContext, otherwise it returns null. |
894 | const DeclContext *getParentFunctionOrMethod() const; |
895 | DeclContext *getParentFunctionOrMethod() { |
896 | return const_cast<DeclContext*>( |
897 | const_cast<const Decl*>(this)->getParentFunctionOrMethod()); |
898 | } |
899 | |
900 | /// Retrieves the "canonical" declaration of the given declaration. |
901 | virtual Decl *getCanonicalDecl() { return this; } |
902 | const Decl *getCanonicalDecl() const { |
903 | return const_cast<Decl*>(this)->getCanonicalDecl(); |
904 | } |
905 | |
906 | /// Whether this particular Decl is a canonical one. |
907 | bool isCanonicalDecl() const { return getCanonicalDecl() == this; } |
908 | |
909 | protected: |
910 | /// Returns the next redeclaration or itself if this is the only decl. |
911 | /// |
912 | /// Decl subclasses that can be redeclared should override this method so that |
913 | /// Decl::redecl_iterator can iterate over them. |
914 | virtual Decl *getNextRedeclarationImpl() { return this; } |
915 | |
916 | /// Implementation of getPreviousDecl(), to be overridden by any |
917 | /// subclass that has a redeclaration chain. |
918 | virtual Decl *getPreviousDeclImpl() { return nullptr; } |
919 | |
920 | /// Implementation of getMostRecentDecl(), to be overridden by any |
921 | /// subclass that has a redeclaration chain. |
922 | virtual Decl *getMostRecentDeclImpl() { return this; } |
923 | |
924 | public: |
925 | /// Iterates through all the redeclarations of the same decl. |
926 | class redecl_iterator { |
927 | /// Current - The current declaration. |
928 | Decl *Current = nullptr; |
929 | Decl *Starter; |
930 | |
931 | public: |
932 | using value_type = Decl *; |
933 | using reference = const value_type &; |
934 | using pointer = const value_type *; |
935 | using iterator_category = std::forward_iterator_tag; |
936 | using difference_type = std::ptrdiff_t; |
937 | |
938 | redecl_iterator() = default; |
939 | explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {} |
940 | |
941 | reference operator*() const { return Current; } |
942 | value_type operator->() const { return Current; } |
943 | |
944 | redecl_iterator& operator++() { |
945 | assert(Current && "Advancing while iterator has reached end")((Current && "Advancing while iterator has reached end" ) ? static_cast<void> (0) : __assert_fail ("Current && \"Advancing while iterator has reached end\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 945, __PRETTY_FUNCTION__)); |
946 | // Get either previous decl or latest decl. |
947 | Decl *Next = Current->getNextRedeclarationImpl(); |
948 | assert(Next && "Should return next redeclaration or itself, never null!")((Next && "Should return next redeclaration or itself, never null!" ) ? static_cast<void> (0) : __assert_fail ("Next && \"Should return next redeclaration or itself, never null!\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 948, __PRETTY_FUNCTION__)); |
949 | Current = (Next != Starter) ? Next : nullptr; |
950 | return *this; |
951 | } |
952 | |
953 | redecl_iterator operator++(int) { |
954 | redecl_iterator tmp(*this); |
955 | ++(*this); |
956 | return tmp; |
957 | } |
958 | |
959 | friend bool operator==(redecl_iterator x, redecl_iterator y) { |
960 | return x.Current == y.Current; |
961 | } |
962 | |
963 | friend bool operator!=(redecl_iterator x, redecl_iterator y) { |
964 | return x.Current != y.Current; |
965 | } |
966 | }; |
967 | |
968 | using redecl_range = llvm::iterator_range<redecl_iterator>; |
969 | |
970 | /// Returns an iterator range for all the redeclarations of the same |
971 | /// decl. It will iterate at least once (when this decl is the only one). |
972 | redecl_range redecls() const { |
973 | return redecl_range(redecls_begin(), redecls_end()); |
974 | } |
975 | |
976 | redecl_iterator redecls_begin() const { |
977 | return redecl_iterator(const_cast<Decl *>(this)); |
978 | } |
979 | |
980 | redecl_iterator redecls_end() const { return redecl_iterator(); } |
981 | |
982 | /// Retrieve the previous declaration that declares the same entity |
983 | /// as this declaration, or NULL if there is no previous declaration. |
984 | Decl *getPreviousDecl() { return getPreviousDeclImpl(); } |
985 | |
986 | /// Retrieve the previous declaration that declares the same entity |
987 | /// as this declaration, or NULL if there is no previous declaration. |
988 | const Decl *getPreviousDecl() const { |
989 | return const_cast<Decl *>(this)->getPreviousDeclImpl(); |
990 | } |
991 | |
992 | /// True if this is the first declaration in its redeclaration chain. |
993 | bool isFirstDecl() const { |
994 | return getPreviousDecl() == nullptr; |
995 | } |
996 | |
997 | /// Retrieve the most recent declaration that declares the same entity |
998 | /// as this declaration (which may be this declaration). |
999 | Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); } |
1000 | |
1001 | /// Retrieve the most recent declaration that declares the same entity |
1002 | /// as this declaration (which may be this declaration). |
1003 | const Decl *getMostRecentDecl() const { |
1004 | return const_cast<Decl *>(this)->getMostRecentDeclImpl(); |
1005 | } |
1006 | |
1007 | /// getBody - If this Decl represents a declaration for a body of code, |
1008 | /// such as a function or method definition, this method returns the |
1009 | /// top-level Stmt* of that body. Otherwise this method returns null. |
1010 | virtual Stmt* getBody() const { return nullptr; } |
1011 | |
1012 | /// Returns true if this \c Decl represents a declaration for a body of |
1013 | /// code, such as a function or method definition. |
1014 | /// Note that \c hasBody can also return true if any redeclaration of this |
1015 | /// \c Decl represents a declaration for a body of code. |
1016 | virtual bool hasBody() const { return getBody() != nullptr; } |
1017 | |
1018 | /// getBodyRBrace - Gets the right brace of the body, if a body exists. |
1019 | /// This works whether the body is a CompoundStmt or a CXXTryStmt. |
1020 | SourceLocation getBodyRBrace() const; |
1021 | |
1022 | // global temp stats (until we have a per-module visitor) |
1023 | static void add(Kind k); |
1024 | static void EnableStatistics(); |
1025 | static void PrintStats(); |
1026 | |
1027 | /// isTemplateParameter - Determines whether this declaration is a |
1028 | /// template parameter. |
1029 | bool isTemplateParameter() const; |
1030 | |
1031 | /// isTemplateParameter - Determines whether this declaration is a |
1032 | /// template parameter pack. |
1033 | bool isTemplateParameterPack() const; |
1034 | |
1035 | /// Whether this declaration is a parameter pack. |
1036 | bool isParameterPack() const; |
1037 | |
1038 | /// returns true if this declaration is a template |
1039 | bool isTemplateDecl() const; |
1040 | |
1041 | /// Whether this declaration is a function or function template. |
1042 | bool isFunctionOrFunctionTemplate() const { |
1043 | return (DeclKind >= Decl::firstFunction && |
1044 | DeclKind <= Decl::lastFunction) || |
1045 | DeclKind == FunctionTemplate; |
1046 | } |
1047 | |
1048 | /// If this is a declaration that describes some template, this |
1049 | /// method returns that template declaration. |
1050 | /// |
1051 | /// Note that this returns nullptr for partial specializations, because they |
1052 | /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle |
1053 | /// those cases. |
1054 | TemplateDecl *getDescribedTemplate() const; |
1055 | |
1056 | /// If this is a declaration that describes some template or partial |
1057 | /// specialization, this returns the corresponding template parameter list. |
1058 | const TemplateParameterList *getDescribedTemplateParams() const; |
1059 | |
1060 | /// Returns the function itself, or the templated function if this is a |
1061 | /// function template. |
1062 | FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__)); |
1063 | |
1064 | const FunctionDecl *getAsFunction() const { |
1065 | return const_cast<Decl *>(this)->getAsFunction(); |
1066 | } |
1067 | |
1068 | /// Changes the namespace of this declaration to reflect that it's |
1069 | /// a function-local extern declaration. |
1070 | /// |
1071 | /// These declarations appear in the lexical context of the extern |
1072 | /// declaration, but in the semantic context of the enclosing namespace |
1073 | /// scope. |
1074 | void setLocalExternDecl() { |
1075 | Decl *Prev = getPreviousDecl(); |
1076 | IdentifierNamespace &= ~IDNS_Ordinary; |
1077 | |
1078 | // It's OK for the declaration to still have the "invisible friend" flag or |
1079 | // the "conflicts with tag declarations in this scope" flag for the outer |
1080 | // scope. |
1081 | assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag )) == 0 && "namespace is not ordinary") ? static_cast <void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1082, __PRETTY_FUNCTION__)) |
1082 | "namespace is not ordinary")(((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag )) == 0 && "namespace is not ordinary") ? static_cast <void> (0) : __assert_fail ("(IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 && \"namespace is not ordinary\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1082, __PRETTY_FUNCTION__)); |
1083 | |
1084 | IdentifierNamespace |= IDNS_LocalExtern; |
1085 | if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary) |
1086 | IdentifierNamespace |= IDNS_Ordinary; |
1087 | } |
1088 | |
1089 | /// Determine whether this is a block-scope declaration with linkage. |
1090 | /// This will either be a local variable declaration declared 'extern', or a |
1091 | /// local function declaration. |
1092 | bool isLocalExternDecl() { |
1093 | return IdentifierNamespace & IDNS_LocalExtern; |
1094 | } |
1095 | |
1096 | /// Changes the namespace of this declaration to reflect that it's |
1097 | /// the object of a friend declaration. |
1098 | /// |
1099 | /// These declarations appear in the lexical context of the friending |
1100 | /// class, but in the semantic context of the actual entity. This property |
1101 | /// applies only to a specific decl object; other redeclarations of the |
1102 | /// same entity may not (and probably don't) share this property. |
1103 | void setObjectOfFriendDecl(bool PerformFriendInjection = false) { |
1104 | unsigned OldNS = IdentifierNamespace; |
1105 | assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag" ) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1108, __PRETTY_FUNCTION__)) |
1106 | IDNS_TagFriend | IDNS_OrdinaryFriend |(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag" ) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1108, __PRETTY_FUNCTION__)) |
1107 | IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag" ) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1108, __PRETTY_FUNCTION__)) |
1108 | "namespace includes neither ordinary nor tag")(((OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && "namespace includes neither ordinary nor tag" ) ? static_cast<void> (0) : __assert_fail ("(OldNS & (IDNS_Tag | IDNS_Ordinary | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes neither ordinary nor tag\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1108, __PRETTY_FUNCTION__)); |
1109 | assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes other than ordinary or tag" ) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1112, __PRETTY_FUNCTION__)) |
1110 | IDNS_TagFriend | IDNS_OrdinaryFriend |((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes other than ordinary or tag" ) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1112, __PRETTY_FUNCTION__)) |
1111 | IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes other than ordinary or tag" ) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1112, __PRETTY_FUNCTION__)) |
1112 | "namespace includes other than ordinary or tag")((!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator )) && "namespace includes other than ordinary or tag" ) ? static_cast<void> (0) : __assert_fail ("!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type | IDNS_TagFriend | IDNS_OrdinaryFriend | IDNS_LocalExtern | IDNS_NonMemberOperator)) && \"namespace includes other than ordinary or tag\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1112, __PRETTY_FUNCTION__)); |
1113 | |
1114 | Decl *Prev = getPreviousDecl(); |
1115 | IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type); |
1116 | |
1117 | if (OldNS & (IDNS_Tag | IDNS_TagFriend)) { |
1118 | IdentifierNamespace |= IDNS_TagFriend; |
1119 | if (PerformFriendInjection || |
1120 | (Prev && Prev->getIdentifierNamespace() & IDNS_Tag)) |
1121 | IdentifierNamespace |= IDNS_Tag | IDNS_Type; |
1122 | } |
1123 | |
1124 | if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend | |
1125 | IDNS_LocalExtern | IDNS_NonMemberOperator)) { |
1126 | IdentifierNamespace |= IDNS_OrdinaryFriend; |
1127 | if (PerformFriendInjection || |
1128 | (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)) |
1129 | IdentifierNamespace |= IDNS_Ordinary; |
1130 | } |
1131 | } |
1132 | |
1133 | enum FriendObjectKind { |
1134 | FOK_None, ///< Not a friend object. |
1135 | FOK_Declared, ///< A friend of a previously-declared entity. |
1136 | FOK_Undeclared ///< A friend of a previously-undeclared entity. |
1137 | }; |
1138 | |
1139 | /// Determines whether this declaration is the object of a |
1140 | /// friend declaration and, if so, what kind. |
1141 | /// |
1142 | /// There is currently no direct way to find the associated FriendDecl. |
1143 | FriendObjectKind getFriendObjectKind() const { |
1144 | unsigned mask = |
1145 | (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend)); |
1146 | if (!mask) return FOK_None; |
1147 | return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared |
1148 | : FOK_Undeclared); |
1149 | } |
1150 | |
1151 | /// Specifies that this declaration is a C++ overloaded non-member. |
1152 | void setNonMemberOperator() { |
1153 | assert(getKind() == Function || getKind() == FunctionTemplate)((getKind() == Function || getKind() == FunctionTemplate) ? static_cast <void> (0) : __assert_fail ("getKind() == Function || getKind() == FunctionTemplate" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1153, __PRETTY_FUNCTION__)); |
1154 | assert((IdentifierNamespace & IDNS_Ordinary) &&(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace" ) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1155, __PRETTY_FUNCTION__)) |
1155 | "visible non-member operators should be in ordinary namespace")(((IdentifierNamespace & IDNS_Ordinary) && "visible non-member operators should be in ordinary namespace" ) ? static_cast<void> (0) : __assert_fail ("(IdentifierNamespace & IDNS_Ordinary) && \"visible non-member operators should be in ordinary namespace\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 1155, __PRETTY_FUNCTION__)); |
1156 | IdentifierNamespace |= IDNS_NonMemberOperator; |
1157 | } |
1158 | |
1159 | static bool classofKind(Kind K) { return true; } |
1160 | static DeclContext *castToDeclContext(const Decl *); |
1161 | static Decl *castFromDeclContext(const DeclContext *); |
1162 | |
1163 | void print(raw_ostream &Out, unsigned Indentation = 0, |
1164 | bool PrintInstantiation = false) const; |
1165 | void print(raw_ostream &Out, const PrintingPolicy &Policy, |
1166 | unsigned Indentation = 0, bool PrintInstantiation = false) const; |
1167 | static void printGroup(Decl** Begin, unsigned NumDecls, |
1168 | raw_ostream &Out, const PrintingPolicy &Policy, |
1169 | unsigned Indentation = 0); |
1170 | |
1171 | // Debuggers don't usually respect default arguments. |
1172 | void dump() const; |
1173 | |
1174 | // Same as dump(), but forces color printing. |
1175 | void dumpColor() const; |
1176 | |
1177 | void dump(raw_ostream &Out, bool Deserialize = false, |
1178 | ASTDumpOutputFormat OutputFormat = ADOF_Default) const; |
1179 | |
1180 | /// \return Unique reproducible object identifier |
1181 | int64_t getID() const; |
1182 | |
1183 | /// Looks through the Decl's underlying type to extract a FunctionType |
1184 | /// when possible. Will return null if the type underlying the Decl does not |
1185 | /// have a FunctionType. |
1186 | const FunctionType *getFunctionType(bool BlocksToo = true) const; |
1187 | |
1188 | private: |
1189 | void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx); |
1190 | void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC, |
1191 | ASTContext &Ctx); |
1192 | |
1193 | protected: |
1194 | ASTMutationListener *getASTMutationListener() const; |
1195 | }; |
1196 | |
1197 | /// Determine whether two declarations declare the same entity. |
1198 | inline bool declaresSameEntity(const Decl *D1, const Decl *D2) { |
1199 | if (!D1 || !D2) |
1200 | return false; |
1201 | |
1202 | if (D1 == D2) |
1203 | return true; |
1204 | |
1205 | return D1->getCanonicalDecl() == D2->getCanonicalDecl(); |
1206 | } |
1207 | |
1208 | /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when |
1209 | /// doing something to a specific decl. |
1210 | class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry { |
1211 | const Decl *TheDecl; |
1212 | SourceLocation Loc; |
1213 | SourceManager &SM; |
1214 | const char *Message; |
1215 | |
1216 | public: |
1217 | PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L, |
1218 | SourceManager &sm, const char *Msg) |
1219 | : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {} |
1220 | |
1221 | void print(raw_ostream &OS) const override; |
1222 | }; |
1223 | |
1224 | /// The results of name lookup within a DeclContext. This is either a |
1225 | /// single result (with no stable storage) or a collection of results (with |
1226 | /// stable storage provided by the lookup table). |
1227 | class DeclContextLookupResult { |
1228 | using ResultTy = ArrayRef<NamedDecl *>; |
1229 | |
1230 | ResultTy Result; |
1231 | |
1232 | // If there is only one lookup result, it would be invalidated by |
1233 | // reallocations of the name table, so store it separately. |
1234 | NamedDecl *Single = nullptr; |
1235 | |
1236 | static NamedDecl *const SingleElementDummyList; |
1237 | |
1238 | public: |
1239 | DeclContextLookupResult() = default; |
1240 | DeclContextLookupResult(ArrayRef<NamedDecl *> Result) |
1241 | : Result(Result) {} |
1242 | DeclContextLookupResult(NamedDecl *Single) |
1243 | : Result(SingleElementDummyList), Single(Single) {} |
1244 | |
1245 | class iterator; |
1246 | |
1247 | using IteratorBase = |
1248 | llvm::iterator_adaptor_base<iterator, ResultTy::iterator, |
1249 | std::random_access_iterator_tag, |
1250 | NamedDecl *const>; |
1251 | |
1252 | class iterator : public IteratorBase { |
1253 | value_type SingleElement; |
1254 | |
1255 | public: |
1256 | explicit iterator(pointer Pos, value_type Single = nullptr) |
1257 | : IteratorBase(Pos), SingleElement(Single) {} |
1258 | |
1259 | reference operator*() const { |
1260 | return SingleElement ? SingleElement : IteratorBase::operator*(); |
1261 | } |
1262 | }; |
1263 | |
1264 | using const_iterator = iterator; |
1265 | using pointer = iterator::pointer; |
1266 | using reference = iterator::reference; |
1267 | |
1268 | iterator begin() const { return iterator(Result.begin(), Single); } |
1269 | iterator end() const { return iterator(Result.end(), Single); } |
1270 | |
1271 | bool empty() const { return Result.empty(); } |
1272 | pointer data() const { return Single ? &Single : Result.data(); } |
1273 | size_t size() const { return Single ? 1 : Result.size(); } |
1274 | reference front() const { return Single ? Single : Result.front(); } |
1275 | reference back() const { return Single ? Single : Result.back(); } |
1276 | reference operator[](size_t N) const { return Single ? Single : Result[N]; } |
1277 | |
1278 | // FIXME: Remove this from the interface |
1279 | DeclContextLookupResult slice(size_t N) const { |
1280 | DeclContextLookupResult Sliced = Result.slice(N); |
1281 | Sliced.Single = Single; |
1282 | return Sliced; |
1283 | } |
1284 | }; |
1285 | |
1286 | /// DeclContext - This is used only as base class of specific decl types that |
1287 | /// can act as declaration contexts. These decls are (only the top classes |
1288 | /// that directly derive from DeclContext are mentioned, not their subclasses): |
1289 | /// |
1290 | /// TranslationUnitDecl |
1291 | /// ExternCContext |
1292 | /// NamespaceDecl |
1293 | /// TagDecl |
1294 | /// OMPDeclareReductionDecl |
1295 | /// OMPDeclareMapperDecl |
1296 | /// FunctionDecl |
1297 | /// ObjCMethodDecl |
1298 | /// ObjCContainerDecl |
1299 | /// LinkageSpecDecl |
1300 | /// ExportDecl |
1301 | /// BlockDecl |
1302 | /// CapturedDecl |
1303 | class DeclContext { |
1304 | /// For makeDeclVisibleInContextImpl |
1305 | friend class ASTDeclReader; |
1306 | /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap, |
1307 | /// hasNeedToReconcileExternalVisibleStorage |
1308 | friend class ExternalASTSource; |
1309 | /// For CreateStoredDeclsMap |
1310 | friend class DependentDiagnostic; |
1311 | /// For hasNeedToReconcileExternalVisibleStorage, |
1312 | /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups |
1313 | friend class ASTWriter; |
1314 | |
1315 | // We use uint64_t in the bit-fields below since some bit-fields |
1316 | // cross the unsigned boundary and this breaks the packing. |
1317 | |
1318 | /// Stores the bits used by DeclContext. |
1319 | /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor |
1320 | /// methods in DeclContext should be updated appropriately. |
1321 | class DeclContextBitfields { |
1322 | friend class DeclContext; |
1323 | /// DeclKind - This indicates which class this is. |
1324 | uint64_t DeclKind : 7; |
1325 | |
1326 | /// Whether this declaration context also has some external |
1327 | /// storage that contains additional declarations that are lexically |
1328 | /// part of this context. |
1329 | mutable uint64_t ExternalLexicalStorage : 1; |
1330 | |
1331 | /// Whether this declaration context also has some external |
1332 | /// storage that contains additional declarations that are visible |
1333 | /// in this context. |
1334 | mutable uint64_t ExternalVisibleStorage : 1; |
1335 | |
1336 | /// Whether this declaration context has had externally visible |
1337 | /// storage added since the last lookup. In this case, \c LookupPtr's |
1338 | /// invariant may not hold and needs to be fixed before we perform |
1339 | /// another lookup. |
1340 | mutable uint64_t NeedToReconcileExternalVisibleStorage : 1; |
1341 | |
1342 | /// If \c true, this context may have local lexical declarations |
1343 | /// that are missing from the lookup table. |
1344 | mutable uint64_t HasLazyLocalLexicalLookups : 1; |
1345 | |
1346 | /// If \c true, the external source may have lexical declarations |
1347 | /// that are missing from the lookup table. |
1348 | mutable uint64_t HasLazyExternalLexicalLookups : 1; |
1349 | |
1350 | /// If \c true, lookups should only return identifier from |
1351 | /// DeclContext scope (for example TranslationUnit). Used in |
1352 | /// LookupQualifiedName() |
1353 | mutable uint64_t UseQualifiedLookup : 1; |
1354 | }; |
1355 | |
1356 | /// Number of bits in DeclContextBitfields. |
1357 | enum { NumDeclContextBits = 13 }; |
1358 | |
1359 | /// Stores the bits used by TagDecl. |
1360 | /// If modified NumTagDeclBits and the accessor |
1361 | /// methods in TagDecl should be updated appropriately. |
1362 | class TagDeclBitfields { |
1363 | friend class TagDecl; |
1364 | /// For the bits in DeclContextBitfields |
1365 | uint64_t : NumDeclContextBits; |
1366 | |
1367 | /// The TagKind enum. |
1368 | uint64_t TagDeclKind : 3; |
1369 | |
1370 | /// True if this is a definition ("struct foo {};"), false if it is a |
1371 | /// declaration ("struct foo;"). It is not considered a definition |
1372 | /// until the definition has been fully processed. |
1373 | uint64_t IsCompleteDefinition : 1; |
1374 | |
1375 | /// True if this is currently being defined. |
1376 | uint64_t IsBeingDefined : 1; |
1377 | |
1378 | /// True if this tag declaration is "embedded" (i.e., defined or declared |
1379 | /// for the very first time) in the syntax of a declarator. |
1380 | uint64_t IsEmbeddedInDeclarator : 1; |
1381 | |
1382 | /// True if this tag is free standing, e.g. "struct foo;". |
1383 | uint64_t IsFreeStanding : 1; |
1384 | |
1385 | /// Indicates whether it is possible for declarations of this kind |
1386 | /// to have an out-of-date definition. |
1387 | /// |
1388 | /// This option is only enabled when modules are enabled. |
1389 | uint64_t MayHaveOutOfDateDef : 1; |
1390 | |
1391 | /// Has the full definition of this type been required by a use somewhere in |
1392 | /// the TU. |
1393 | uint64_t IsCompleteDefinitionRequired : 1; |
1394 | }; |
1395 | |
1396 | /// Number of non-inherited bits in TagDeclBitfields. |
1397 | enum { NumTagDeclBits = 9 }; |
1398 | |
1399 | /// Stores the bits used by EnumDecl. |
1400 | /// If modified NumEnumDeclBit and the accessor |
1401 | /// methods in EnumDecl should be updated appropriately. |
1402 | class EnumDeclBitfields { |
1403 | friend class EnumDecl; |
1404 | /// For the bits in DeclContextBitfields. |
1405 | uint64_t : NumDeclContextBits; |
1406 | /// For the bits in TagDeclBitfields. |
1407 | uint64_t : NumTagDeclBits; |
1408 | |
1409 | /// Width in bits required to store all the non-negative |
1410 | /// enumerators of this enum. |
1411 | uint64_t NumPositiveBits : 8; |
1412 | |
1413 | /// Width in bits required to store all the negative |
1414 | /// enumerators of this enum. |
1415 | uint64_t NumNegativeBits : 8; |
1416 | |
1417 | /// True if this tag declaration is a scoped enumeration. Only |
1418 | /// possible in C++11 mode. |
1419 | uint64_t IsScoped : 1; |
1420 | |
1421 | /// If this tag declaration is a scoped enum, |
1422 | /// then this is true if the scoped enum was declared using the class |
1423 | /// tag, false if it was declared with the struct tag. No meaning is |
1424 | /// associated if this tag declaration is not a scoped enum. |
1425 | uint64_t IsScopedUsingClassTag : 1; |
1426 | |
1427 | /// True if this is an enumeration with fixed underlying type. Only |
1428 | /// possible in C++11, Microsoft extensions, or Objective C mode. |
1429 | uint64_t IsFixed : 1; |
1430 | |
1431 | /// True if a valid hash is stored in ODRHash. |
1432 | uint64_t HasODRHash : 1; |
1433 | }; |
1434 | |
1435 | /// Number of non-inherited bits in EnumDeclBitfields. |
1436 | enum { NumEnumDeclBits = 20 }; |
1437 | |
1438 | /// Stores the bits used by RecordDecl. |
1439 | /// If modified NumRecordDeclBits and the accessor |
1440 | /// methods in RecordDecl should be updated appropriately. |
1441 | class RecordDeclBitfields { |
1442 | friend class RecordDecl; |
1443 | /// For the bits in DeclContextBitfields. |
1444 | uint64_t : NumDeclContextBits; |
1445 | /// For the bits in TagDeclBitfields. |
1446 | uint64_t : NumTagDeclBits; |
1447 | |
1448 | /// This is true if this struct ends with a flexible |
1449 | /// array member (e.g. int X[]) or if this union contains a struct that does. |
1450 | /// If so, this cannot be contained in arrays or other structs as a member. |
1451 | uint64_t HasFlexibleArrayMember : 1; |
1452 | |
1453 | /// Whether this is the type of an anonymous struct or union. |
1454 | uint64_t AnonymousStructOrUnion : 1; |
1455 | |
1456 | /// This is true if this struct has at least one member |
1457 | /// containing an Objective-C object pointer type. |
1458 | uint64_t HasObjectMember : 1; |
1459 | |
1460 | /// This is true if struct has at least one member of |
1461 | /// 'volatile' type. |
1462 | uint64_t HasVolatileMember : 1; |
1463 | |
1464 | /// Whether the field declarations of this record have been loaded |
1465 | /// from external storage. To avoid unnecessary deserialization of |
1466 | /// methods/nested types we allow deserialization of just the fields |
1467 | /// when needed. |
1468 | mutable uint64_t LoadedFieldsFromExternalStorage : 1; |
1469 | |
1470 | /// Basic properties of non-trivial C structs. |
1471 | uint64_t NonTrivialToPrimitiveDefaultInitialize : 1; |
1472 | uint64_t NonTrivialToPrimitiveCopy : 1; |
1473 | uint64_t NonTrivialToPrimitiveDestroy : 1; |
1474 | |
1475 | /// The following bits indicate whether this is or contains a C union that |
1476 | /// is non-trivial to default-initialize, destruct, or copy. These bits |
1477 | /// imply the associated basic non-triviality predicates declared above. |
1478 | uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1; |
1479 | uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1; |
1480 | uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1; |
1481 | |
1482 | /// Indicates whether this struct is destroyed in the callee. |
1483 | uint64_t ParamDestroyedInCallee : 1; |
1484 | |
1485 | /// Represents the way this type is passed to a function. |
1486 | uint64_t ArgPassingRestrictions : 2; |
1487 | }; |
1488 | |
1489 | /// Number of non-inherited bits in RecordDeclBitfields. |
1490 | enum { NumRecordDeclBits = 14 }; |
1491 | |
1492 | /// Stores the bits used by OMPDeclareReductionDecl. |
1493 | /// If modified NumOMPDeclareReductionDeclBits and the accessor |
1494 | /// methods in OMPDeclareReductionDecl should be updated appropriately. |
1495 | class OMPDeclareReductionDeclBitfields { |
1496 | friend class OMPDeclareReductionDecl; |
1497 | /// For the bits in DeclContextBitfields |
1498 | uint64_t : NumDeclContextBits; |
1499 | |
1500 | /// Kind of initializer, |
1501 | /// function call or omp_priv<init_expr> initializtion. |
1502 | uint64_t InitializerKind : 2; |
1503 | }; |
1504 | |
1505 | /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields. |
1506 | enum { NumOMPDeclareReductionDeclBits = 2 }; |
1507 | |
1508 | /// Stores the bits used by FunctionDecl. |
1509 | /// If modified NumFunctionDeclBits and the accessor |
1510 | /// methods in FunctionDecl and CXXDeductionGuideDecl |
1511 | /// (for IsCopyDeductionCandidate) should be updated appropriately. |
1512 | class FunctionDeclBitfields { |
1513 | friend class FunctionDecl; |
1514 | /// For IsCopyDeductionCandidate |
1515 | friend class CXXDeductionGuideDecl; |
1516 | /// For the bits in DeclContextBitfields. |
1517 | uint64_t : NumDeclContextBits; |
1518 | |
1519 | uint64_t SClass : 3; |
1520 | uint64_t IsInline : 1; |
1521 | uint64_t IsInlineSpecified : 1; |
1522 | |
1523 | uint64_t IsVirtualAsWritten : 1; |
1524 | uint64_t IsPure : 1; |
1525 | uint64_t HasInheritedPrototype : 1; |
1526 | uint64_t HasWrittenPrototype : 1; |
1527 | uint64_t IsDeleted : 1; |
1528 | /// Used by CXXMethodDecl |
1529 | uint64_t IsTrivial : 1; |
1530 | |
1531 | /// This flag indicates whether this function is trivial for the purpose of |
1532 | /// calls. This is meaningful only when this function is a copy/move |
1533 | /// constructor or a destructor. |
1534 | uint64_t IsTrivialForCall : 1; |
1535 | |
1536 | uint64_t IsDefaulted : 1; |
1537 | uint64_t IsExplicitlyDefaulted : 1; |
1538 | uint64_t HasDefaultedFunctionInfo : 1; |
1539 | uint64_t HasImplicitReturnZero : 1; |
1540 | uint64_t IsLateTemplateParsed : 1; |
1541 | |
1542 | /// Kind of contexpr specifier as defined by ConstexprSpecKind. |
1543 | uint64_t ConstexprKind : 2; |
1544 | uint64_t InstantiationIsPending : 1; |
1545 | |
1546 | /// Indicates if the function uses __try. |
1547 | uint64_t UsesSEHTry : 1; |
1548 | |
1549 | /// Indicates if the function was a definition |
1550 | /// but its body was skipped. |
1551 | uint64_t HasSkippedBody : 1; |
1552 | |
1553 | /// Indicates if the function declaration will |
1554 | /// have a body, once we're done parsing it. |
1555 | uint64_t WillHaveBody : 1; |
1556 | |
1557 | /// Indicates that this function is a multiversioned |
1558 | /// function using attribute 'target'. |
1559 | uint64_t IsMultiVersion : 1; |
1560 | |
1561 | /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that |
1562 | /// the Deduction Guide is the implicitly generated 'copy |
1563 | /// deduction candidate' (is used during overload resolution). |
1564 | uint64_t IsCopyDeductionCandidate : 1; |
1565 | |
1566 | /// Store the ODRHash after first calculation. |
1567 | uint64_t HasODRHash : 1; |
1568 | |
1569 | /// Indicates if the function uses Floating Point Constrained Intrinsics |
1570 | uint64_t UsesFPIntrin : 1; |
1571 | }; |
1572 | |
1573 | /// Number of non-inherited bits in FunctionDeclBitfields. |
1574 | enum { NumFunctionDeclBits = 27 }; |
1575 | |
1576 | /// Stores the bits used by CXXConstructorDecl. If modified |
1577 | /// NumCXXConstructorDeclBits and the accessor |
1578 | /// methods in CXXConstructorDecl should be updated appropriately. |
1579 | class CXXConstructorDeclBitfields { |
1580 | friend class CXXConstructorDecl; |
1581 | /// For the bits in DeclContextBitfields. |
1582 | uint64_t : NumDeclContextBits; |
1583 | /// For the bits in FunctionDeclBitfields. |
1584 | uint64_t : NumFunctionDeclBits; |
1585 | |
1586 | /// 24 bits to fit in the remaining available space. |
1587 | /// Note that this makes CXXConstructorDeclBitfields take |
1588 | /// exactly 64 bits and thus the width of NumCtorInitializers |
1589 | /// will need to be shrunk if some bit is added to NumDeclContextBitfields, |
1590 | /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields. |
1591 | uint64_t NumCtorInitializers : 21; |
1592 | uint64_t IsInheritingConstructor : 1; |
1593 | |
1594 | /// Whether this constructor has a trail-allocated explicit specifier. |
1595 | uint64_t HasTrailingExplicitSpecifier : 1; |
1596 | /// If this constructor does't have a trail-allocated explicit specifier. |
1597 | /// Whether this constructor is explicit specified. |
1598 | uint64_t IsSimpleExplicit : 1; |
1599 | }; |
1600 | |
1601 | /// Number of non-inherited bits in CXXConstructorDeclBitfields. |
1602 | enum { |
1603 | NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits |
1604 | }; |
1605 | |
1606 | /// Stores the bits used by ObjCMethodDecl. |
1607 | /// If modified NumObjCMethodDeclBits and the accessor |
1608 | /// methods in ObjCMethodDecl should be updated appropriately. |
1609 | class ObjCMethodDeclBitfields { |
1610 | friend class ObjCMethodDecl; |
1611 | |
1612 | /// For the bits in DeclContextBitfields. |
1613 | uint64_t : NumDeclContextBits; |
1614 | |
1615 | /// The conventional meaning of this method; an ObjCMethodFamily. |
1616 | /// This is not serialized; instead, it is computed on demand and |
1617 | /// cached. |
1618 | mutable uint64_t Family : ObjCMethodFamilyBitWidth; |
1619 | |
1620 | /// instance (true) or class (false) method. |
1621 | uint64_t IsInstance : 1; |
1622 | uint64_t IsVariadic : 1; |
1623 | |
1624 | /// True if this method is the getter or setter for an explicit property. |
1625 | uint64_t IsPropertyAccessor : 1; |
1626 | |
1627 | /// True if this method is a synthesized property accessor stub. |
1628 | uint64_t IsSynthesizedAccessorStub : 1; |
1629 | |
1630 | /// Method has a definition. |
1631 | uint64_t IsDefined : 1; |
1632 | |
1633 | /// Method redeclaration in the same interface. |
1634 | uint64_t IsRedeclaration : 1; |
1635 | |
1636 | /// Is redeclared in the same interface. |
1637 | mutable uint64_t HasRedeclaration : 1; |
1638 | |
1639 | /// \@required/\@optional |
1640 | uint64_t DeclImplementation : 2; |
1641 | |
1642 | /// in, inout, etc. |
1643 | uint64_t objcDeclQualifier : 7; |
1644 | |
1645 | /// Indicates whether this method has a related result type. |
1646 | uint64_t RelatedResultType : 1; |
1647 | |
1648 | /// Whether the locations of the selector identifiers are in a |
1649 | /// "standard" position, a enum SelectorLocationsKind. |
1650 | uint64_t SelLocsKind : 2; |
1651 | |
1652 | /// Whether this method overrides any other in the class hierarchy. |
1653 | /// |
1654 | /// A method is said to override any method in the class's |
1655 | /// base classes, its protocols, or its categories' protocols, that has |
1656 | /// the same selector and is of the same kind (class or instance). |
1657 | /// A method in an implementation is not considered as overriding the same |
1658 | /// method in the interface or its categories. |
1659 | uint64_t IsOverriding : 1; |
1660 | |
1661 | /// Indicates if the method was a definition but its body was skipped. |
1662 | uint64_t HasSkippedBody : 1; |
1663 | }; |
1664 | |
1665 | /// Number of non-inherited bits in ObjCMethodDeclBitfields. |
1666 | enum { NumObjCMethodDeclBits = 24 }; |
1667 | |
1668 | /// Stores the bits used by ObjCContainerDecl. |
1669 | /// If modified NumObjCContainerDeclBits and the accessor |
1670 | /// methods in ObjCContainerDecl should be updated appropriately. |
1671 | class ObjCContainerDeclBitfields { |
1672 | friend class ObjCContainerDecl; |
1673 | /// For the bits in DeclContextBitfields |
1674 | uint32_t : NumDeclContextBits; |
1675 | |
1676 | // Not a bitfield but this saves space. |
1677 | // Note that ObjCContainerDeclBitfields is full. |
1678 | SourceLocation AtStart; |
1679 | }; |
1680 | |
1681 | /// Number of non-inherited bits in ObjCContainerDeclBitfields. |
1682 | /// Note that here we rely on the fact that SourceLocation is 32 bits |
1683 | /// wide. We check this with the static_assert in the ctor of DeclContext. |
1684 | enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits }; |
1685 | |
1686 | /// Stores the bits used by LinkageSpecDecl. |
1687 | /// If modified NumLinkageSpecDeclBits and the accessor |
1688 | /// methods in LinkageSpecDecl should be updated appropriately. |
1689 | class LinkageSpecDeclBitfields { |
1690 | friend class LinkageSpecDecl; |
1691 | /// For the bits in DeclContextBitfields. |
1692 | uint64_t : NumDeclContextBits; |
1693 | |
1694 | /// The language for this linkage specification with values |
1695 | /// in the enum LinkageSpecDecl::LanguageIDs. |
1696 | uint64_t Language : 3; |
1697 | |
1698 | /// True if this linkage spec has braces. |
1699 | /// This is needed so that hasBraces() returns the correct result while the |
1700 | /// linkage spec body is being parsed. Once RBraceLoc has been set this is |
1701 | /// not used, so it doesn't need to be serialized. |
1702 | uint64_t HasBraces : 1; |
1703 | }; |
1704 | |
1705 | /// Number of non-inherited bits in LinkageSpecDeclBitfields. |
1706 | enum { NumLinkageSpecDeclBits = 4 }; |
1707 | |
1708 | /// Stores the bits used by BlockDecl. |
1709 | /// If modified NumBlockDeclBits and the accessor |
1710 | /// methods in BlockDecl should be updated appropriately. |
1711 | class BlockDeclBitfields { |
1712 | friend class BlockDecl; |
1713 | /// For the bits in DeclContextBitfields. |
1714 | uint64_t : NumDeclContextBits; |
1715 | |
1716 | uint64_t IsVariadic : 1; |
1717 | uint64_t CapturesCXXThis : 1; |
1718 | uint64_t BlockMissingReturnType : 1; |
1719 | uint64_t IsConversionFromLambda : 1; |
1720 | |
1721 | /// A bit that indicates this block is passed directly to a function as a |
1722 | /// non-escaping parameter. |
1723 | uint64_t DoesNotEscape : 1; |
1724 | |
1725 | /// A bit that indicates whether it's possible to avoid coying this block to |
1726 | /// the heap when it initializes or is assigned to a local variable with |
1727 | /// automatic storage. |
1728 | uint64_t CanAvoidCopyToHeap : 1; |
1729 | }; |
1730 | |
1731 | /// Number of non-inherited bits in BlockDeclBitfields. |
1732 | enum { NumBlockDeclBits = 5 }; |
1733 | |
1734 | /// Pointer to the data structure used to lookup declarations |
1735 | /// within this context (or a DependentStoredDeclsMap if this is a |
1736 | /// dependent context). We maintain the invariant that, if the map |
1737 | /// contains an entry for a DeclarationName (and we haven't lazily |
1738 | /// omitted anything), then it contains all relevant entries for that |
1739 | /// name (modulo the hasExternalDecls() flag). |
1740 | mutable StoredDeclsMap *LookupPtr = nullptr; |
1741 | |
1742 | protected: |
1743 | /// This anonymous union stores the bits belonging to DeclContext and classes |
1744 | /// deriving from it. The goal is to use otherwise wasted |
1745 | /// space in DeclContext to store data belonging to derived classes. |
1746 | /// The space saved is especially significient when pointers are aligned |
1747 | /// to 8 bytes. In this case due to alignment requirements we have a |
1748 | /// little less than 8 bytes free in DeclContext which we can use. |
1749 | /// We check that none of the classes in this union is larger than |
1750 | /// 8 bytes with static_asserts in the ctor of DeclContext. |
1751 | union { |
1752 | DeclContextBitfields DeclContextBits; |
1753 | TagDeclBitfields TagDeclBits; |
1754 | EnumDeclBitfields EnumDeclBits; |
1755 | RecordDeclBitfields RecordDeclBits; |
1756 | OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits; |
1757 | FunctionDeclBitfields FunctionDeclBits; |
1758 | CXXConstructorDeclBitfields CXXConstructorDeclBits; |
1759 | ObjCMethodDeclBitfields ObjCMethodDeclBits; |
1760 | ObjCContainerDeclBitfields ObjCContainerDeclBits; |
1761 | LinkageSpecDeclBitfields LinkageSpecDeclBits; |
1762 | BlockDeclBitfields BlockDeclBits; |
1763 | |
1764 | static_assert(sizeof(DeclContextBitfields) <= 8, |
1765 | "DeclContextBitfields is larger than 8 bytes!"); |
1766 | static_assert(sizeof(TagDeclBitfields) <= 8, |
1767 | "TagDeclBitfields is larger than 8 bytes!"); |
1768 | static_assert(sizeof(EnumDeclBitfields) <= 8, |
1769 | "EnumDeclBitfields is larger than 8 bytes!"); |
1770 | static_assert(sizeof(RecordDeclBitfields) <= 8, |
1771 | "RecordDeclBitfields is larger than 8 bytes!"); |
1772 | static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8, |
1773 | "OMPDeclareReductionDeclBitfields is larger than 8 bytes!"); |
1774 | static_assert(sizeof(FunctionDeclBitfields) <= 8, |
1775 | "FunctionDeclBitfields is larger than 8 bytes!"); |
1776 | static_assert(sizeof(CXXConstructorDeclBitfields) <= 8, |
1777 | "CXXConstructorDeclBitfields is larger than 8 bytes!"); |
1778 | static_assert(sizeof(ObjCMethodDeclBitfields) <= 8, |
1779 | "ObjCMethodDeclBitfields is larger than 8 bytes!"); |
1780 | static_assert(sizeof(ObjCContainerDeclBitfields) <= 8, |
1781 | "ObjCContainerDeclBitfields is larger than 8 bytes!"); |
1782 | static_assert(sizeof(LinkageSpecDeclBitfields) <= 8, |
1783 | "LinkageSpecDeclBitfields is larger than 8 bytes!"); |
1784 | static_assert(sizeof(BlockDeclBitfields) <= 8, |
1785 | "BlockDeclBitfields is larger than 8 bytes!"); |
1786 | }; |
1787 | |
1788 | /// FirstDecl - The first declaration stored within this declaration |
1789 | /// context. |
1790 | mutable Decl *FirstDecl = nullptr; |
1791 | |
1792 | /// LastDecl - The last declaration stored within this declaration |
1793 | /// context. FIXME: We could probably cache this value somewhere |
1794 | /// outside of the DeclContext, to reduce the size of DeclContext by |
1795 | /// another pointer. |
1796 | mutable Decl *LastDecl = nullptr; |
1797 | |
1798 | /// Build up a chain of declarations. |
1799 | /// |
1800 | /// \returns the first/last pair of declarations. |
1801 | static std::pair<Decl *, Decl *> |
1802 | BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded); |
1803 | |
1804 | DeclContext(Decl::Kind K); |
1805 | |
1806 | public: |
1807 | ~DeclContext(); |
1808 | |
1809 | Decl::Kind getDeclKind() const { |
1810 | return static_cast<Decl::Kind>(DeclContextBits.DeclKind); |
1811 | } |
1812 | |
1813 | const char *getDeclKindName() const; |
1814 | |
1815 | /// getParent - Returns the containing DeclContext. |
1816 | DeclContext *getParent() { |
1817 | return cast<Decl>(this)->getDeclContext(); |
1818 | } |
1819 | const DeclContext *getParent() const { |
1820 | return const_cast<DeclContext*>(this)->getParent(); |
1821 | } |
1822 | |
1823 | /// getLexicalParent - Returns the containing lexical DeclContext. May be |
1824 | /// different from getParent, e.g.: |
1825 | /// |
1826 | /// namespace A { |
1827 | /// struct S; |
1828 | /// } |
1829 | /// struct A::S {}; // getParent() == namespace 'A' |
1830 | /// // getLexicalParent() == translation unit |
1831 | /// |
1832 | DeclContext *getLexicalParent() { |
1833 | return cast<Decl>(this)->getLexicalDeclContext(); |
1834 | } |
1835 | const DeclContext *getLexicalParent() const { |
1836 | return const_cast<DeclContext*>(this)->getLexicalParent(); |
1837 | } |
1838 | |
1839 | DeclContext *getLookupParent(); |
1840 | |
1841 | const DeclContext *getLookupParent() const { |
1842 | return const_cast<DeclContext*>(this)->getLookupParent(); |
1843 | } |
1844 | |
1845 | ASTContext &getParentASTContext() const { |
1846 | return cast<Decl>(this)->getASTContext(); |
1847 | } |
1848 | |
1849 | bool isClosure() const { return getDeclKind() == Decl::Block; } |
1850 | |
1851 | /// Return this DeclContext if it is a BlockDecl. Otherwise, return the |
1852 | /// innermost enclosing BlockDecl or null if there are no enclosing blocks. |
1853 | const BlockDecl *getInnermostBlockDecl() const; |
1854 | |
1855 | bool isObjCContainer() const { |
1856 | switch (getDeclKind()) { |
1857 | case Decl::ObjCCategory: |
1858 | case Decl::ObjCCategoryImpl: |
1859 | case Decl::ObjCImplementation: |
1860 | case Decl::ObjCInterface: |
1861 | case Decl::ObjCProtocol: |
1862 | return true; |
1863 | default: |
1864 | return false; |
1865 | } |
1866 | } |
1867 | |
1868 | bool isFunctionOrMethod() const { |
1869 | switch (getDeclKind()) { |
1870 | case Decl::Block: |
1871 | case Decl::Captured: |
1872 | case Decl::ObjCMethod: |
1873 | return true; |
1874 | default: |
1875 | return getDeclKind() >= Decl::firstFunction && |
1876 | getDeclKind() <= Decl::lastFunction; |
1877 | } |
1878 | } |
1879 | |
1880 | /// Test whether the context supports looking up names. |
1881 | bool isLookupContext() const { |
1882 | return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec && |
1883 | getDeclKind() != Decl::Export; |
1884 | } |
1885 | |
1886 | bool isFileContext() const { |
1887 | return getDeclKind() == Decl::TranslationUnit || |
1888 | getDeclKind() == Decl::Namespace; |
1889 | } |
1890 | |
1891 | bool isTranslationUnit() const { |
1892 | return getDeclKind() == Decl::TranslationUnit; |
1893 | } |
1894 | |
1895 | bool isRecord() const { |
1896 | return getDeclKind() >= Decl::firstRecord && |
1897 | getDeclKind() <= Decl::lastRecord; |
1898 | } |
1899 | |
1900 | bool isNamespace() const { return getDeclKind() == Decl::Namespace; } |
1901 | |
1902 | bool isStdNamespace() const; |
1903 | |
1904 | bool isInlineNamespace() const; |
1905 | |
1906 | /// Determines whether this context is dependent on a |
1907 | /// template parameter. |
1908 | bool isDependentContext() const; |
1909 | |
1910 | /// isTransparentContext - Determines whether this context is a |
1911 | /// "transparent" context, meaning that the members declared in this |
1912 | /// context are semantically declared in the nearest enclosing |
1913 | /// non-transparent (opaque) context but are lexically declared in |
1914 | /// this context. For example, consider the enumerators of an |
1915 | /// enumeration type: |
1916 | /// @code |
1917 | /// enum E { |
1918 | /// Val1 |
1919 | /// }; |
1920 | /// @endcode |
1921 | /// Here, E is a transparent context, so its enumerator (Val1) will |
1922 | /// appear (semantically) that it is in the same context of E. |
1923 | /// Examples of transparent contexts include: enumerations (except for |
1924 | /// C++0x scoped enums), and C++ linkage specifications. |
1925 | bool isTransparentContext() const; |
1926 | |
1927 | /// Determines whether this context or some of its ancestors is a |
1928 | /// linkage specification context that specifies C linkage. |
1929 | bool isExternCContext() const; |
1930 | |
1931 | /// Retrieve the nearest enclosing C linkage specification context. |
1932 | const LinkageSpecDecl *getExternCContext() const; |
1933 | |
1934 | /// Determines whether this context or some of its ancestors is a |
1935 | /// linkage specification context that specifies C++ linkage. |
1936 | bool isExternCXXContext() const; |
1937 | |
1938 | /// Determine whether this declaration context is equivalent |
1939 | /// to the declaration context DC. |
1940 | bool Equals(const DeclContext *DC) const { |
1941 | return DC && this->getPrimaryContext() == DC->getPrimaryContext(); |
1942 | } |
1943 | |
1944 | /// Determine whether this declaration context encloses the |
1945 | /// declaration context DC. |
1946 | bool Encloses(const DeclContext *DC) const; |
1947 | |
1948 | /// Find the nearest non-closure ancestor of this context, |
1949 | /// i.e. the innermost semantic parent of this context which is not |
1950 | /// a closure. A context may be its own non-closure ancestor. |
1951 | Decl *getNonClosureAncestor(); |
1952 | const Decl *getNonClosureAncestor() const { |
1953 | return const_cast<DeclContext*>(this)->getNonClosureAncestor(); |
1954 | } |
1955 | |
1956 | /// getPrimaryContext - There may be many different |
1957 | /// declarations of the same entity (including forward declarations |
1958 | /// of classes, multiple definitions of namespaces, etc.), each with |
1959 | /// a different set of declarations. This routine returns the |
1960 | /// "primary" DeclContext structure, which will contain the |
1961 | /// information needed to perform name lookup into this context. |
1962 | DeclContext *getPrimaryContext(); |
1963 | const DeclContext *getPrimaryContext() const { |
1964 | return const_cast<DeclContext*>(this)->getPrimaryContext(); |
1965 | } |
1966 | |
1967 | /// getRedeclContext - Retrieve the context in which an entity conflicts with |
1968 | /// other entities of the same name, or where it is a redeclaration if the |
1969 | /// two entities are compatible. This skips through transparent contexts. |
1970 | DeclContext *getRedeclContext(); |
1971 | const DeclContext *getRedeclContext() const { |
1972 | return const_cast<DeclContext *>(this)->getRedeclContext(); |
1973 | } |
1974 | |
1975 | /// Retrieve the nearest enclosing namespace context. |
1976 | DeclContext *getEnclosingNamespaceContext(); |
1977 | const DeclContext *getEnclosingNamespaceContext() const { |
1978 | return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext(); |
1979 | } |
1980 | |
1981 | /// Retrieve the outermost lexically enclosing record context. |
1982 | RecordDecl *getOuterLexicalRecordContext(); |
1983 | const RecordDecl *getOuterLexicalRecordContext() const { |
1984 | return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext(); |
1985 | } |
1986 | |
1987 | /// Test if this context is part of the enclosing namespace set of |
1988 | /// the context NS, as defined in C++0x [namespace.def]p9. If either context |
1989 | /// isn't a namespace, this is equivalent to Equals(). |
1990 | /// |
1991 | /// The enclosing namespace set of a namespace is the namespace and, if it is |
1992 | /// inline, its enclosing namespace, recursively. |
1993 | bool InEnclosingNamespaceSetOf(const DeclContext *NS) const; |
1994 | |
1995 | /// Collects all of the declaration contexts that are semantically |
1996 | /// connected to this declaration context. |
1997 | /// |
1998 | /// For declaration contexts that have multiple semantically connected but |
1999 | /// syntactically distinct contexts, such as C++ namespaces, this routine |
2000 | /// retrieves the complete set of such declaration contexts in source order. |
2001 | /// For example, given: |
2002 | /// |
2003 | /// \code |
2004 | /// namespace N { |
2005 | /// int x; |
2006 | /// } |
2007 | /// namespace N { |
2008 | /// int y; |
2009 | /// } |
2010 | /// \endcode |
2011 | /// |
2012 | /// The \c Contexts parameter will contain both definitions of N. |
2013 | /// |
2014 | /// \param Contexts Will be cleared and set to the set of declaration |
2015 | /// contexts that are semanticaly connected to this declaration context, |
2016 | /// in source order, including this context (which may be the only result, |
2017 | /// for non-namespace contexts). |
2018 | void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts); |
2019 | |
2020 | /// decl_iterator - Iterates through the declarations stored |
2021 | /// within this context. |
2022 | class decl_iterator { |
2023 | /// Current - The current declaration. |
2024 | Decl *Current = nullptr; |
2025 | |
2026 | public: |
2027 | using value_type = Decl *; |
2028 | using reference = const value_type &; |
2029 | using pointer = const value_type *; |
2030 | using iterator_category = std::forward_iterator_tag; |
2031 | using difference_type = std::ptrdiff_t; |
2032 | |
2033 | decl_iterator() = default; |
2034 | explicit decl_iterator(Decl *C) : Current(C) {} |
2035 | |
2036 | reference operator*() const { return Current; } |
2037 | |
2038 | // This doesn't meet the iterator requirements, but it's convenient |
2039 | value_type operator->() const { return Current; } |
2040 | |
2041 | decl_iterator& operator++() { |
2042 | Current = Current->getNextDeclInContext(); |
2043 | return *this; |
2044 | } |
2045 | |
2046 | decl_iterator operator++(int) { |
2047 | decl_iterator tmp(*this); |
2048 | ++(*this); |
2049 | return tmp; |
2050 | } |
2051 | |
2052 | friend bool operator==(decl_iterator x, decl_iterator y) { |
2053 | return x.Current == y.Current; |
2054 | } |
2055 | |
2056 | friend bool operator!=(decl_iterator x, decl_iterator y) { |
2057 | return x.Current != y.Current; |
2058 | } |
2059 | }; |
2060 | |
2061 | using decl_range = llvm::iterator_range<decl_iterator>; |
2062 | |
2063 | /// decls_begin/decls_end - Iterate over the declarations stored in |
2064 | /// this context. |
2065 | decl_range decls() const { return decl_range(decls_begin(), decls_end()); } |
2066 | decl_iterator decls_begin() const; |
2067 | decl_iterator decls_end() const { return decl_iterator(); } |
2068 | bool decls_empty() const; |
2069 | |
2070 | /// noload_decls_begin/end - Iterate over the declarations stored in this |
2071 | /// context that are currently loaded; don't attempt to retrieve anything |
2072 | /// from an external source. |
2073 | decl_range noload_decls() const { |
2074 | return decl_range(noload_decls_begin(), noload_decls_end()); |
2075 | } |
2076 | decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); } |
2077 | decl_iterator noload_decls_end() const { return decl_iterator(); } |
2078 | |
2079 | /// specific_decl_iterator - Iterates over a subrange of |
2080 | /// declarations stored in a DeclContext, providing only those that |
2081 | /// are of type SpecificDecl (or a class derived from it). This |
2082 | /// iterator is used, for example, to provide iteration over just |
2083 | /// the fields within a RecordDecl (with SpecificDecl = FieldDecl). |
2084 | template<typename SpecificDecl> |
2085 | class specific_decl_iterator { |
2086 | /// Current - The current, underlying declaration iterator, which |
2087 | /// will either be NULL or will point to a declaration of |
2088 | /// type SpecificDecl. |
2089 | DeclContext::decl_iterator Current; |
2090 | |
2091 | /// SkipToNextDecl - Advances the current position up to the next |
2092 | /// declaration of type SpecificDecl that also meets the criteria |
2093 | /// required by Acceptable. |
2094 | void SkipToNextDecl() { |
2095 | while (*Current && !isa<SpecificDecl>(*Current)) |
2096 | ++Current; |
2097 | } |
2098 | |
2099 | public: |
2100 | using value_type = SpecificDecl *; |
2101 | // TODO: Add reference and pointer types (with some appropriate proxy type) |
2102 | // if we ever have a need for them. |
2103 | using reference = void; |
2104 | using pointer = void; |
2105 | using difference_type = |
2106 | std::iterator_traits<DeclContext::decl_iterator>::difference_type; |
2107 | using iterator_category = std::forward_iterator_tag; |
2108 | |
2109 | specific_decl_iterator() = default; |
2110 | |
2111 | /// specific_decl_iterator - Construct a new iterator over a |
2112 | /// subset of the declarations the range [C, |
2113 | /// end-of-declarations). If A is non-NULL, it is a pointer to a |
2114 | /// member function of SpecificDecl that should return true for |
2115 | /// all of the SpecificDecl instances that will be in the subset |
2116 | /// of iterators. For example, if you want Objective-C instance |
2117 | /// methods, SpecificDecl will be ObjCMethodDecl and A will be |
2118 | /// &ObjCMethodDecl::isInstanceMethod. |
2119 | explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) { |
2120 | SkipToNextDecl(); |
2121 | } |
2122 | |
2123 | value_type operator*() const { return cast<SpecificDecl>(*Current); } |
2124 | |
2125 | // This doesn't meet the iterator requirements, but it's convenient |
2126 | value_type operator->() const { return **this; } |
2127 | |
2128 | specific_decl_iterator& operator++() { |
2129 | ++Current; |
2130 | SkipToNextDecl(); |
2131 | return *this; |
2132 | } |
2133 | |
2134 | specific_decl_iterator operator++(int) { |
2135 | specific_decl_iterator tmp(*this); |
2136 | ++(*this); |
2137 | return tmp; |
2138 | } |
2139 | |
2140 | friend bool operator==(const specific_decl_iterator& x, |
2141 | const specific_decl_iterator& y) { |
2142 | return x.Current == y.Current; |
2143 | } |
2144 | |
2145 | friend bool operator!=(const specific_decl_iterator& x, |
2146 | const specific_decl_iterator& y) { |
2147 | return x.Current != y.Current; |
2148 | } |
2149 | }; |
2150 | |
2151 | /// Iterates over a filtered subrange of declarations stored |
2152 | /// in a DeclContext. |
2153 | /// |
2154 | /// This iterator visits only those declarations that are of type |
2155 | /// SpecificDecl (or a class derived from it) and that meet some |
2156 | /// additional run-time criteria. This iterator is used, for |
2157 | /// example, to provide access to the instance methods within an |
2158 | /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and |
2159 | /// Acceptable = ObjCMethodDecl::isInstanceMethod). |
2160 | template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const> |
2161 | class filtered_decl_iterator { |
2162 | /// Current - The current, underlying declaration iterator, which |
2163 | /// will either be NULL or will point to a declaration of |
2164 | /// type SpecificDecl. |
2165 | DeclContext::decl_iterator Current; |
2166 | |
2167 | /// SkipToNextDecl - Advances the current position up to the next |
2168 | /// declaration of type SpecificDecl that also meets the criteria |
2169 | /// required by Acceptable. |
2170 | void SkipToNextDecl() { |
2171 | while (*Current && |
2172 | (!isa<SpecificDecl>(*Current) || |
2173 | (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)()))) |
2174 | ++Current; |
2175 | } |
2176 | |
2177 | public: |
2178 | using value_type = SpecificDecl *; |
2179 | // TODO: Add reference and pointer types (with some appropriate proxy type) |
2180 | // if we ever have a need for them. |
2181 | using reference = void; |
2182 | using pointer = void; |
2183 | using difference_type = |
2184 | std::iterator_traits<DeclContext::decl_iterator>::difference_type; |
2185 | using iterator_category = std::forward_iterator_tag; |
2186 | |
2187 | filtered_decl_iterator() = default; |
2188 | |
2189 | /// filtered_decl_iterator - Construct a new iterator over a |
2190 | /// subset of the declarations the range [C, |
2191 | /// end-of-declarations). If A is non-NULL, it is a pointer to a |
2192 | /// member function of SpecificDecl that should return true for |
2193 | /// all of the SpecificDecl instances that will be in the subset |
2194 | /// of iterators. For example, if you want Objective-C instance |
2195 | /// methods, SpecificDecl will be ObjCMethodDecl and A will be |
2196 | /// &ObjCMethodDecl::isInstanceMethod. |
2197 | explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) { |
2198 | SkipToNextDecl(); |
2199 | } |
2200 | |
2201 | value_type operator*() const { return cast<SpecificDecl>(*Current); } |
2202 | value_type operator->() const { return cast<SpecificDecl>(*Current); } |
2203 | |
2204 | filtered_decl_iterator& operator++() { |
2205 | ++Current; |
2206 | SkipToNextDecl(); |
2207 | return *this; |
2208 | } |
2209 | |
2210 | filtered_decl_iterator operator++(int) { |
2211 | filtered_decl_iterator tmp(*this); |
2212 | ++(*this); |
2213 | return tmp; |
2214 | } |
2215 | |
2216 | friend bool operator==(const filtered_decl_iterator& x, |
2217 | const filtered_decl_iterator& y) { |
2218 | return x.Current == y.Current; |
2219 | } |
2220 | |
2221 | friend bool operator!=(const filtered_decl_iterator& x, |
2222 | const filtered_decl_iterator& y) { |
2223 | return x.Current != y.Current; |
2224 | } |
2225 | }; |
2226 | |
2227 | /// Add the declaration D into this context. |
2228 | /// |
2229 | /// This routine should be invoked when the declaration D has first |
2230 | /// been declared, to place D into the context where it was |
2231 | /// (lexically) defined. Every declaration must be added to one |
2232 | /// (and only one!) context, where it can be visited via |
2233 | /// [decls_begin(), decls_end()). Once a declaration has been added |
2234 | /// to its lexical context, the corresponding DeclContext owns the |
2235 | /// declaration. |
2236 | /// |
2237 | /// If D is also a NamedDecl, it will be made visible within its |
2238 | /// semantic context via makeDeclVisibleInContext. |
2239 | void addDecl(Decl *D); |
2240 | |
2241 | /// Add the declaration D into this context, but suppress |
2242 | /// searches for external declarations with the same name. |
2243 | /// |
2244 | /// Although analogous in function to addDecl, this removes an |
2245 | /// important check. This is only useful if the Decl is being |
2246 | /// added in response to an external search; in all other cases, |
2247 | /// addDecl() is the right function to use. |
2248 | /// See the ASTImporter for use cases. |
2249 | void addDeclInternal(Decl *D); |
2250 | |
2251 | /// Add the declaration D to this context without modifying |
2252 | /// any lookup tables. |
2253 | /// |
2254 | /// This is useful for some operations in dependent contexts where |
2255 | /// the semantic context might not be dependent; this basically |
2256 | /// only happens with friends. |
2257 | void addHiddenDecl(Decl *D); |
2258 | |
2259 | /// Removes a declaration from this context. |
2260 | void removeDecl(Decl *D); |
2261 | |
2262 | /// Checks whether a declaration is in this context. |
2263 | bool containsDecl(Decl *D) const; |
2264 | |
2265 | /// Checks whether a declaration is in this context. |
2266 | /// This also loads the Decls from the external source before the check. |
2267 | bool containsDeclAndLoad(Decl *D) const; |
2268 | |
2269 | using lookup_result = DeclContextLookupResult; |
2270 | using lookup_iterator = lookup_result::iterator; |
2271 | |
2272 | /// lookup - Find the declarations (if any) with the given Name in |
2273 | /// this context. Returns a range of iterators that contains all of |
2274 | /// the declarations with this name, with object, function, member, |
2275 | /// and enumerator names preceding any tag name. Note that this |
2276 | /// routine will not look into parent contexts. |
2277 | lookup_result lookup(DeclarationName Name) const; |
2278 | |
2279 | /// Find the declarations with the given name that are visible |
2280 | /// within this context; don't attempt to retrieve anything from an |
2281 | /// external source. |
2282 | lookup_result noload_lookup(DeclarationName Name); |
2283 | |
2284 | /// A simplistic name lookup mechanism that performs name lookup |
2285 | /// into this declaration context without consulting the external source. |
2286 | /// |
2287 | /// This function should almost never be used, because it subverts the |
2288 | /// usual relationship between a DeclContext and the external source. |
2289 | /// See the ASTImporter for the (few, but important) use cases. |
2290 | /// |
2291 | /// FIXME: This is very inefficient; replace uses of it with uses of |
2292 | /// noload_lookup. |
2293 | void localUncachedLookup(DeclarationName Name, |
2294 | SmallVectorImpl<NamedDecl *> &Results); |
2295 | |
2296 | /// Makes a declaration visible within this context. |
2297 | /// |
2298 | /// This routine makes the declaration D visible to name lookup |
2299 | /// within this context and, if this is a transparent context, |
2300 | /// within its parent contexts up to the first enclosing |
2301 | /// non-transparent context. Making a declaration visible within a |
2302 | /// context does not transfer ownership of a declaration, and a |
2303 | /// declaration can be visible in many contexts that aren't its |
2304 | /// lexical context. |
2305 | /// |
2306 | /// If D is a redeclaration of an existing declaration that is |
2307 | /// visible from this context, as determined by |
2308 | /// NamedDecl::declarationReplaces, the previous declaration will be |
2309 | /// replaced with D. |
2310 | void makeDeclVisibleInContext(NamedDecl *D); |
2311 | |
2312 | /// all_lookups_iterator - An iterator that provides a view over the results |
2313 | /// of looking up every possible name. |
2314 | class all_lookups_iterator; |
2315 | |
2316 | using lookups_range = llvm::iterator_range<all_lookups_iterator>; |
2317 | |
2318 | lookups_range lookups() const; |
2319 | // Like lookups(), but avoids loading external declarations. |
2320 | // If PreserveInternalState, avoids building lookup data structures too. |
2321 | lookups_range noload_lookups(bool PreserveInternalState) const; |
2322 | |
2323 | /// Iterators over all possible lookups within this context. |
2324 | all_lookups_iterator lookups_begin() const; |
2325 | all_lookups_iterator lookups_end() const; |
2326 | |
2327 | /// Iterators over all possible lookups within this context that are |
2328 | /// currently loaded; don't attempt to retrieve anything from an external |
2329 | /// source. |
2330 | all_lookups_iterator noload_lookups_begin() const; |
2331 | all_lookups_iterator noload_lookups_end() const; |
2332 | |
2333 | struct udir_iterator; |
2334 | |
2335 | using udir_iterator_base = |
2336 | llvm::iterator_adaptor_base<udir_iterator, lookup_iterator, |
2337 | std::random_access_iterator_tag, |
2338 | UsingDirectiveDecl *>; |
2339 | |
2340 | struct udir_iterator : udir_iterator_base { |
2341 | udir_iterator(lookup_iterator I) : udir_iterator_base(I) {} |
2342 | |
2343 | UsingDirectiveDecl *operator*() const; |
2344 | }; |
2345 | |
2346 | using udir_range = llvm::iterator_range<udir_iterator>; |
2347 | |
2348 | udir_range using_directives() const; |
2349 | |
2350 | // These are all defined in DependentDiagnostic.h. |
2351 | class ddiag_iterator; |
2352 | |
2353 | using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>; |
2354 | |
2355 | inline ddiag_range ddiags() const; |
2356 | |
2357 | // Low-level accessors |
2358 | |
2359 | /// Mark that there are external lexical declarations that we need |
2360 | /// to include in our lookup table (and that are not available as external |
2361 | /// visible lookups). These extra lookup results will be found by walking |
2362 | /// the lexical declarations of this context. This should be used only if |
2363 | /// setHasExternalLexicalStorage() has been called on any decl context for |
2364 | /// which this is the primary context. |
2365 | void setMustBuildLookupTable() { |
2366 | assert(this == getPrimaryContext() &&((this == getPrimaryContext() && "should only be called on primary context" ) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 2367, __PRETTY_FUNCTION__)) |
2367 | "should only be called on primary context")((this == getPrimaryContext() && "should only be called on primary context" ) ? static_cast<void> (0) : __assert_fail ("this == getPrimaryContext() && \"should only be called on primary context\"" , "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/DeclBase.h" , 2367, __PRETTY_FUNCTION__)); |
2368 | DeclContextBits.HasLazyExternalLexicalLookups = true; |
2369 | } |
2370 | |
2371 | /// Retrieve the internal representation of the lookup structure. |
2372 | /// This may omit some names if we are lazily building the structure. |
2373 | StoredDeclsMap *getLookupPtr() const { return LookupPtr; } |
2374 | |
2375 | /// Ensure the lookup structure is fully-built and return it. |
2376 | StoredDeclsMap *buildLookup(); |
2377 | |
2378 | /// Whether this DeclContext has external storage containing |
2379 | /// additional declarations that are lexically in this context. |
2380 | bool hasExternalLexicalStorage() const { |
2381 | return DeclContextBits.ExternalLexicalStorage; |
2382 | } |
2383 | |
2384 | /// State whether this DeclContext has external storage for |
2385 | /// declarations lexically in this context. |
2386 | void setHasExternalLexicalStorage(bool ES = true) const { |
2387 | DeclContextBits.ExternalLexicalStorage = ES; |
2388 | } |
2389 | |
2390 | /// Whether this DeclContext has external storage containing |
2391 | /// additional declarations that are visible in this context. |
2392 | bool hasExternalVisibleStorage() const { |
2393 | return DeclContextBits.ExternalVisibleStorage; |
2394 | } |
2395 | |
2396 | /// State whether this DeclContext has external storage for |
2397 | /// declarations visible in this context. |
2398 | void setHasExternalVisibleStorage(bool ES = true) const { |
2399 | DeclContextBits.ExternalVisibleStorage = ES; |
2400 | if (ES && LookupPtr) |
2401 | DeclContextBits.NeedToReconcileExternalVisibleStorage = true; |
2402 | } |
2403 | |
2404 | /// Determine whether the given declaration is stored in the list of |
2405 | /// declarations lexically within this context. |
2406 | bool isDeclInLexicalTraversal(const Decl *D) const { |
2407 | return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl || |
2408 | D == LastDecl); |
2409 | } |
2410 | |
2411 | bool setUseQualifiedLookup(bool use = true) const { |
2412 | bool old_value = DeclContextBits.UseQualifiedLookup; |
2413 | DeclContextBits.UseQualifiedLookup = use; |
2414 | return old_value; |
2415 | } |
2416 | |
2417 | bool shouldUseQualifiedLookup() const { |
2418 | return DeclContextBits.UseQualifiedLookup; |
2419 | } |
2420 | |
2421 | static bool classof(const Decl *D); |
2422 | static bool classof(const DeclContext *D) { return true; } |
2423 | |
2424 | void dumpDeclContext() const; |
2425 | void dumpLookups() const; |
2426 | void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false, |
2427 | bool Deserialize = false) const; |
2428 | |
2429 | private: |
2430 | /// Whether this declaration context has had externally visible |
2431 | /// storage added since the last lookup. In this case, \c LookupPtr's |
2432 | /// invariant may not hold and needs to be fixed before we perform |
2433 | /// another lookup. |
2434 | bool hasNeedToReconcileExternalVisibleStorage() const { |
2435 | return DeclContextBits.NeedToReconcileExternalVisibleStorage; |
2436 | } |
2437 | |
2438 | /// State that this declaration context has had externally visible |
2439 | /// storage added since the last lookup. In this case, \c LookupPtr's |
2440 | /// invariant may not hold and needs to be fixed before we perform |
2441 | /// another lookup. |
2442 | void setNeedToReconcileExternalVisibleStorage(bool Need = true) const { |
2443 | DeclContextBits.NeedToReconcileExternalVisibleStorage = Need; |
2444 | } |
2445 | |
2446 | /// If \c true, this context may have local lexical declarations |
2447 | /// that are missing from the lookup table. |
2448 | bool hasLazyLocalLexicalLookups() const { |
2449 | return DeclContextBits.HasLazyLocalLexicalLookups; |
2450 | } |
2451 | |
2452 | /// If \c true, this context may have local lexical declarations |
2453 | /// that are missing from the lookup table. |
2454 | void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const { |
2455 | DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL; |
2456 | } |
2457 | |
2458 | /// If \c true, the external source may have lexical declarations |
2459 | /// that are missing from the lookup table. |
2460 | bool hasLazyExternalLexicalLookups() const { |
2461 | return DeclContextBits.HasLazyExternalLexicalLookups; |
2462 | } |
2463 | |
2464 | /// If \c true, the external source may have lexical declarations |
2465 | /// that are missing from the lookup table. |
2466 | void setHasLazyExternalLexicalLookups(bool HasLELL = true) const { |
2467 | DeclContextBits.HasLazyExternalLexicalLookups = HasLELL; |
2468 | } |
2469 | |
2470 | void reconcileExternalVisibleStorage() const; |
2471 | bool LoadLexicalDeclsFromExternalStorage() const; |
2472 | |
2473 | /// Makes a declaration visible within this context, but |
2474 | /// suppresses searches for external declarations with the same |
2475 | /// name. |
2476 | /// |
2477 | /// Analogous to makeDeclVisibleInContext, but for the exclusive |
2478 | /// use of addDeclInternal(). |
2479 | void makeDeclVisibleInContextInternal(NamedDecl *D); |
2480 | |
2481 | StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const; |
2482 | |
2483 | void loadLazyLocalLexicalLookups(); |
2484 | void buildLookupImpl(DeclContext *DCtx, bool Internal); |
2485 | void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, |
2486 | bool Rediscoverable); |
2487 | void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal); |
2488 | }; |
2489 | |
2490 | inline bool Decl::isTemplateParameter() const { |
2491 | return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm || |
2492 | getKind() == TemplateTemplateParm; |
2493 | } |
2494 | |
2495 | // Specialization selected when ToTy is not a known subclass of DeclContext. |
2496 | template <class ToTy, |
2497 | bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value> |
2498 | struct cast_convert_decl_context { |
2499 | static const ToTy *doit(const DeclContext *Val) { |
2500 | return static_cast<const ToTy*>(Decl::castFromDeclContext(Val)); |
2501 | } |
2502 | |
2503 | static ToTy *doit(DeclContext *Val) { |
2504 | return static_cast<ToTy*>(Decl::castFromDeclContext(Val)); |
2505 | } |
2506 | }; |
2507 | |
2508 | // Specialization selected when ToTy is a known subclass of DeclContext. |
2509 | template <class ToTy> |
2510 | struct cast_convert_decl_context<ToTy, true> { |
2511 | static const ToTy *doit(const DeclContext *Val) { |
2512 | return static_cast<const ToTy*>(Val); |
2513 | } |
2514 | |
2515 | static ToTy *doit(DeclContext *Val) { |
2516 | return static_cast<ToTy*>(Val); |
2517 | } |
2518 | }; |
2519 | |
2520 | } // namespace clang |
2521 | |
2522 | namespace llvm { |
2523 | |
2524 | /// isa<T>(DeclContext*) |
2525 | template <typename To> |
2526 | struct isa_impl<To, ::clang::DeclContext> { |
2527 | static bool doit(const ::clang::DeclContext &Val) { |
2528 | return To::classofKind(Val.getDeclKind()); |
2529 | } |
2530 | }; |
2531 | |
2532 | /// cast<T>(DeclContext*) |
2533 | template<class ToTy> |
2534 | struct cast_convert_val<ToTy, |
2535 | const ::clang::DeclContext,const ::clang::DeclContext> { |
2536 | static const ToTy &doit(const ::clang::DeclContext &Val) { |
2537 | return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); |
2538 | } |
2539 | }; |
2540 | |
2541 | template<class ToTy> |
2542 | struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> { |
2543 | static ToTy &doit(::clang::DeclContext &Val) { |
2544 | return *::clang::cast_convert_decl_context<ToTy>::doit(&Val); |
2545 | } |
2546 | }; |
2547 | |
2548 | template<class ToTy> |
2549 | struct cast_convert_val<ToTy, |
2550 | const ::clang::DeclContext*, const ::clang::DeclContext*> { |
2551 | static const ToTy *doit(const ::clang::DeclContext *Val) { |
2552 | return ::clang::cast_convert_decl_context<ToTy>::doit(Val); |
2553 | } |
2554 | }; |
2555 | |
2556 | template<class ToTy> |
2557 | struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> { |
2558 | static ToTy *doit(::clang::DeclContext *Val) { |
2559 | return ::clang::cast_convert_decl_context<ToTy>::doit(Val); |
2560 | } |
2561 | }; |
2562 | |
2563 | /// Implement cast_convert_val for Decl -> DeclContext conversions. |
2564 | template<class FromTy> |
2565 | struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> { |
2566 | static ::clang::DeclContext &doit(const FromTy &Val) { |
2567 | return *FromTy::castToDeclContext(&Val); |
2568 | } |
2569 | }; |
2570 | |
2571 | template<class FromTy> |
2572 | struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> { |
2573 | static ::clang::DeclContext *doit(const FromTy *Val) { |
2574 | return FromTy::castToDeclContext(Val); |
2575 | } |
2576 | }; |
2577 | |
2578 | template<class FromTy> |
2579 | struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> { |
2580 | static const ::clang::DeclContext &doit(const FromTy &Val) { |
2581 | return *FromTy::castToDeclContext(&Val); |
2582 | } |
2583 | }; |
2584 | |
2585 | template<class FromTy> |
2586 | struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> { |
2587 | static const ::clang::DeclContext *doit(const FromTy *Val) { |
2588 | return FromTy::castToDeclContext(Val); |
2589 | } |
2590 | }; |
2591 | |
2592 | } // namespace llvm |
2593 | |
2594 | #endif // LLVM_CLANG_AST_DECLBASE_H |